Leon fc4dfcb4f1 added file `import.sql` to `src/main/resources` | 7 gadus atpakaļ | |
---|---|---|
src | 7 gadus atpakaļ | |
.gitignore | 7 gadus atpakaļ | |
README.md | 7 gadus atpakaļ | |
pom.xml | 7 gadus atpakaļ |
io.zipcoder.tc_spring_poll_application
named domain
.-
Option
Option
class in the domain
sub-package.Option
class signature is annotated with @Entity
Option
has an id
instance variable of type Long
id
should be annotated
with
@Id
@GeneratedValue
column(field)
@Column(name = "OPTION_ID")
Option
has a value
instance variable of type String
value
should be annotated
with
@Column(name = "OPTION_VALUE")
Create a getter
and setter
for each of the respective instance variables.
-
Poll
Poll
class in the domain
sub-package.Poll
class signature is annotated with @Entity
Poll
has an id
instance variable of type Long
id
should be annotated
with
@Id
@GeneratedValue
Column(name = "POLL_ID")
Poll
has a question
instance variable of type String
question
should be annotated
with
@Column(name = "QUESTION")
Poll
has an options
instance variable of type Set
of Option
options
should be annotated
with
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "POLL_ID")
@OrderBy
Create a getter
and setter
for each of the respective instance variables.
-
Vote
Vote
class in the domain
sub-package.Vote
class signature is annotated with @Entity
Vote
has an id
instance variable of type Long
id
should be annotated
with
@Id
@GeneratedValue
Column(name = "VOTE_ID")
Vote
has a option
instance variable of type Option
option
should be annotated
with
@ManyToOne
@JoinColumn(name = "OPTION_ID")
Create a getter
and setter
for each of the respective instance variables.
findById
, findAll
, for retrieving data, and methods to persist and delete data.Repository
per domain
object.io.zipcoder.tc_spring_poll_application
named repositories
.-
OptionRepository
OptionRepository
interface in the repositories
subpackage.OptionRepository
extends CrudRepository<Option, Long>
-
PollRepository
PollRepository
interface in the repositories
subpackage.PollRepository
extends CrudRepository<Poll, Long>
-
VoteRepository
VoteRepository
interface in the repositories
subpackage.VoteRepository
extends CrudRepository<Vote, Long>
io.zipcoder.tc_spring_poll_application
named controller
.-
PollController
Create a PollController
class in the controller
sub package.
PollController
signature should be annotated
with @RestController
PollController
has a pollRepository
instance variable of type PollRepository
pollRepository
should be annotated
with @Inject
-
GET
request methodGET
request on the /polls
endpoint which provides a collection of all of the polls available in the QuickPolls application. Copy and paste this into your PollController
class.@RequestMapping(value="/polls", method= RequestMethod.GET)
public ResponseEntity<Iterable<Poll>> getAllPolls() {
Iterable<Poll> allPolls = pollRepository.findAll();
return new ResponseEntity<>(allPolls, HttpStatus.OK);
}
PollRepository
.ResponseEntity
and pass in Poll
data and the HttpStatus.OK
status value.Poll
data becomes part of the response body and OK
(code 200) becomes the response status code.-
start-class
tag in your pom.xml
encapsulates io.zipcoder.springdemo.QuickPollApplication
mvn spring-boot:run
http://localhost:8080/polls
and hit Send.-
POST
request methodPollController
by implementing the POST
verb functionality in a createPoll
method:@RequestMapping(value="/polls", method=RequestMethod.POST)
public ResponseEntity<?> createPoll(@RequestBody Poll poll) {
poll = pollRepository.save(poll);
return new ResponseEntity<>(null, HttpStatus.CREATED);
}
@RequestBody Poll poll
@RequestBody
tells Spring that the entire request body needs to be converted to an instance of PollPoll
persistence to PollRepository
’s save method
poll = pollRepository.save(poll);
-
createPoll
ServletUriComponentsBuilder
utility class. This will ensure that the client has some way of knowing the URI of the newly created Poll.URI newPollUri = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(poll.getId())
.toUri();
createPoll
method so that it returns a ResponseEntity
which takes an argument of a new HttpHeaders()
whose location has been set to the above newPollUri
via the setLocation
method.-
GET
request method@RequestMapping
takes a URI template /polls/{pollId}
.{pollId}
along with @PathVarible
annotation allows Spring to examine the request URI path and extract the pollId
parameter value.PollRepository
’s findOne
finder method to read the poll and pass it as part of a ResponseEntity
.@RequestMapping(value="/polls/{pollId}", method=RequestMethod.GET)
public ResponseEntity<?> getPoll(@PathVariable Long pollId) {
Poll p = pollRepository.findOne(pollId);
return new ResponseEntity<> (p, HttpStatus.OK);
}
-
UPDATE
request methodRequestMapping(value="/polls/{pollId}", method=RequestMethod.PUT)
public ResponseEntity<?> updatePoll(@RequestBody Poll poll, @PathVariable Long pollId) {
// Save the entity
Poll p = pollRepository.save(poll);
return new ResponseEntity<>(HttpStatus.OK);
}
-
DELETE
request method.@RequestMapping(value="/polls/{pollId}", method=RequestMethod.DELETE)
public ResponseEntity<?> deletePoll(@PathVariable Long pollId) {
pollRepository.delete(pollId);
return new ResponseEntity<>(HttpStatus.OK);
}
-
PUT
to http://localhost:8080/polls/1
whose request body is the JSON
object below.Body
tab, selecting the raw
radio button, and selecting the JSON
option from the text format dropdown.{
"id": 1,
"question": "What's the best netflix original?",
"options": [
{ "id": 1, "value": "Black Mirror" },
{ "id": 2, "value": "Stranger Things" },
{ "id": 3, "value": "Orange is the New Black"},
{ "id": 4, "value": "The Get Down" }
]
}
-
VoteController
PollController
, we implement the VoteController
class.VoteController
class along with the functionality to create a vote.VoteController
uses an injected instance of VoteRepository
to perform CRUD
operations on Vote instances.@RestController
public class VoteController {
@Inject
private VoteRepository voteRepository;
@RequestMapping(value = "/polls/{pollId}/votes", method = RequestMethod.POST)
public ResponseEntity<?> createVote(@PathVariable Long pollId, @RequestBody Vote
vote) {
vote = voteRepository.save(vote);
// Set the headers for the newly created resource
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setLocation(ServletUriComponentsBuilder.
fromCurrentRequest().path("/{id}").buildAndExpand(vote.getId()).toUri());
return new ResponseEntity<>(null, responseHeaders, HttpStatus.CREATED);
}
}
VoteController
POST
a new Vote to the /polls/1/votes
endpoint with the option object expressed in JSON
below.{
"option": { "id": 1, "value": "Black Mirror" }
}
-
VoteRepository
findAll
in the VoteRepository
retrieves all votes in a Database rather than a given poll.VoteRepository
.public interface VoteRepository extends CrudRepository<Vote, Long> {
@Query(value = "SELECT v.* " +
"FROM Option o, Vote v " +
"WHERE o.POLL_ID = ?1 " +
"AND v.OPTION_ID = o.OPTION_ID", nativeQuery = true)
public Iterable<Vote> findVotesByPoll(Long pollId);
}
findVotesByPoll
takes the ID
of the Poll
as its parameter.@Query
annotation on this method takes a native SQL query along with the nativeQuery
flag set to true
.?1
placeholder with the passed-in pollId
parameter value.-
VoteController
getAllVotes
method in the VoteController
@RequestMapping(value="/polls/{pollId}/votes", method=RequestMethod.GET)
public Iterable<Vote> getAllVotes(@PathVariable Long pollId) {
return voteRepository. findByPoll(pollId);
}
java
named dtos
-
OptionCount
OptionCount
DTO contains the ID
of the option and a count of votes casted for that option.public class OptionCount {
private Long optionId;
private int count;
public Long getOptionId() {
return optionId;
}
public void setOptionId(Long optionId) {
this.optionId = optionId;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
VoteResult
VoteResult
DTO contains the total votes cast and a collection of OptionCount
instances.import java.util.Collection;
public class VoteResult {
private int totalVotes;
private Collection<OptionCount> results;
public int getTotalVotes() {
return totalVotes;
}
public void setTotalVotes(int totalVotes) {
this.totalVotes = totalVotes;
}
public Collection<OptionCount> getResults() {
return results;
}
public void setResults(Collection<OptionCount> results) {
this.results = results;
}
}
ComputeResultController
PollController
and VoteController
, we create a new ComputeResultController
class@RestController
public class ComputeResultController {
@Inject
private VoteRepository voteRepository;
@RequestMapping(value = "/computeresult", method = RequestMethod.GET)
public ResponseEntity<?> computeResult(@RequestParam Long pollId) {
VoteResult voteResult = new VoteResult();
Iterable<Vote> allVotes = voteRepository.findVotesByPoll(pollId);
// Algorithm to count votes
return new ResponseEntity<VoteResult>(voteResult, HttpStatus.OK);
}
VoteRepository
into the controller, which is used to retrieve votes for a given poll.computeResult
method takes pollId
as its parameter.@RequestParam
annotation instructs Spring to retrieve the pollId
value from a HTTP query parameter.ResponseEntity
.QuickPoll
application.status
of 200
is returned by executing a GET
request of http://localhost:8080/computeresults?pollId=1
via Postman