Apologies for not finding this in the documentation - maybe I can't read:
During an open session, hibernate tracks loaded object changes, and at the session end (flush) saves modified (isDirty) objects automatically.
However, when I use detached objects (i.e. I load my objects in one session, work on then, and then create another session to save them using session.update()), transaction commit always updates the entire object graph (instrument has a set of data items) - despite no changes have been made.
Is this an EXPECTED behavior, OR am I doing something WRONG?
Do I HAVE to keep the first session open all the time?
Is there some cache configuration parameter affecting this?
Or, is there some 'other' way to 'make' hibernate track changes to my objects between the original session AND the one using session.update() ?
In addition, immediatelly after calling session.update() in a second session, that session is considered isDirty(), even when I call this code imediatelly after I just loaded the object in the first session. I would hope I could use Hibernate object change tracking to find out IF my objects have been changed...
I definitelly can not keep the session open across between the object tree load and save - I need to use the underlying connection for many other short-lived sessions, some of which may encounter an error (and hence must be discarded).
Hibernate version:3.0
Mapping documents: n/a
Code between sessionFactory.openSession() and session.close():
public Instrument loadInstrument(Integer instId, ) throws Exception {
Instrument ret = null;
Session ses = null;
DBUtilHibernate util = DBUtilHibernate.getInstance(); // simplified
try {
ses = sessionFactory.openSession();
util.beginTransaction();
Query q = ses.createQuery("from Instrument i where id :instId");
q.setInteger("instId", instId);
ret = (Instrument) q.uniqueResult();
util.commitTransaction();
} finally {
closeSessionNoThrow(ses);
}
return ret;
}
public void saveInstrument(Instrument inst) throws Exception {
DBUtilHibernate util = DBUtilHibernate.getInstance(); // simplified
Session ses = null;
try {
ses = sessionFactory.openSession();
util.beginTransaction();
ses.update(inst);
util.commitTransaction();
} finally {
closeSessionNoThrow(ses);
}
}
public boolean isInstrumentDirty(Instrument inst) {
// Ask Hibernate what IT thinks
DBUtilHibernate util = DBUtilHibernate.getInstance(); // simplified
Session ses = null;
boolean dirty = false;
try {
ses = sessionFactory.openSession();
util.beginTransaction();
ses.update(inst);
return ses.isDirty();
util.rollbackTransaction();
} catch (Exception ex) {
return false;
} finally {
closeSessionNoThrow(ses);
}
}
void closeSessionNoThrow(Session ses) {
try { if (ses != null) ses.sloseSession(); } catch (Exception e) {}
}
Full stack trace of any exception that occurs: none
Name and version of the database you are using: MySQL 5.0
The generated SQL (show_sql=true): n/a
Debug level Hibernate log excerpt: n/a
|