add Session.getReference(Object)

like in Hibernate Reactive

this is really useful for dealing with detached instances + associations
This commit is contained in:
Gavin King 2021-12-24 13:39:33 +01:00 committed by Steve Ebersole
parent 0dc94d312e
commit 65ce96b776
3 changed files with 30 additions and 0 deletions

View File

@ -781,6 +781,18 @@ public interface Session extends SharedSessionContract, EntityManager {
*/
String getEntityName(Object object);
/**
* Return the persistent instance with the same identity as the given instance, which
* might be detached, assuming that the instance is still persistent in the database.
* This method never results in access to the underlying data store, and thus might
* return a proxy that must be initialized explicitly.
*
* @param object a detached persistent instance
*
* @return the persistent instance or proxy
*/
<T> T getReference(T object);
/**
* Create an {@link IdentifierLoadAccess} instance to retrieve the specified entity type by
* primary key.

View File

@ -900,6 +900,11 @@ public class SessionDelegatorBaseImpl implements SessionImplementor {
return delegate.getEntityName( object );
}
@Override
public <T> T getReference(T object) {
return delegate.getReference( object );
}
@Override
public <T> IdentifierLoadAccess<T> byId(String entityName) {
return delegate.byId( entityName );

View File

@ -1703,6 +1703,19 @@ public class SessionImpl
return entry.getPersister().getEntityName();
}
@Override @SuppressWarnings("unchecked")
public <T> T getReference(T object) {
checkOpen();
if ( object instanceof HibernateProxy ) {
LazyInitializer initializer = ( (HibernateProxy) object ).getHibernateLazyInitializer();
return (T) getReference( initializer.getPersistentClass(), initializer.getIdentifier() );
}
else {
EntityPersister persister = getEntityPersister( null, object );
return (T) getReference( persister.getMappedClass(), persister.getIdentifier(object, this) );
}
}
private void throwTransientObjectException(Object object) throws HibernateException {
throw new TransientObjectException(
"object references an unsaved transient instance - save the transient instance before flushing: " +