Reputation: 107
Going through this tutorial
"Once the session is ended, the persistence object set to detached object"
my question is what happens if you begin another transaction after the first commit but before closing the session. what state is the user object in at this point?
public static void main(String[] args) {
System.out.println("Maven + Hibernate + Oracle");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
DBUser user = new DBUser(); //creating transient object
user.setUserId(104);
user.setUsername("user1");
user.setCreatedBy("system");
user.setCreatedDate(new Date());
session.saveOrUpdate(user); //Updating the transient object to persistence object
session.getTransaction().commit();
session.beginTransaction();
user.setUsername("user2"); //what state is user object in right now?
session.saveOrUpdate(user);
session.getTransaction().commit();
session.close();
}
Upvotes: 1
Views: 1017
Reputation: 21133
Once an entity has been attached to an associated Hibernate Session, it will remain a managed object until either the instance is evicted from the Hibernate Session cache or the session is closed.
That said, if you create an additional transaction before closing the session or evicting your session's managed objects, the entity will continue to be managed and tracked by the session. This means you can continue to use your saved entity from transaction 1 in your subsequent transactions with no issue since it is still being managed so long as your subsequent transactions use the same Hibernate session.
Upvotes: 0