Browse Source

Up to Part 4

PeterMcCormick 8 years ago
parent
commit
005fe1dc86

+ 38
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/controller/VoteController.java View File

@@ -0,0 +1,38 @@
1
+package io.zipcoder.tc_spring_poll_application.controller;
2
+
3
+import io.zipcoder.tc_spring_poll_application.domain.Vote;
4
+import io.zipcoder.tc_spring_poll_application.repositories.VoteRepository;
5
+import org.springframework.http.HttpHeaders;
6
+import org.springframework.http.HttpStatus;
7
+import org.springframework.http.ResponseEntity;
8
+import org.springframework.web.bind.annotation.*;
9
+import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
10
+
11
+import javax.inject.Inject;
12
+
13
+@RestController
14
+public class VoteController {
15
+    @Inject
16
+    private VoteRepository voteRepository;
17
+
18
+    @RequestMapping(value = "/polls/{pollId}/votes", method = RequestMethod.POST)
19
+    public ResponseEntity<?> createVote(@PathVariable Long pollId, @RequestBody Vote
20
+            vote) {
21
+        vote = voteRepository.save(vote);
22
+        // Set the headers for the newly created resource
23
+        HttpHeaders responseHeaders = new HttpHeaders();
24
+        responseHeaders.setLocation(ServletUriComponentsBuilder.
25
+                fromCurrentRequest().path("/{id}").buildAndExpand(vote.getId()).toUri());
26
+        return new ResponseEntity<>(null, responseHeaders, HttpStatus.CREATED);
27
+    }
28
+
29
+    @RequestMapping(value="/polls/{pollId}/votes", method=RequestMethod.GET)
30
+    public Iterable<Vote> getAllVotes() {
31
+        return voteRepository.findAll();
32
+    }
33
+
34
+    @RequestMapping(value="/polls/{pollId}/votes", method=RequestMethod.GET)
35
+    public Iterable<Vote> getVote(@PathVariable Long pollId) {
36
+        return voteRepository.findVotesByPoll(pollId);
37
+    }
38
+}

+ 6
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/repositories/VoteRepository.java View File

@@ -1,8 +1,14 @@
1 1
 package io.zipcoder.tc_spring_poll_application.repositories;
2 2
 
3 3
 import io.zipcoder.tc_spring_poll_application.domain.Vote;
4
+import org.springframework.data.jpa.repository.Query;
4 5
 import org.springframework.data.repository.CrudRepository;
5 6
 
6 7
 public interface VoteRepository extends CrudRepository<Vote, Long>{
7 8
 
9
+    @Query(value = "SELECT v.* " +
10
+            "FROM Option o, Vote v " +
11
+            "WHERE o.POLL_ID = ?1 " +
12
+            "AND v.OPTION_ID = o.OPTION_ID", nativeQuery = true)
13
+    public Iterable<Vote> findVotesByPoll(Long pollId);
8 14
 }