JPA find and getReference


JPA find() & getReference()

in javax.persistence.EntityManager

* find(): always call select from DB

 

Use for select one entity from DB.

 

Example:

 

Game game = entityManager.find(Game.class, 1L);

* getReference(): Objecre returned is an entity that only has primary key field initialized. The other field remain unset unless we request them.


Use for update, delete.

 

Example :

 

Game game = entityManager.getReference(Game.class, 1L);

// update it-self
game1.setName("Game Updated 1");
entityManager.persist(game1);

//update parent of it
Player player1 = entityManager.find(Player.class, 1L);
player1.setGame(game);
entityManager.persist(player1);

// delete
it-self 

entityManager.remove(game)



Reference:
Post: https://www.baeldung.com/jpa-entity-manager-get-reference
Test: https://github.com/eugenp/tutorials/blob/master/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceMySQLManualTest.java

 

 

 

0 comments :

Post a Comment

Cancel Reply

About Me

My photo
Tân An, Long An, Vietnam
Hello everyone, I love programming, I love making friends with people all over the world.