I am trying to understand how HibernateTemplate handles session open and close. I was using saveOrUpdate to persist objects and I came across the well known "org.hibernate.NonUniqueObjectException". Then I started using merge() to overcome this problem. But now I am curious to know what exactly was causing this error since I do not see how a second instance of the same object got linked to the current session. Let me give a code snippet that I believe is causing this exception. It will be helpful if someone can explain what is going on in the background.
------------------------------------------------------------------------------------
// This is an annotated class
class A {
int id;
...
}
class Impl {
void foo1(int id) {
// Runs a criteria query to retrieve an object of class <A> using the
// primary key <id>. This object is retrieved just to check if it exists in
// the database.
}
void foo2(A a) {
getHibernateTemplate().saveOrUpdate(a);
}
}
class Service {
A a = new A();
a.id = 1;
// The database already has this object <a>
foo1(1);
// Update the database with <a>
foo2(a);
}
------------------------------------------------------------------------------------
If i comment out the criteria query in foo1() or set getHibernateTemplate().setAlwaysUseNewSession(true) inside foo2(), no exception is thrown. Can someone point out the 2 instances that are linked to the same session? What is the best way to handle these issues? Also when we use API's like update, saveOrUpdate, hibernate handles the sessions, but does it close the session immediately after executing the statement?
|