Is there an API call for detecting whether an object is transient or not? The obvious solution is something like if( object.getId( ) < 0 ) { // unsaved }, but that's sort of a hack given that the unsaved-value is defined outside of the code in the mapping XML. I read in another post that there is a method called isUnsaved( ) (or something similar) on SessionImplementor, but casting Session to SessionImplementor is equally bad, if not worse.
I guess the best way would be to *know* whether the object is transient or detached by design. However, it is very tempting to combine add and edit functions since they are 99% the same code (same views, same backing beans, same validations, same model, same DAO method calls). And again, I suppose I could save the new instance right off the bat so that it is a detached instance rather than transient, but that is committing data that I don't want committed.
I think what I'll do for now is develop an interface for my model classes that exposes an isTransient( ) method and create an abstract base class that provides a default implementation based on a negative ID field. Then I'll change my HibernateUtil method like so:
Code:
public class HibernateUtil
{
public void lock( ModelObject o )
{
// Check for transience here so that we don't
// have to address the same concern in every
// calling method
if( ! o.isTransient( ) )
{
getSession( ).lock( o, LockMode.NONE );
// Allow StaleObjectException to be thrown
// and handled on a case-by-case basis.
}
}
}
I didn't know about the cascading locks and NonUniqueObjectException, but I think that my odds of getting that are probably low considering I'm closing the session on each request and dealing mostly with detached objects. Still, good to know.