CWinarski 8 лет назад
Родитель
Сommit
f0d3174e5b

+ 41
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/controller/VoteController.java Просмотреть файл

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

+ 7
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/repositories/VoteRepository.java Просмотреть файл

@@ -1,9 +1,16 @@
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
     //these are DAOs pr Data Access Objects they provide abstraction for interacting with data stores
8 9
     // ypu have usually one repository per domain object
10
+
11
+    @Query(value = "SELECT v.* " +
12
+            "FROM Option o, Vote v " +
13
+            "WHERE o.POLL_ID = ?1 " +
14
+            "AND v.OPTION_ID = o.OPTION_ID", nativeQuery = true)
15
+    public Iterable<Vote> findVotesByPoll(Long pollId);
9 16
 }