Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions hibernate-core/src/main/java/org/hibernate/Session.java
Original file line number Diff line number Diff line change
Expand Up @@ -901,6 +901,13 @@ public interface Session extends SharedSessionContract, EntityManager {
* @return a persistent instance or null
*
* @deprecated The semantics of this method may change in a future release.
* Use {@link SessionFactory#createGraphForDynamicEntity(String)}
* together with {@link #find(EntityGraph, Object, FindOption...)}
* to load {@link org.hibernate.metamodel.RepresentationMode#MAP
* dynamic entities}.
*
* @see SessionFactory#createGraphForDynamicEntity(String)
* @see #find(EntityGraph, Object, FindOption...)
*/
@Deprecated(since = "7")
Object get(String entityName, Object id);
Expand Down
22 changes: 22 additions & 0 deletions hibernate-core/src/main/java/org/hibernate/SessionFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import javax.naming.Referenceable;

import jakarta.persistence.EntityManager;
import jakarta.persistence.FindOption;
import jakarta.persistence.SynchronizationType;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.engine.spi.FilterDefinition;
Expand Down Expand Up @@ -413,6 +414,27 @@ default <R> R fromStatelessTransaction(Function<? super StatelessSession,R> acti
*/
RootGraph<?> findEntityGraphByName(String name);

/**
* Create an {@link EntityGraph} which may be used from loading a
* {@linkplain org.hibernate.metamodel.RepresentationMode#MAP dynamic}
* entity with {@link Session#find(EntityGraph, Object, FindOption...)}.
* <p>
* This allows a dynamic entity to be loaded without the need for a cast.
* <pre>
* var MyDynamicEntity_ = factory.createGraphForDynamicEntity("MyDynamicEntity");
* Map&lt;String,?&gt; myDynamicEntity = session.find(MyDynamicEntity_, id);
* </pre>
*
* @apiNote Dynamic entities are normally defined using XML mappings.
*
* @param entityName The name of the dynamic entity
*
* @since 7.0
*
* @see Session#find(EntityGraph, Object, FindOption...)
*/
RootGraph<Map<String,?>> createGraphForDynamicEntity(String entityName);

/**
* Obtain the set of names of all {@link org.hibernate.annotations.FilterDef
* defined filters}.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.EntityCopyObserverFactory;
import org.hibernate.event.spi.EventEngine;
import org.hibernate.graph.RootGraph;
import org.hibernate.graph.spi.RootGraphImplementor;
import org.hibernate.event.service.spi.EventListenerGroups;
import org.hibernate.metamodel.MappingMetamodel;
Expand Down Expand Up @@ -226,6 +227,11 @@ public SqlStringGenerationContext getSqlStringGenerationContext() {
return delegate.getSqlStringGenerationContext();
}

@Override
public RootGraph<Map<String, ?>> createGraphForDynamicEntity(String entityName) {
return delegate.createGraphForDynamicEntity( entityName );
}

@Override
public RootGraphImplementor<?> findEntityGraphByName(String name) {
return delegate.findEntityGraphByName( name );
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@
import org.hibernate.event.spi.EventEngine;
import org.hibernate.event.service.spi.EventListenerGroups;
import org.hibernate.generator.Generator;
import org.hibernate.graph.RootGraph;
import org.hibernate.graph.internal.RootGraphImpl;
import org.hibernate.graph.spi.RootGraphImplementor;
import org.hibernate.integrator.spi.Integrator;
import org.hibernate.integrator.spi.IntegratorService;
Expand All @@ -82,8 +84,10 @@
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.RootClass;
import org.hibernate.metamodel.MappingMetamodel;
import org.hibernate.metamodel.RepresentationMode;
import org.hibernate.metamodel.internal.RuntimeMetamodelsImpl;
import org.hibernate.metamodel.mapping.JdbcMapping;
import org.hibernate.metamodel.model.domain.EntityDomainType;
import org.hibernate.metamodel.model.domain.internal.MappingMetamodelImpl;
import org.hibernate.metamodel.model.domain.spi.JpaMetamodelImplementor;
import org.hibernate.metamodel.spi.MappingMetamodelImplementor;
Expand Down Expand Up @@ -724,6 +728,17 @@ public boolean isOpen() {
return status != Status.CLOSED;
}

@Override
public RootGraph<Map<String, ?>> createGraphForDynamicEntity(String entityName) {
final EntityDomainType<?> entity = getJpaMetamodel().entity( entityName );
if ( entity.getRepresentationMode() != RepresentationMode.MAP ) {
throw new IllegalArgumentException( "Entity '" + entityName + "' is not a dynamic entity" );
}
@SuppressWarnings("unchecked") //Safe, because we just checked
final EntityDomainType<Map<String, ?>> dynamicEntity = (EntityDomainType<Map<String, ?>>) entity;
return new RootGraphImpl<>( null, dynamicEntity );
}

@Override
public RootGraphImplementor<?> findEntityGraphByName(String name) {
return getJpaMetamodel().findEntityGraphByName( name );
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@
import org.hibernate.BatchSize;
import org.hibernate.CacheMode;
import org.hibernate.ConnectionAcquisitionMode;
import org.hibernate.EntityFilterException;
import org.hibernate.EnabledFetchProfile;
import org.hibernate.EntityFilterException;
import org.hibernate.FetchNotFoundException;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
Expand Down Expand Up @@ -106,6 +106,7 @@
import org.hibernate.event.spi.ReplicateEvent;
import org.hibernate.event.spi.ReplicateEventListener;
import org.hibernate.loader.internal.CacheLoadHelper;
import org.hibernate.metamodel.model.domain.ManagedDomainType;
import org.hibernate.resource.transaction.spi.TransactionObserver;
import org.hibernate.event.monitor.spi.EventMonitor;
import org.hibernate.event.monitor.spi.DiagnosticEvent;
Expand Down Expand Up @@ -961,8 +962,7 @@ public void load(Object object, Object id) {
fireLoad( new LoadEvent( id, object, this, getReadOnlyFromLoadQueryInfluencers() ), LoadEventListener.RELOAD );
}

private <T> MultiIdentifierLoadAccess<T> multiloadAccessWithOptions(Class<T> entityClass, FindOption[] options) {
final MultiIdentifierLoadAccess<T> loadAccess = byMultipleIds( entityClass );
private <T> void setMultiIdentifierLoadAccessOptions(FindOption[] options, MultiIdentifierLoadAccess<T> loadAccess) {
CacheStoreMode storeMode = getCacheStoreMode();
CacheRetrieveMode retrieveMode = getCacheRetrieveMode();
LockOptions lockOptions = copySessionLockOptions();
Expand Down Expand Up @@ -1006,12 +1006,13 @@ else if ( option instanceof BatchSize batchSizeOption ) {
loadAccess.with( lockOptions )
.with( interpretCacheMode( storeMode, retrieveMode ) )
.withBatchSize( batchSize );
return loadAccess;
}

@Override
public <E> List<E> findMultiple(Class<E> entityType, List<Object> ids, FindOption... options) {
return multiloadAccessWithOptions( entityType, options ).multiLoad( ids );
final MultiIdentifierLoadAccess<E> loadAccess = byMultipleIds( entityType );
setMultiIdentifierLoadAccessOptions( options, loadAccess );
return loadAccess.multiLoad( ids );
}

@Override
Expand Down Expand Up @@ -2498,8 +2499,7 @@ private static <T> void logIgnoringEntityNotFound(Class<T> entityClass, Object p
}
}

private <T> IdentifierLoadAccessImpl<T> loadAccessWithOptions(Class<T> entityClass, FindOption[] options) {
final IdentifierLoadAccessImpl<T> loadAccess = byId( entityClass );
private <T> void setLoadAccessOptions(FindOption[] options, IdentifierLoadAccessImpl<T> loadAccess) {
CacheStoreMode storeMode = getCacheStoreMode();
CacheRetrieveMode retrieveMode = getCacheRetrieveMode();
LockOptions lockOptions = copySessionLockOptions();
Expand Down Expand Up @@ -2537,19 +2537,26 @@ else if ( option instanceof ReadOnlyMode ) {
}
}
loadAccess.with( lockOptions ).with( interpretCacheMode( storeMode, retrieveMode ) );
return loadAccess;
}

@Override
public <T> T find(Class<T> entityClass, Object primaryKey, FindOption... options) {
return loadAccessWithOptions( entityClass, options ).load( primaryKey );
final IdentifierLoadAccessImpl<T> loadAccess = byId( entityClass );
setLoadAccessOptions( options, loadAccess );
return loadAccess.load( primaryKey );
}

@Override
public <T> T find(EntityGraph<T> entityGraph, Object primaryKey, FindOption... options) {
final RootGraph<T> graph = (RootGraph<T>) entityGraph;
final Class<T> entityClass = graph.getGraphedType().getJavaType();
return loadAccessWithOptions( entityClass, options ).withLoadGraph( graph ).load( primaryKey );
final ManagedDomainType<T> type = graph.getGraphedType();
final IdentifierLoadAccessImpl<T> loadAccess =
switch ( type.getRepresentationMode() ) {
case MAP -> byId( type.getTypeName() );
case POJO -> byId( type.getJavaType() );
};
setLoadAccessOptions( options, loadAccess );
return loadAccess.withLoadGraph( graph ).load( primaryKey );
}

private void checkTransactionNeededForLock(LockMode lockMode) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
*/
package org.hibernate.metamodel;

import org.hibernate.AssertionFailure;

import java.util.Locale;

Expand All @@ -19,28 +18,19 @@ public enum RepresentationMode {
MAP;

public String getExternalName() {
switch (this) {
case POJO:
return "pojo";
case MAP:
return "dynamic-map";
default:
throw new AssertionFailure("Unknown RepresentationMode");
}
return switch ( this ) {
case POJO -> "pojo";
case MAP -> "dynamic-map";
};
}

public static RepresentationMode fromExternalName(String externalName) {
if ( externalName == null ) {
return POJO;
}
switch ( externalName.toLowerCase(Locale.ROOT) ) {
case "pojo":
return POJO;
case "dynamic-map":
case "map":
return MAP;
default:
throw new IllegalArgumentException("Unknown RepresentationMode");
}
return externalName == null
? POJO
: switch ( externalName.toLowerCase( Locale.ROOT ) ) {
case "pojo" -> POJO;
case "dynamic-map", "map" -> MAP;
default -> throw new IllegalArgumentException( "Unknown RepresentationMode" );
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import org.hibernate.metamodel.model.domain.internal.AttributeContainer;
import org.hibernate.metamodel.model.domain.spi.JpaMetamodelImplementor;
import org.hibernate.type.descriptor.java.JavaType;
import org.hibernate.type.descriptor.java.spi.DynamicModelJavaType;

import static java.util.Collections.emptySet;
import static org.hibernate.internal.util.collections.CollectionHelper.isEmpty;
Expand Down Expand Up @@ -66,10 +67,11 @@ protected AbstractManagedType(
supertype.addSubType( this );
}

// todo (6.0) : need to handle RepresentationMode#MAP as well
this.representationMode = RepresentationMode.POJO;
representationMode = javaType instanceof DynamicModelJavaType
? RepresentationMode.MAP
: RepresentationMode.POJO;

this.inFlightAccess = createInFlightAccess();
inFlightAccess = createInFlightAccess();
}

protected InFlightAccess<J> createInFlightAccess() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,8 @@
*/
@Internal
public abstract class AbstractCollectionPersister
implements CollectionPersister, InFlightCollectionMapping, CollectionMutationTarget, PluralAttributeMappingImpl.Aware, FetchProfileAffectee, Joinable {
implements CollectionPersister, InFlightCollectionMapping, CollectionMutationTarget,
PluralAttributeMappingImpl.Aware, FetchProfileAffectee, Joinable {

private final NavigableRole navigableRole;
private final CollectionSemantics<?,?> collectionSemantics;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,8 @@
@Internal
@SuppressWarnings("deprecation")
public abstract class AbstractEntityPersister
implements EntityPersister, InFlightEntityMappingType, EntityMutationTarget, LazyPropertyInitializer, FetchProfileAffectee, Joinable {
implements EntityPersister, InFlightEntityMappingType, EntityMutationTarget, LazyPropertyInitializer,
FetchProfileAffectee, Joinable {

private static final CoreMessageLogger LOG = CoreLogging.messageLogger( AbstractEntityPersister.class );

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import java.util.HashMap;
import java.util.Map;

import org.hibernate.graph.RootGraph;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
Expand All @@ -33,6 +34,20 @@ public void testLoading(SessionFactoryScope scope) {
} );
}

@Test
public void testLoadingNewApi(SessionFactoryScope scope) {
final RootGraph<Map<String, ?>> Sub_ =
scope.getSessionFactory()
.createGraphForDynamicEntity( "Sub" );
scope.inTransaction( (session) -> {
final Map<String,?> entity = session.find( Sub_, 1 );
assertThat( entity ).isNotNull();
assertThat( entity.get( "name" ) ).isEqualTo( "sub" );
assertThat( entity.get( TYPE_KEY ) ).isNotNull();
assertThat( entity.get( TYPE_KEY ) ).isEqualTo( "Sub" );
} );
}

@BeforeEach
public void createTestData(SessionFactoryScope scope) {
scope.inTransaction( (session) -> {
Expand Down
Loading