mmerder wrote:
You can use session.contains to check if the object is associated to the current session.
here is the code from hibernate which determines the state of entity
and how good is using session.contains() compared to this ?
Code:
protected int getEntityState(
Object entity,
String entityName,
EntityEntry entry, //pass this as an argument only to avoid double looking
SessionImplementor source) {
if ( entry != null ) { // the object is persistent
//the entity is associated with the session, so check its status
if ( entry.getStatus() != Status.DELETED ) {
// do nothing for persistent instances
if ( log.isTraceEnabled() ) {
log.trace(
"persistent instance of: " +
getLoggableName( entityName, entity )
);
}
return PERSISTENT;
}
else {
//ie. e.status==DELETED
if ( log.isTraceEnabled() ) {
log.trace(
"deleted instance of: " +
getLoggableName( entityName, entity )
);
}
return DELETED;
}
}
else { // the object is transient or detached
//the entity is not associated with the session, so
//try interceptor and unsaved-value
if ( ForeignKeys.isTransient( entityName, entity, getAssumedUnsaved(), source ) ) {
if ( log.isTraceEnabled() ) {
log.trace(
"transient instance of: " +
getLoggableName( entityName, entity )
);
}
return TRANSIENT;
}
else {
if ( log.isTraceEnabled() ) {
log.trace(
"detached instance of: " +
getLoggableName( entityName, entity )
);
}
return DETACHED;
}
}
}
public static boolean isTransient(String entityName, Object entity, Boolean assumed, SessionImplementor session)
throws HibernateException {
if (entity==LazyPropertyInitializer.UNFETCHED_PROPERTY) {
// an unfetched association can only point to
// an entity that already exists in the db
return false;
}
// let the interceptor inspect the instance to decide
Boolean isUnsaved = session.getInterceptor().isTransient(entity);
if (isUnsaved!=null) return isUnsaved.booleanValue();
// let the persister inspect the instance to decide
EntityPersister persister = session.getEntityPersister(entityName, entity);
isUnsaved = persister.isTransient(entity, session);
if (isUnsaved!=null) return isUnsaved.booleanValue();
// we use the assumed value, if there is one, to avoid hitting
// the database
if (assumed!=null) return assumed.booleanValue();
// hit the database, after checking the session cache for a snapshot
Object[] snapshot = session.getPersistenceContext()
.getDatabaseSnapshot( persister.getIdentifier( entity, session.getEntityMode() ), persister );
return snapshot==null;
}