As soon as the persistence context is closed, object becomes a detached instance. If you want to save modifications you made to a detached object, you have to either reattach or merge it. A detached instance may be reattached to a new Session(and managed by this new persistence context) by calling update() on the detached object. In your experience, it may be easier for you to understand if you rename the update() method in your mind to reattach().
item.getId(); // The database identity is "1234"
item.setDescription(...);
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Item item2 = (Item) session.get(Item.class, new Long(1234));
session.update(item); // Throws exception!
tx.commit();
session.close();
item.getId(); // The database identity is "1234"
item.setDescription(...);
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Item item2 = (Item) session.get(Item.class, new Long(1234));
session.update(item); // Throws exception!
tx.commit();
session.close();
Comments
Post a Comment