I've got a web application using hibernate3.jar, and it works fine most of the time. I have objects in the application that I fetch, create, update, etc., via Hibernate, some of which are stored in the (web app) session for future use. We use lazy loading, so occasionally I will come across an object that had been loaded by an earlier Hib Session, in which case I lock it to the current Session. I can't always predict when I will run into a situation where I will need to lock, so I use the following algorithm in some cases:
Code:
try {
log.debug("Processing " + foo.getBars().size() + " Bars");
setBar = foo.getBars();
}
catch (Exception e) {
session.lock(foo, LockMode.NONE);
}
In this case, foo's set of Bar objects is lazily loaded. Sometimes the set will be loaded without incident, and other times there will be a exception of the type
Code:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: foo.bars, no session or session was closed
in which case the foo is locked and we go on our merry way.
Well, recently I came across a situation where the lock resulted in the following:
Code:
org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [Foo#1006561]
so I inserted a second try/catch:
Code:
try {
log.debug("Processing " + foo.getBars().size() + " Bars");
setBar = foo.getBars();
}
catch (Exception e) {
try {
session.lock(foo, LockMode.NONE);
} catch (Exception e1) {
session.evict(foo);
session.flush();
session.lock(foo, LockMode.NONE);
}
}
but this fails too with the same NonUniqueObjectException! So I had to resort to loading the set separately:
Code:
try {
log.debug("Processing " + foo.getBars().size() + " Bars");
setBar = foo.getBars();
}
catch (Exception e) {
try {
session.lock(foo, LockMode.NONE);
} catch (Exception e1) {
try {
session.evict(foo);
session.flush();
session.lock(foo, LockMode.NONE);
} catch (Exception e2) {
// What the - ? How is this possible?
setBar = session.CreateCriteria(Bar.class)
.add(Restrictions.eq("foo", foo))
.list();
}
}
}
So my question is, if I evict the object, how can I then be told that I have a non-unique object?
Thanks
~Paul T.