It's well explained in blogs such as [1] that update() and merge() methods may behave differently in case we need to update some detached entity. On the other hand, blog [2] states:
First level cache is associated with “session” object and other session objects in application can not see it.The scope of cache objects is of session. Once session is closed, cached objects are gone forever.
Here's a code snippet from reference [1]:
Session session = factory.openSession();
Student student = (Student) session.get(Student.class, 111);
session.close();
student.setName("chandrashekhar");
Session session2 = factory.openSession();
Student student2 = session2.get(Student.class, 111); //a new Student object with id=111
Transaction tx = session2.beginTransaction();
session2.update(student); //throws NonUniqueObjectExcpetion because there's already *student2* in session2 cache
tx.commit();
Here's my question: session
and session2
are two different Session
objects. why does update()
method throw a NonUniqueObjectExcpetion
while by closing the object session
it should've destroyed the object student
? (thus we couldn't have encountered such an exception.)