CRUD Operations
Explore how to perform create, read, update, and delete operations using Spring Data JPA's EntityManager. Learn to use methods such as merge for insert and update, find for retrieving records, and remove for deletions, all while working with automatic SQL generation and Hibernate integration.
The EntityManager offers a large number of methods to perform various queries. We will write methods to insert, fetch, update, and delete data in the PlayerRepository.
merge() method for INSERT and UPDATE queries
The EntityManager offers a merge() method for both INSERT and UPDATE operations. merge() checks if the primary key value is being passed to it or not. If it finds the primary key, it updates the corresponding record. If the primary key is not passed, it generates a value and inserts a new record in the table. The merge() method returns a Player object.
The logic of insertPlayer() and updatePlayer() methods will be the same. The difference lies in the arguments being passed to the merge() method.
public Player insertPlayer(Player player){return entityManager.merge(player);}public Player updatePlayer(Player player){return entityManager.merge(player);}