@PostMapping

Learn how to add a record to the database using a POST request.

In this lesson, we will create an endpoint for the REST API which creates a new player and adds it to the database.

The REST client will send a POST request to /players. The body of the request contains the JSON data for a player. Since this is a new player, the client will not pass the ID (primary key). The backend system will generate the key for the new record.

The REST service will convert JSON data to POJO and add it to the database. The primary key of the added player is automatically generated by Hibernate, which is the default ORM used by Spring Data JPA. The response to the client is an echo of the player details along with the newly generated ID value.

Press + to interact
POST request to /players
POST request to /players

We will begin by writing the service layer method to add a player. This method, addPlayer takes a Player object as parameter and returns the entity that has been added.

public Player addPlayer(Player p) {
//call repository method to add a player object to the player table
}
Service layer method for inserting a record

save() method

The JpaRepository interface inherits a method from the CrudRepository called save(). This method handles both inserts and updates. To distinguish between an INSERT and UPDATE operation, the save() method checks the primary key of the object that is being passed to it. If the primary key is empty or null, an INSERT operation is performed, otherwise an UPDATE to an existing record is ...