Conventionally, a GET
request is used when you wish to GET information from the database. Similarly, a POST
request is used when we wish to create new information in the database.
With Spring Data JPA’s CrudRepository
, you can use the .save()
method to create records in the database. The .save()
method accepts your model as a parameter, and uses all the annotations you added to indicate the columns as its basis when it uses the ORM to create the underlying SQL INSERT
statement.
Once again, we’ll refer to the Person
example:
@PostMapping("/people") public Person createNewPerson(@RequestBody Person person) { Person newPerson = this.personRepository.save(person); return newPerson; }
In this example, the end user of the API would pass in a Person
using the body of their POST
request. To save this person to our database, we use the .save
method from the PersonRepository
. The .save
method returns a Person
as well, and the only difference between this newPerson
and the original person
passed by the user is that the newPerson
will have an id
field, generated by means of the @GeneratedValue
annotation from the model definition.
Lastly, this newPerson
is returned in the response body, so that the end user can know the ID that was assigned to the new entry they created in the database.
Now, let’s do something similar for our plants application.
Instructions
Create a public
method in the PlantController
that can accept a Plant
plant
and save it using the plantRepository
field. Call this method createNewPlant
. Don’t add any of the Spring annotations just yet. After saving the plant
, this method should return the newPlant
that is created after .save
is called.
Add the annotations that will attach this method as a handler to a POST
request made to "/plants"
. Additionally, add the annotation required to make Spring Boot check the request body for the plant
passed by the user in their request.
You’re ready to test out your new method! Use curl
to make a POST
request to this new endpoint, passing in all the required parameters for creating a record in the PLANTS
database.
Remember, you won’t have to pass an id
, as that will be automatically generated with our @GeneratedValue
annotation on that field. For the rest of the parameters, check your Plant.java
file to see what fields are expected for this model.
If you got a response body back with a new id
, then your code to create a new Plant
entry in the PLANTS
database worked!
Validate this again by hitting the GET
endpoints you created. Using either the web browser pane or curl
, ensure that your GET /plants
and GET /plants/{id}
endpoints both reflect that a new entry was created.