I have written this utility class called DetachedObject which I want to run by the experts here:
Code:
public class DetachedObject
{
private Object object;
private final boolean reattachRequired;
public DetachedObject( Object object, Session session )
{
this.object = object;
reattachRequired = session.contains( object );
}
public Object reattach( Session session )
{
if( reattachRequired )
{
return session.merge( object );
}
else
{
return object;
}
}
}
The idea here is that I'm going to store the DetachedObject in the HttpSession of my webapp. When a request comes back in, I'd like to reliably be able to reattach the object to the current session (I'm using open-session-in-view). I'm implementing a custom "persistence strategy" in Tapestry. So, for persistent page/component properties of type "entity" I'd use this class to store the object into the session.
1. I always want to store the object "as-is" because I want to account for optimistically locked (versioned) objects. If I just store the identity of the object (entity name and identifier), then I basically circumvent the version checking logic, because I'd be reading the latest version out of the db. I realize that when the occasion does arise when a versioned object has been modified since I last loaded it, the call to merge() will fail with a StaleStateException, but that's what I want. I want to know that. Does this sound about right to you folks? I could make sure my HTML forms update the version property, but I read somewhere that you're really not supposed to manually set the version property.
2. If the object is "new", I don't want to reattach it at all (as it wasn't persistent in the first place). I am using the contains() method to see if something is persistent. Is this a good way to do it? Does anyone see anything else that's flawed with this approach? Is there a better way to see if an object is "new"? Because, it could have been loaded in another Session, but it's still persistent. I guess I could ask for the identity and catch the exception that's thrown when it doesn't have one (I think I've done that before), but I hate using exceptions for logic.
Sorry for the long post.
Hibernate version: 3.1