Hibernate version: 2.1.6
Hi Folks - this is in relation to the issue of choosing between using session.saveOrUpdate() and session.saveOrUpdateCopy().
Skip to the bottom for my implemented workaround - its very hacky, but I don't see a better way to handle the situation.
We have a system that operates fairly simply by allowing code to
- receive a modified object from our view layer code
- call a utility class method to save/update the object
It works fine to call session.saveOrUpdate() with an object when another version of the object has not been loaded.
However, in many cases, we need to examine the previously existing version of the same object before updating it.
Fine, so we session.load() the old version, check stuff, then use saveOrUpdateCopy() to avoid a NonUniqueObjectException.
The problem is that now the code that performs the saveOrUpdate() or saveOrUpdateCopy() has to be aware of the context of the surrounding code so that it knows whether the object was previously loaded.
So, to keep the coupling down between these layers of code, I would like our persistence utility to be able to expose a single method that will do the right thing.
The best I have come up with is this:
Code:
//determine if there is a loaded version of the object
boolean entityLoaded = false;
ClassPersister cp = ((SessionImplementor)session).getPersister(object);
Serializable id = cp.getIdentifier(object);
Key objectKey = new Key(id, cp);
entityLoaded = ((SessionImplementor)session).getEntity(objectKey) != null;
if (entityLoaded){
if (log.isDebugEnabled()) {
log.debug("found loaded entity for object: "+ object);
}
session.saveOrUpdateCopy(object);
} else {
if (log.isDebugEnabled()) {
log.debug("did NOT find loaded entity for object: "+ object);
}
session.saveOrUpdate(object);
}
I would really rather not use the hibernate mechanisms of SessionImplementor, ClassPersister and Key, but I don't think the hibernate session has an exposed method for indicating that "i know the object may already be loaded, in that case please use saveOrUpdateCopy() pattern".
Any thoughts on this?
thanks
tyson