Spring hibernate Lifecycle

Persistence Context has two implemnet is JPA EntityManage and Hiberbate Session


Example use Session of hiberate  has exist github you can view it in tail post.

// Get persistence context by hibernate session
Session session = HibernateLifecycleUtil.getSessionfatory().openSession();
Transaction transaction =
session.beginTransaction();

//Get entity
List<FootballPlayer> players = session.createQuery("from FootballPlayer").getResultList();
FootballPlayer cr7 = session.get(FootballPlayer.class, 1L); // get id has 1

//can you edit, delete or detach or actach with entity above

// detack entity cr7 not tracker by persistence context
session.evict(cr7);

// actach it and all change has udpate into persistence not DB,
// you must call commit or flush to do that update real changes in DB
session.update(cr7);

//save object
// not save in DB only persistence context
session.save(neymar);

//delete object
// not delete in DB only persistence context
session.delete(neymar);



=>> you must use transaction.commit() or session.flush() to that real action in database

 

=>> If use spring boot you can use interface CRUDRepository or JPAReposioty to save, update, remove, findObject ... Them useful so we wouldn't work directly with persistence context. 


Image life cycle by source: https://amigoscode.com/p/spring-data-jpa

 


 

Github project example : https://github.com/nguyenthinhit996/sharefullcode/tree/master/spring/hibernate/DefiningEntities

 

Reference by : https://www.baeldung.com/hibernate-entity-lifecycle

 



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.