3

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.)

Shahin
  • 253
  • 1
  • 3
  • 13
  • What kind of exception are you encountering? – Michiel Leegwater Jul 20 '19 at 07:32
  • @MichielLeegwater if there's another entity object with the same id, then we will get NonUniqueObjectException. – Shahin Jul 20 '19 at 08:42
  • Does this article help understand the issue? https://www.journaldev.com/3481/hibernate-session-merge-vs-update-save-saveorupdate-persist-example – Michiel Leegwater Jul 20 '19 at 08:56
  • Another hunch might be that the session is closed, but the object that is loaded still considers itself attached. To sort that out the object needs detaching. See https://stackoverflow.com/questions/5800814/is-it-possible-to-detach-hibernate-entity-so-that-changes-to-object-are-not-aut – Michiel Leegwater Jul 20 '19 at 09:00

0 Answers0