avoid the use of TypeConfiguration.getSessionFactory() which is not very typesafe

continue sorting out issues with lifecycle of SessionFactoryImpl and friends
This commit is contained in:
Gavin 2023-01-03 15:01:51 +01:00 committed by Gavin King
parent 91c69d72a7
commit e8f899ffbc
49 changed files with 605 additions and 424 deletions

View File

@ -11,7 +11,7 @@ import java.util.Collections;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.engine.query.internal.NativeQueryInterpreterStandardImpl; import org.hibernate.engine.query.internal.NativeQueryInterpreterStandardImpl;
import org.hibernate.metamodel.model.domain.internal.JpaMetamodelImpl; import org.hibernate.metamodel.model.domain.internal.JpaMetamodelImpl;
import org.hibernate.orm.test.jpa.JpaComplianceStub; import org.hibernate.metamodel.model.domain.internal.MappingMetamodelImpl;
import org.hibernate.query.criteria.ValueHandlingMode; import org.hibernate.query.criteria.ValueHandlingMode;
import org.hibernate.query.internal.NamedObjectRepositoryImpl; import org.hibernate.query.internal.NamedObjectRepositoryImpl;
import org.hibernate.query.spi.QueryEngine; import org.hibernate.query.spi.QueryEngine;
@ -48,7 +48,8 @@ public class InformixDialectTestCase extends BaseUnitTestCase {
@BeforeClass @BeforeClass
public static void init() { public static void init() {
final JpaMetamodelImpl jpaMetamodel = new JpaMetamodelImpl( new TypeConfiguration(), new JpaComplianceStub() ); TypeConfiguration typeConfiguration = new TypeConfiguration();
final JpaMetamodelImpl jpaMetamodel = new JpaMetamodelImpl(typeConfiguration, new MappingMetamodelImpl( typeConfiguration, ssr ) );
ssr = new StandardServiceRegistryBuilder().build(); ssr = new StandardServiceRegistryBuilder().build();
queryEngine = new QueryEngine( queryEngine = new QueryEngine(

View File

@ -13,7 +13,6 @@ import org.hibernate.action.spi.AfterTransactionCompletionProcess;
import org.hibernate.action.spi.BeforeTransactionCompletionProcess; import org.hibernate.action.spi.BeforeTransactionCompletionProcess;
import org.hibernate.action.spi.Executable; import org.hibernate.action.spi.Executable;
import org.hibernate.engine.spi.EntityEntry; import org.hibernate.engine.spi.EntityEntry;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.event.spi.EventSource; import org.hibernate.event.spi.EventSource;
import org.hibernate.internal.FastSessionServices; import org.hibernate.internal.FastSessionServices;
import org.hibernate.internal.util.StringHelper; import org.hibernate.internal.util.StringHelper;
@ -158,7 +157,7 @@ public abstract class EntityAction
return roleComparison != 0 return roleComparison != 0
? roleComparison ? roleComparison
//then by id //then by id
: persister.getIdentifierType().compare( id, action.getId() ); : persister.getIdentifierType().compare( id, action.getId(), session.getSessionFactory() );
} }
/** /**

View File

@ -39,6 +39,7 @@ import org.hibernate.resource.jdbc.spi.StatementInspector;
public class SessionFactoryBuilderImpl implements SessionFactoryBuilderImplementor { public class SessionFactoryBuilderImpl implements SessionFactoryBuilderImplementor {
private final MetadataImplementor metadata; private final MetadataImplementor metadata;
private final SessionFactoryOptionsBuilder optionsBuilder; private final SessionFactoryOptionsBuilder optionsBuilder;
private final BootstrapContext bootstrapContext;
public SessionFactoryBuilderImpl(MetadataImplementor metadata, BootstrapContext bootstrapContext) { public SessionFactoryBuilderImpl(MetadataImplementor metadata, BootstrapContext bootstrapContext) {
this( this(
@ -46,13 +47,15 @@ public class SessionFactoryBuilderImpl implements SessionFactoryBuilderImplement
new SessionFactoryOptionsBuilder( new SessionFactoryOptionsBuilder(
metadata.getMetadataBuildingOptions().getServiceRegistry(), metadata.getMetadataBuildingOptions().getServiceRegistry(),
bootstrapContext bootstrapContext
) ),
bootstrapContext
); );
} }
public SessionFactoryBuilderImpl(MetadataImplementor metadata, SessionFactoryOptionsBuilder optionsBuilder) { public SessionFactoryBuilderImpl(MetadataImplementor metadata, SessionFactoryOptionsBuilder optionsBuilder, BootstrapContext context) {
this.metadata = metadata; this.metadata = metadata;
this.optionsBuilder = optionsBuilder; this.optionsBuilder = optionsBuilder;
this.bootstrapContext = context;
if ( metadata.getSqlFunctionMap() != null ) { if ( metadata.getSqlFunctionMap() != null ) {
for ( Map.Entry<String, SqmFunctionDescriptor> sqlFunctionEntry : metadata.getSqlFunctionMap().entrySet() ) { for ( Map.Entry<String, SqmFunctionDescriptor> sqlFunctionEntry : metadata.getSqlFunctionMap().entrySet() ) {
@ -69,6 +72,14 @@ public class SessionFactoryBuilderImpl implements SessionFactoryBuilderImplement
addSessionFactoryObservers( new SessionFactoryObserverForRegistration() ); addSessionFactoryObservers( new SessionFactoryObserverForRegistration() );
} }
/**
* @deprecated This constructor will be removed
*/
@Deprecated(since = "6.2", forRemoval = true)
public SessionFactoryBuilderImpl(MetadataImplementor metadata, SessionFactoryOptionsBuilder optionsBuilder) {
this( metadata, optionsBuilder, metadata.getTypeConfiguration().getMetadataBuildingContext().getBootstrapContext() );
}
@Override @Override
public SessionFactoryBuilder applyBeanManager(Object beanManager) { public SessionFactoryBuilder applyBeanManager(Object beanManager) {
this.optionsBuilder.applyBeanManager( beanManager ); this.optionsBuilder.applyBeanManager( beanManager );
@ -417,7 +428,7 @@ public class SessionFactoryBuilderImpl implements SessionFactoryBuilderImplement
@Override @Override
public SessionFactory build() { public SessionFactory build() {
return new SessionFactoryImpl( metadata, buildSessionFactoryOptions() ); return new SessionFactoryImpl( metadata, buildSessionFactoryOptions(), bootstrapContext );
} }
@Override @Override

View File

@ -34,7 +34,7 @@ public interface MetadataImplementor extends Metadata {
MetadataBuildingOptions getMetadataBuildingOptions(); MetadataBuildingOptions getMetadataBuildingOptions();
/** /**
* Access to the {@link TypeConfiguration} * Access to the {@link TypeConfiguration} belonging to the {@link BootstrapContext}
*/ */
TypeConfiguration getTypeConfiguration(); TypeConfiguration getTypeConfiguration();

View File

@ -10,11 +10,14 @@ import java.util.List;
import java.util.Locale; import java.util.Locale;
import org.hibernate.QueryException; import org.hibernate.QueryException;
import org.hibernate.metamodel.MappingMetamodel;
import org.hibernate.query.sqm.function.AbstractSqmSelfRenderingFunctionDescriptor; import org.hibernate.query.sqm.function.AbstractSqmSelfRenderingFunctionDescriptor;
import org.hibernate.query.sqm.produce.function.ArgumentTypesValidator; import org.hibernate.query.sqm.produce.function.ArgumentTypesValidator;
import org.hibernate.query.sqm.produce.function.ArgumentsValidator;
import org.hibernate.query.sqm.produce.function.StandardArgumentsValidators; import org.hibernate.query.sqm.produce.function.StandardArgumentsValidators;
import org.hibernate.query.sqm.produce.function.StandardFunctionArgumentTypeResolvers; import org.hibernate.query.sqm.produce.function.StandardFunctionArgumentTypeResolvers;
import org.hibernate.query.sqm.produce.function.StandardFunctionReturnTypeResolvers; import org.hibernate.query.sqm.produce.function.StandardFunctionReturnTypeResolvers;
import org.hibernate.query.sqm.tree.SqmTypedNode;
import org.hibernate.query.sqm.tree.expression.SqmLiteral; import org.hibernate.query.sqm.tree.expression.SqmLiteral;
import org.hibernate.sql.ast.SqlAstTranslator; import org.hibernate.sql.ast.SqlAstTranslator;
import org.hibernate.sql.ast.spi.SqlAppender; import org.hibernate.sql.ast.spi.SqlAppender;
@ -38,7 +41,9 @@ public class ChrLiteralEmulation extends AbstractSqmSelfRenderingFunctionDescrip
new ArgumentTypesValidator( new ArgumentTypesValidator(
StandardArgumentsValidators.composite( StandardArgumentsValidators.composite(
StandardArgumentsValidators.exactly(1), StandardArgumentsValidators.exactly(1),
(arguments, functionName, queryEngine) -> { new ArgumentsValidator() {
@Override
public void validate(List<? extends SqmTypedNode<?>> arguments, String functionName, MappingMetamodel metamodel) {
if ( !( arguments.get( 0 ) instanceof SqmLiteral<?> ) ) { if ( !( arguments.get( 0 ) instanceof SqmLiteral<?> ) ) {
throw new QueryException( throw new QueryException(
String.format( String.format(
@ -49,6 +54,7 @@ public class ChrLiteralEmulation extends AbstractSqmSelfRenderingFunctionDescrip
); );
} }
} }
}
), ),
INTEGER INTEGER
), ),

View File

@ -0,0 +1,80 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.internal;
import org.hibernate.HibernateException;
import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.engine.profile.Association;
import org.hibernate.engine.profile.Fetch;
import org.hibernate.engine.profile.FetchProfile;
import org.hibernate.metamodel.MappingMetamodel;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.persister.entity.Loadable;
import org.hibernate.type.Type;
import java.util.HashMap;
import java.util.Map;
/**
* Creates {@link FetchProfile}s.
*
* @author Gavin King
*/
public class FetchProfileHelper {
public static Map<String, FetchProfile> getFetchProfiles(
MetadataImplementor bootMetamodel,
MappingMetamodel mappingMetamodel) {
final Map<String, FetchProfile> fetchProfiles = new HashMap<>();
for ( org.hibernate.mapping.FetchProfile mappingProfile : bootMetamodel.getFetchProfiles() ) {
final FetchProfile fetchProfile = createFetchProfile( mappingMetamodel, mappingProfile );
fetchProfiles.put( fetchProfile.getName(), fetchProfile );
}
return fetchProfiles;
}
private static FetchProfile createFetchProfile(
MappingMetamodel mappingMetamodel,
org.hibernate.mapping.FetchProfile mappingProfile) {
final FetchProfile fetchProfile = new FetchProfile( mappingProfile.getName() );
for ( org.hibernate.mapping.FetchProfile.Fetch mappingFetch : mappingProfile.getFetches() ) {
// resolve the persister owning the fetch
final EntityPersister owner = getEntityPersister( mappingMetamodel, fetchProfile, mappingFetch );
// validate the specified association fetch
final Type associationType = owner.getPropertyType( mappingFetch.getAssociation() );
if ( associationType == null || !associationType.isAssociationType() ) {
throw new HibernateException( "Fetch profile [" + fetchProfile.getName()
+ "] specified an association that does not exist [" + mappingFetch.getAssociation() + "]" );
}
// resolve the style
final Fetch.Style fetchStyle = Fetch.Style.parse( mappingFetch.getStyle() );
// then construct the fetch instance...
fetchProfile.addFetch( new Association( owner, mappingFetch.getAssociation() ), fetchStyle );
((Loadable) owner).registerAffectingFetchProfile( fetchProfile.getName() );
}
return fetchProfile;
}
private static EntityPersister getEntityPersister(
MappingMetamodel mappingMetamodel,
FetchProfile fetchProfile,
org.hibernate.mapping.FetchProfile.Fetch mappingFetch) {
final String entityName = mappingMetamodel.getImportedName( mappingFetch.getEntity() );
if ( entityName != null ) {
EntityPersister persister = mappingMetamodel.getEntityDescriptor( entityName );
if ( persister != null ) {
return persister;
}
}
throw new HibernateException( "Unable to resolve entity reference [" + mappingFetch.getEntity()
+ "] in fetch profile [" + fetchProfile.getName() + "]" );
}
}

View File

@ -58,8 +58,6 @@ import org.hibernate.dialect.Dialect;
import org.hibernate.engine.config.spi.ConfigurationService; import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess; import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess;
import org.hibernate.engine.jdbc.spi.JdbcServices; import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.engine.profile.Association;
import org.hibernate.engine.profile.Fetch;
import org.hibernate.engine.profile.FetchProfile; import org.hibernate.engine.profile.FetchProfile;
import org.hibernate.engine.spi.FilterDefinition; import org.hibernate.engine.spi.FilterDefinition;
import org.hibernate.engine.spi.SessionBuilderImplementor; import org.hibernate.engine.spi.SessionBuilderImplementor;
@ -79,6 +77,7 @@ import org.hibernate.mapping.Collection;
import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.RootClass; import org.hibernate.mapping.RootClass;
import org.hibernate.metadata.CollectionMetadata; import org.hibernate.metadata.CollectionMetadata;
import org.hibernate.metamodel.MappingMetamodel;
import org.hibernate.metamodel.internal.RuntimeMetamodelsImpl; import org.hibernate.metamodel.internal.RuntimeMetamodelsImpl;
import org.hibernate.metamodel.model.domain.internal.MappingMetamodelImpl; import org.hibernate.metamodel.model.domain.internal.MappingMetamodelImpl;
import org.hibernate.metamodel.model.domain.spi.JpaMetamodelImplementor; import org.hibernate.metamodel.model.domain.spi.JpaMetamodelImplementor;
@ -86,8 +85,6 @@ import org.hibernate.metamodel.spi.MappingMetamodelImplementor;
import org.hibernate.metamodel.spi.MetamodelImplementor; import org.hibernate.metamodel.spi.MetamodelImplementor;
import org.hibernate.metamodel.spi.RuntimeMetamodelsImplementor; import org.hibernate.metamodel.spi.RuntimeMetamodelsImplementor;
import org.hibernate.metamodel.spi.RuntimeModelCreationContext; import org.hibernate.metamodel.spi.RuntimeModelCreationContext;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.persister.entity.Loadable;
import org.hibernate.persister.entity.SessionFactoryBasedWrapperOptions; import org.hibernate.persister.entity.SessionFactoryBasedWrapperOptions;
import org.hibernate.procedure.spi.ProcedureCallImplementor; import org.hibernate.procedure.spi.ProcedureCallImplementor;
import org.hibernate.proxy.EntityNotFoundDelegate; import org.hibernate.proxy.EntityNotFoundDelegate;
@ -132,6 +129,7 @@ import static org.hibernate.cfg.AvailableSettings.CREATE_EMPTY_COMPOSITES_ENABLE
import static org.hibernate.cfg.AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS; import static org.hibernate.cfg.AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS;
import static org.hibernate.cfg.AvailableSettings.JAKARTA_VALIDATION_FACTORY; import static org.hibernate.cfg.AvailableSettings.JAKARTA_VALIDATION_FACTORY;
import static org.hibernate.cfg.AvailableSettings.JPA_VALIDATION_FACTORY; import static org.hibernate.cfg.AvailableSettings.JPA_VALIDATION_FACTORY;
import static org.hibernate.internal.FetchProfileHelper.getFetchProfiles;
import static org.hibernate.internal.util.config.ConfigurationHelper.getBoolean; import static org.hibernate.internal.util.config.ConfigurationHelper.getBoolean;
import static org.hibernate.proxy.HibernateProxy.extractLazyInitializer; import static org.hibernate.proxy.HibernateProxy.extractLazyInitializer;
import static org.hibernate.resource.jdbc.spi.PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_RELEASE_AFTER_STATEMENT; import static org.hibernate.resource.jdbc.spi.PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_RELEASE_AFTER_STATEMENT;
@ -197,11 +195,20 @@ public class SessionFactoryImpl implements SessionFactoryImplementor {
private final transient SchemaManager schemaManager; private final transient SchemaManager schemaManager;
public SessionFactoryImpl(final MetadataImplementor bootMetamodel, final SessionFactoryOptions options) { /**
LOG.debug( "Building session factory" ); * @deprecated This constructor will be removed
*/
@Deprecated(since = "6.2", forRemoval = true)
public SessionFactoryImpl(MetadataImplementor bootMetamodel, SessionFactoryOptions options) {
this( bootMetamodel, options, bootMetamodel.getTypeConfiguration().getMetadataBuildingContext().getBootstrapContext() );
}
final TypeConfiguration typeConfiguration = bootMetamodel.getTypeConfiguration(); public SessionFactoryImpl(
final BootstrapContext bootstrapContext = typeConfiguration.getMetadataBuildingContext().getBootstrapContext(); final MetadataImplementor bootMetamodel,
final SessionFactoryOptions options,
final BootstrapContext bootstrapContext) {
LOG.debug( "Building session factory" );
final TypeConfiguration typeConfiguration = bootstrapContext.getTypeConfiguration();
sessionFactoryOptions = options; sessionFactoryOptions = options;
@ -248,15 +255,22 @@ public class SessionFactoryImpl implements SessionFactoryImplementor {
primeSecondLevelCacheRegions( bootMetamodel ); primeSecondLevelCacheRegions( bootMetamodel );
// we build this before creating the runtime metamodel
// because the persisters need the SqmFunctionRegistry
// to translate SQL formulas ... but, if we fix Dialect
// as I proposed, so that it can contribute functions
// to the SqmFunctionRegistry before the QueryEngine is
// created, then we can split creation of QueryEngine
// and SqmFunctionRegistry, instantiating just the
// registry here, and doing the engine later
queryEngine = QueryEngine.from( this, bootMetamodel ); queryEngine = QueryEngine.from( this, bootMetamodel );
bootstrapContext.getTypeConfiguration().scope( this ); // this is where creation of the runtime metamodel happens
final RuntimeMetamodelsImpl runtimeMetamodelsImpl = new RuntimeMetamodelsImpl(); final RuntimeMetamodelsImpl runtimeMetamodelsImpl = new RuntimeMetamodelsImpl();
runtimeMetamodels = runtimeMetamodelsImpl; runtimeMetamodels = runtimeMetamodelsImpl;
new RuntimeModelCreationContext() { new RuntimeModelCreationContext() {
final MappingMetamodelImpl mappingMetamodelImpl = final MappingMetamodelImpl mappingMetamodelImpl =
new MappingMetamodelImpl( typeConfiguration, serviceRegistry, options.getJpaCompliance() ); new MappingMetamodelImpl( typeConfiguration, serviceRegistry );
{ {
// need to set this before calling finishInitialization() // need to set this before calling finishInitialization()
runtimeMetamodelsImpl.setMappingMetamodel( mappingMetamodelImpl ); runtimeMetamodelsImpl.setMappingMetamodel( mappingMetamodelImpl );
@ -264,7 +278,6 @@ public class SessionFactoryImpl implements SessionFactoryImplementor {
mappingMetamodelImpl.finishInitialization( this ); mappingMetamodelImpl.finishInitialization( this );
// need to set this after calling finishInitialization() // need to set this after calling finishInitialization()
runtimeMetamodelsImpl.setJpaMetamodel( mappingMetamodelImpl.getJpaMetamodel() ); runtimeMetamodelsImpl.setJpaMetamodel( mappingMetamodelImpl.getJpaMetamodel() );
} }
@Override @Override
@ -334,8 +347,9 @@ public class SessionFactoryImpl implements SessionFactoryImplementor {
} }
}; };
// this needs to happen after persisters are all ready to go... // this needs to happen after the mapping metamodel is
fetchProfiles = getFetchProfiles( bootMetamodel, runtimeMetamodelsImpl ); // completely built, since we need to use the persisters
fetchProfiles = getFetchProfiles( bootMetamodel, runtimeMetamodels.getMappingMetamodel() );
defaultSessionOpenOptions = createDefaultSessionOpenOptionsIfPossible(); defaultSessionOpenOptions = createDefaultSessionOpenOptionsIfPossible();
temporarySessionOpenOptions = defaultSessionOpenOptions == null ? null : buildTemporarySessionOpenOptions(); temporarySessionOpenOptions = defaultSessionOpenOptions == null ? null : buildTemporarySessionOpenOptions();
@ -345,6 +359,13 @@ public class SessionFactoryImpl implements SessionFactoryImplementor {
currentSessionContext = buildCurrentSessionContext(); currentSessionContext = buildCurrentSessionContext();
// re-scope the TypeConfiguration to this SessionFactory,
// now that we are (almost) fully-initialized ... note,
// we could have done this earlier, but then it's hard to
// really know or control who's calling back to us while
// we're in an incompletely-initialized state
typeConfiguration.scope( this );
observer.sessionFactoryCreated( this ); observer.sessionFactoryCreated( this );
// As last operation, delete all caches from ReflectionManager // As last operation, delete all caches from ReflectionManager
@ -443,52 +464,6 @@ public class SessionFactoryImpl implements SessionFactoryImplementor {
} }
} }
private static Map<String, FetchProfile> getFetchProfiles(
MetadataImplementor bootMetamodel,
RuntimeMetamodelsImpl runtimeMetamodels) {
final Map<String, FetchProfile> fetchProfiles = new HashMap<>();
for ( org.hibernate.mapping.FetchProfile mappingProfile : bootMetamodel.getFetchProfiles() ) {
final FetchProfile fetchProfile = createFetchProfile( runtimeMetamodels, mappingProfile );
fetchProfiles.put( fetchProfile.getName(), fetchProfile );
}
return fetchProfiles;
}
private static FetchProfile createFetchProfile(
RuntimeMetamodelsImpl runtimeMetamodels,
org.hibernate.mapping.FetchProfile mappingProfile) {
final FetchProfile fetchProfile = new FetchProfile( mappingProfile.getName() );
for ( org.hibernate.mapping.FetchProfile.Fetch mappingFetch : mappingProfile.getFetches() ) {
// resolve the persister owning the fetch
final EntityPersister owner = getEntityPersister( runtimeMetamodels, fetchProfile, mappingFetch );
// validate the specified association fetch
final Type associationType = owner.getPropertyType( mappingFetch.getAssociation() );
if ( associationType == null || !associationType.isAssociationType() ) {
throw new HibernateException( "Fetch profile [" + fetchProfile.getName() + "] specified an invalid association" );
}
// resolve the style
final Fetch.Style fetchStyle = Fetch.Style.parse( mappingFetch.getStyle() );
// then construct the fetch instance...
fetchProfile.addFetch( new Association( owner, mappingFetch.getAssociation() ), fetchStyle );
((Loadable) owner).registerAffectingFetchProfile( fetchProfile.getName() );
}
return fetchProfile;
}
private static EntityPersister getEntityPersister(RuntimeMetamodelsImpl runtimeMetamodels, FetchProfile fetchProfile, org.hibernate.mapping.FetchProfile.Fetch mappingFetch) {
final String entityName = runtimeMetamodels.getImportedName( mappingFetch.getEntity() );
if ( entityName != null ) {
EntityPersister persister = runtimeMetamodels.getMappingMetamodel().getEntityDescriptor( entityName );
if ( persister != null ) {
return persister;
}
}
throw new HibernateException( "Unable to resolve entity reference [" + mappingFetch.getEntity()
+ "] in fetch profile [" + fetchProfile.getName() + "]" );
}
private static Map<String, Object> getSettings(SessionFactoryOptions options, SessionFactoryServiceRegistry serviceRegistry) { private static Map<String, Object> getSettings(SessionFactoryOptions options, SessionFactoryServiceRegistry serviceRegistry) {
final Map<String, Object> settings = serviceRegistry.getService( ConfigurationService.class ).getSettings(); final Map<String, Object> settings = serviceRegistry.getService( ConfigurationService.class ).getSettings();

View File

@ -242,7 +242,12 @@ public class AttributeFactory {
final JavaType<Y> baseJtd = context.getTypeConfiguration() final JavaType<Y> baseJtd = context.getTypeConfiguration()
.getJavaTypeRegistry() .getJavaTypeRegistry()
.resolveDescriptor( anyType.getReturnedClass() ); .resolveDescriptor( anyType.getReturnedClass() );
return (DomainType<Y>) new AnyMappingDomainTypeImpl( anyType, (JavaType<Class>) baseJtd, context.getTypeConfiguration() ); return (DomainType<Y>) new AnyMappingDomainTypeImpl(
anyType,
(JavaType<Class>) baseJtd,
context.getTypeConfiguration(),
context.getMetamodel()
);
} }
case EMBEDDABLE: { case EMBEDDABLE: {
final Component component = (Component) typeContext.getHibernateValue(); final Component component = (Component) typeContext.getHibernateValue();

View File

@ -33,7 +33,6 @@ import org.hibernate.metamodel.model.domain.BasicDomainType;
import org.hibernate.metamodel.model.domain.EmbeddableDomainType; import org.hibernate.metamodel.model.domain.EmbeddableDomainType;
import org.hibernate.metamodel.model.domain.EntityDomainType; import org.hibernate.metamodel.model.domain.EntityDomainType;
import org.hibernate.metamodel.model.domain.IdentifiableDomainType; import org.hibernate.metamodel.model.domain.IdentifiableDomainType;
import org.hibernate.metamodel.model.domain.JpaMetamodel;
import org.hibernate.metamodel.model.domain.ManagedDomainType; import org.hibernate.metamodel.model.domain.ManagedDomainType;
import org.hibernate.metamodel.model.domain.MappedSuperclassDomainType; import org.hibernate.metamodel.model.domain.MappedSuperclassDomainType;
import org.hibernate.metamodel.model.domain.PersistentAttribute; import org.hibernate.metamodel.model.domain.PersistentAttribute;
@ -45,6 +44,7 @@ import org.hibernate.metamodel.model.domain.internal.EntityTypeImpl;
import org.hibernate.metamodel.model.domain.internal.MappedSuperclassTypeImpl; import org.hibernate.metamodel.model.domain.internal.MappedSuperclassTypeImpl;
import org.hibernate.metamodel.model.domain.internal.MappingMetamodelImpl; import org.hibernate.metamodel.model.domain.internal.MappingMetamodelImpl;
import org.hibernate.metamodel.model.domain.internal.PrimitiveBasicTypeImpl; import org.hibernate.metamodel.model.domain.internal.PrimitiveBasicTypeImpl;
import org.hibernate.metamodel.model.domain.spi.JpaMetamodelImplementor;
import org.hibernate.metamodel.spi.RuntimeModelCreationContext; import org.hibernate.metamodel.spi.RuntimeModelCreationContext;
import org.hibernate.type.descriptor.java.JavaType; import org.hibernate.type.descriptor.java.JavaType;
import org.hibernate.type.descriptor.java.spi.EntityJavaType; import org.hibernate.type.descriptor.java.spi.EntityJavaType;
@ -73,7 +73,7 @@ import jakarta.persistence.metamodel.Type;
public class MetadataContext { public class MetadataContext {
private static final EntityManagerMessageLogger LOG = HEMLogging.messageLogger( MetadataContext.class ); private static final EntityManagerMessageLogger LOG = HEMLogging.messageLogger( MetadataContext.class );
private final JpaMetamodel jpaMetamodel; private final JpaMetamodelImplementor jpaMetamodel;
private final RuntimeModelCreationContext runtimeModelCreationContext; private final RuntimeModelCreationContext runtimeModelCreationContext;
private final Set<MappedSuperclass> knownMappedSuperclasses; private final Set<MappedSuperclass> knownMappedSuperclasses;
@ -103,7 +103,7 @@ public class MetadataContext {
private final MappingMetamodel metamodel; private final MappingMetamodel metamodel;
public MetadataContext( public MetadataContext(
JpaMetamodel jpaMetamodel, JpaMetamodelImplementor jpaMetamodel,
MappingMetamodel mappingMetamodel, MappingMetamodel mappingMetamodel,
MetadataImplementor bootMetamodel, MetadataImplementor bootMetamodel,
JpaStaticMetaModelPopulationSetting jpaStaticMetaModelPopulationSetting, JpaStaticMetaModelPopulationSetting jpaStaticMetaModelPopulationSetting,
@ -122,7 +122,7 @@ public class MetadataContext {
return runtimeModelCreationContext; return runtimeModelCreationContext;
} }
public JpaMetamodel getJpaMetamodel() { public JpaMetamodelImplementor getJpaMetamodel() {
return jpaMetamodel; return jpaMetamodel;
} }

View File

@ -163,7 +163,7 @@ public class SimpleNaturalIdMapping extends AbstractNaturalIdMapping implements
normalizedValue = naturalIdToLoad; normalizedValue = naturalIdToLoad;
} }
if ( getTypeConfiguration().getSessionFactory().getJpaMetamodel().getJpaCompliance().isLoadByIdComplianceEnabled() ) { if ( getTypeConfiguration().getJpaCompliance().isLoadByIdComplianceEnabled() ) {
return normalizedValue; return normalizedValue;
} }
return getJavaType().coerce( normalizedValue, this ); return getJavaType().coerce( normalizedValue, this );

View File

@ -6,21 +6,22 @@
*/ */
package org.hibernate.metamodel.model.domain; package org.hibernate.metamodel.model.domain;
import org.hibernate.metamodel.model.domain.spi.JpaMetamodelImplementor;
import org.hibernate.type.descriptor.java.JavaType; import org.hibernate.type.descriptor.java.JavaType;
/** /**
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public abstract class AbstractDomainType<J> implements SimpleDomainType<J> { public abstract class AbstractDomainType<J> implements SimpleDomainType<J> {
private final JpaMetamodel domainMetamodel; private final JpaMetamodelImplementor domainMetamodel;
private final JavaType<J> javaType; private final JavaType<J> javaType;
public AbstractDomainType(JavaType<J> javaType, JpaMetamodel domainMetamodel) { public AbstractDomainType(JavaType<J> javaType, JpaMetamodelImplementor domainMetamodel) {
this.javaType = javaType; this.javaType = javaType;
this.domainMetamodel = domainMetamodel; this.domainMetamodel = domainMetamodel;
} }
protected JpaMetamodel jpaMetamodel() { protected JpaMetamodelImplementor jpaMetamodel() {
return domainMetamodel; return domainMetamodel;
} }

View File

@ -22,6 +22,7 @@ import org.hibernate.metamodel.mapping.EntityIdentifierMapping;
import org.hibernate.metamodel.model.domain.internal.BasicSqmPathSource; import org.hibernate.metamodel.model.domain.internal.BasicSqmPathSource;
import org.hibernate.metamodel.model.domain.internal.EmbeddedSqmPathSource; import org.hibernate.metamodel.model.domain.internal.EmbeddedSqmPathSource;
import org.hibernate.metamodel.model.domain.internal.NonAggregatedCompositeSqmPathSource; import org.hibernate.metamodel.model.domain.internal.NonAggregatedCompositeSqmPathSource;
import org.hibernate.metamodel.model.domain.spi.JpaMetamodelImplementor;
import org.hibernate.query.sqm.SqmPathSource; import org.hibernate.query.sqm.SqmPathSource;
import org.hibernate.type.descriptor.java.JavaType; import org.hibernate.type.descriptor.java.JavaType;
import org.hibernate.type.descriptor.java.spi.PrimitiveJavaType; import org.hibernate.type.descriptor.java.spi.PrimitiveJavaType;
@ -64,7 +65,7 @@ public abstract class AbstractIdentifiableType<J>
boolean hasIdClass, boolean hasIdClass,
boolean hasIdentifierProperty, boolean hasIdentifierProperty,
boolean versioned, boolean versioned,
JpaMetamodel jpaMetamodel) { JpaMetamodelImplementor jpaMetamodel) {
super( typeName, javaType, superType, jpaMetamodel ); super( typeName, javaType, superType, jpaMetamodel );
this.hasIdClass = hasIdClass; this.hasIdClass = hasIdClass;
this.hasIdentifierProperty = hasIdentifierProperty; this.hasIdentifierProperty = hasIdentifierProperty;

View File

@ -31,12 +31,13 @@ import jakarta.persistence.metamodel.SingularAttribute;
import org.hibernate.graph.internal.SubGraphImpl; import org.hibernate.graph.internal.SubGraphImpl;
import org.hibernate.graph.spi.SubGraphImplementor; import org.hibernate.graph.spi.SubGraphImplementor;
import org.hibernate.internal.util.collections.CollectionHelper; import org.hibernate.internal.util.collections.CollectionHelper;
import org.hibernate.metamodel.MappingMetamodel;
import org.hibernate.metamodel.RepresentationMode; import org.hibernate.metamodel.RepresentationMode;
import org.hibernate.metamodel.RuntimeMetamodels;
import org.hibernate.metamodel.mapping.EntityMappingType; import org.hibernate.metamodel.mapping.EntityMappingType;
import org.hibernate.metamodel.mapping.MappingModelHelper; import org.hibernate.metamodel.mapping.MappingModelHelper;
import org.hibernate.metamodel.model.domain.internal.AttributeContainer; import org.hibernate.metamodel.model.domain.internal.AttributeContainer;
import org.hibernate.metamodel.model.domain.internal.DomainModelHelper; import org.hibernate.metamodel.model.domain.internal.DomainModelHelper;
import org.hibernate.metamodel.model.domain.spi.JpaMetamodelImplementor;
import org.hibernate.query.SemanticException; import org.hibernate.query.SemanticException;
import org.hibernate.type.descriptor.java.JavaType; import org.hibernate.type.descriptor.java.JavaType;
@ -62,7 +63,7 @@ public abstract class AbstractManagedType<J>
String hibernateTypeName, String hibernateTypeName,
JavaType<J> javaType, JavaType<J> javaType,
ManagedDomainType<? super J> superType, ManagedDomainType<? super J> superType,
JpaMetamodel domainMetamodel) { JpaMetamodelImplementor domainMetamodel) {
super( javaType, domainMetamodel ); super( javaType, domainMetamodel );
this.hibernateTypeName = hibernateTypeName; this.hibernateTypeName = hibernateTypeName;
this.superType = superType; this.superType = superType;
@ -197,13 +198,11 @@ public abstract class AbstractManagedType<J>
if ( attribute1 == attribute2 ) { if ( attribute1 == attribute2 ) {
return true; return true;
} }
final RuntimeMetamodels runtimeMetamodels = jpaMetamodel().getTypeConfiguration() final MappingMetamodel runtimeMetamodels = jpaMetamodel().getMappingMetamodel();
.getSessionFactory() final EntityMappingType entity1 = runtimeMetamodels.getEntityDescriptor(
.getRuntimeMetamodels();
final EntityMappingType entity1 = runtimeMetamodels.getEntityMappingType(
attribute1.getDeclaringType().getTypeName() attribute1.getDeclaringType().getTypeName()
); );
final EntityMappingType entity2 = runtimeMetamodels.getEntityMappingType( final EntityMappingType entity2 = runtimeMetamodels.getEntityDescriptor(
attribute2.getDeclaringType().getTypeName() attribute2.getDeclaringType().getTypeName()
); );

View File

@ -6,6 +6,7 @@
*/ */
package org.hibernate.metamodel.model.domain.internal; package org.hibernate.metamodel.model.domain.internal;
import org.hibernate.metamodel.MappingMetamodel;
import org.hibernate.metamodel.RepresentationMode; import org.hibernate.metamodel.RepresentationMode;
import org.hibernate.metamodel.model.convert.spi.BasicValueConverter; import org.hibernate.metamodel.model.convert.spi.BasicValueConverter;
import org.hibernate.persister.entity.EntityPersister; import org.hibernate.persister.entity.EntityPersister;
@ -17,15 +18,19 @@ import org.hibernate.type.spi.TypeConfiguration;
public class AnyDiscriminatorConverter implements BasicValueConverter<Class, Object> { public class AnyDiscriminatorConverter implements BasicValueConverter<Class, Object> {
private final MetaType modelPart; private final MetaType modelPart;
private BasicType discriminatorBasicType; private final BasicType discriminatorBasicType;
private TypeConfiguration typeConfiguration; private final TypeConfiguration typeConfiguration;
private final MappingMetamodel mappingMetamodel;
public AnyDiscriminatorConverter( public AnyDiscriminatorConverter(
MetaType modelPart, BasicType discriminatorBasicType, MetaType modelPart,
TypeConfiguration typeConfiguration) { BasicType discriminatorBasicType,
TypeConfiguration typeConfiguration,
MappingMetamodel mappingMetamodel) {
this.modelPart = modelPart; this.modelPart = modelPart;
this.discriminatorBasicType = discriminatorBasicType; this.discriminatorBasicType = discriminatorBasicType;
this.typeConfiguration = typeConfiguration; this.typeConfiguration = typeConfiguration;
this.mappingMetamodel = mappingMetamodel;
} }
@Override @Override
@ -35,10 +40,7 @@ public class AnyDiscriminatorConverter implements BasicValueConverter<Class, Obj
} }
final String entityName = modelPart.getDiscriminatorValuesToEntityNameMap().get( discriminatorValue ); final String entityName = modelPart.getDiscriminatorValuesToEntityNameMap().get( discriminatorValue );
final EntityPersister entityDescriptor = typeConfiguration.getSessionFactory() final EntityPersister entityDescriptor = mappingMetamodel.getEntityDescriptor( entityName );
.getRuntimeMetamodels()
.getMappingMetamodel()
.getEntityDescriptor( entityName );
assert entityDescriptor.getRepresentationStrategy().getMode() == RepresentationMode.POJO; assert entityDescriptor.getRepresentationStrategy().getMode() == RepresentationMode.POJO;
return entityDescriptor.getJavaType().getJavaTypeClass(); return entityDescriptor.getJavaType().getJavaTypeClass();
} }

View File

@ -6,11 +6,11 @@
*/ */
package org.hibernate.metamodel.model.domain.internal; package org.hibernate.metamodel.model.domain.internal;
import org.hibernate.metamodel.MappingMetamodel;
import org.hibernate.metamodel.model.domain.AnyMappingDomainType; import org.hibernate.metamodel.model.domain.AnyMappingDomainType;
import org.hibernate.metamodel.model.domain.SimpleDomainType; import org.hibernate.metamodel.model.domain.SimpleDomainType;
import org.hibernate.type.AnyType; import org.hibernate.type.AnyType;
import org.hibernate.type.BasicType; import org.hibernate.type.BasicType;
import org.hibernate.type.ConvertedBasicType;
import org.hibernate.type.MetaType; import org.hibernate.type.MetaType;
import org.hibernate.type.descriptor.java.JavaType; import org.hibernate.type.descriptor.java.JavaType;
import org.hibernate.type.internal.ConvertedBasicTypeImpl; import org.hibernate.type.internal.ConvertedBasicTypeImpl;
@ -24,7 +24,11 @@ public class AnyMappingDomainTypeImpl implements AnyMappingDomainType<Class> {
private final JavaType<Class> baseJtd; private final JavaType<Class> baseJtd;
private final BasicType<Class> anyDiscriminatorType; private final BasicType<Class> anyDiscriminatorType;
public AnyMappingDomainTypeImpl(AnyType anyType, JavaType<Class> baseJtd, TypeConfiguration typeConfiguration) { public AnyMappingDomainTypeImpl(
AnyType anyType,
JavaType<Class> baseJtd,
TypeConfiguration typeConfiguration,
MappingMetamodel mappingMetamodel) {
this.anyType = anyType; this.anyType = anyType;
this.baseJtd = baseJtd; this.baseJtd = baseJtd;
final MetaType discriminatorType = (MetaType) anyType.getDiscriminatorType(); final MetaType discriminatorType = (MetaType) anyType.getDiscriminatorType();
@ -33,7 +37,12 @@ public class AnyMappingDomainTypeImpl implements AnyMappingDomainType<Class> {
new ConvertedBasicTypeImpl<>( new ConvertedBasicTypeImpl<>(
null, // no name null, // no name
discriminatorBasicType.getJdbcType(), discriminatorBasicType.getJdbcType(),
new AnyDiscriminatorConverter( discriminatorType, discriminatorBasicType, typeConfiguration ) new AnyDiscriminatorConverter(
discriminatorType,
discriminatorBasicType,
typeConfiguration,
mappingMetamodel
)
); );
} }

View File

@ -12,7 +12,7 @@ import org.hibernate.graph.internal.SubGraphImpl;
import org.hibernate.graph.spi.SubGraphImplementor; import org.hibernate.graph.spi.SubGraphImplementor;
import org.hibernate.metamodel.model.domain.AbstractManagedType; import org.hibernate.metamodel.model.domain.AbstractManagedType;
import org.hibernate.metamodel.model.domain.EmbeddableDomainType; import org.hibernate.metamodel.model.domain.EmbeddableDomainType;
import org.hibernate.metamodel.model.domain.JpaMetamodel; import org.hibernate.metamodel.model.domain.spi.JpaMetamodelImplementor;
import org.hibernate.type.descriptor.java.JavaType; import org.hibernate.type.descriptor.java.JavaType;
/** /**
@ -31,7 +31,7 @@ public class EmbeddableTypeImpl<J>
public EmbeddableTypeImpl( public EmbeddableTypeImpl(
JavaType<J> javaType, JavaType<J> javaType,
boolean isDynamic, boolean isDynamic,
JpaMetamodel domainMetamodel) { JpaMetamodelImplementor domainMetamodel) {
super( javaType.getJavaType().getTypeName(), javaType, null, domainMetamodel ); super( javaType.getJavaType().getTypeName(), javaType, null, domainMetamodel );
this.isDynamic = isDynamic; this.isDynamic = isDynamic;
} }

View File

@ -23,8 +23,8 @@ import org.hibernate.metamodel.model.domain.IdentifiableDomainType;
import org.hibernate.metamodel.model.domain.JpaMetamodel; import org.hibernate.metamodel.model.domain.JpaMetamodel;
import org.hibernate.metamodel.model.domain.PersistentAttribute; import org.hibernate.metamodel.model.domain.PersistentAttribute;
import org.hibernate.metamodel.model.domain.SingularPersistentAttribute; import org.hibernate.metamodel.model.domain.SingularPersistentAttribute;
import org.hibernate.metamodel.model.domain.spi.JpaMetamodelImplementor;
import org.hibernate.persister.entity.DiscriminatorMetadata; import org.hibernate.persister.entity.DiscriminatorMetadata;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.persister.entity.Queryable; import org.hibernate.persister.entity.Queryable;
import org.hibernate.query.sqm.SqmPathSource; import org.hibernate.query.sqm.SqmPathSource;
import org.hibernate.query.sqm.tree.domain.SqmPath; import org.hibernate.query.sqm.tree.domain.SqmPath;
@ -47,7 +47,7 @@ public class EntityTypeImpl<J>
JavaType<J> javaType, JavaType<J> javaType,
IdentifiableDomainType<? super J> superType, IdentifiableDomainType<? super J> superType,
PersistentClass persistentClass, PersistentClass persistentClass,
JpaMetamodel jpaMetamodel) { JpaMetamodelImplementor jpaMetamodel) {
super( super(
persistentClass.getEntityName(), persistentClass.getEntityName(),
javaType, javaType,
@ -61,10 +61,8 @@ public class EntityTypeImpl<J>
this.jpaEntityName = persistentClass.getJpaEntityName(); this.jpaEntityName = persistentClass.getJpaEntityName();
final Queryable entityDescriptor = (Queryable) jpaMetamodel.getTypeConfiguration() final Queryable entityDescriptor = (Queryable)
.getSessionFactory() jpaMetamodel.getMappingMetamodel()
.getRuntimeMetamodels()
.getMappingMetamodel()
.getEntityDescriptor( getHibernateEntityName() ); .getEntityDescriptor( getHibernateEntityName() );
final DiscriminatorMetadata discriminatorMetadata = entityDescriptor.getTypeDiscriminatorMetadata(); final DiscriminatorMetadata discriminatorMetadata = entityDescriptor.getTypeDiscriminatorMetadata();
final DomainType discriminatorType; final DomainType discriminatorType;
@ -83,7 +81,7 @@ public class EntityTypeImpl<J>
entityDescriptor entityDescriptor
); );
} }
public EntityTypeImpl(JavaType<J> javaTypeDescriptor, JpaMetamodel jpaMetamodel) { public EntityTypeImpl(JavaType<J> javaTypeDescriptor, JpaMetamodelImplementor jpaMetamodel) {
super( super(
javaTypeDescriptor.getJavaTypeClass().getName(), javaTypeDescriptor.getJavaTypeClass().getName(),
javaTypeDescriptor, javaTypeDescriptor,

View File

@ -84,7 +84,7 @@ public class JpaMetamodelImpl implements JpaMetamodelImplementor, Serializable {
} }
private final TypeConfiguration typeConfiguration; private final TypeConfiguration typeConfiguration;
private final JpaCompliance jpaCompliance; private final MappingMetamodel mappingMetamodel;
private final Map<String, EntityDomainType<?>> jpaEntityTypeMap = new TreeMap<>(); // Need ordering for deterministic implementers list in SqmPolymorphicRootDescriptor private final Map<String, EntityDomainType<?>> jpaEntityTypeMap = new TreeMap<>(); // Need ordering for deterministic implementers list in SqmPolymorphicRootDescriptor
private final Map<Class<?>, ManagedDomainType<?>> jpaManagedTypeMap = new HashMap<>(); private final Map<Class<?>, ManagedDomainType<?>> jpaManagedTypeMap = new HashMap<>();
@ -102,9 +102,9 @@ public class JpaMetamodelImpl implements JpaMetamodelImplementor, Serializable {
private final Map<String,Object> knownInvalidnameToImportMap = new ConcurrentHashMap<>(); private final Map<String,Object> knownInvalidnameToImportMap = new ConcurrentHashMap<>();
public JpaMetamodelImpl(TypeConfiguration typeConfiguration, JpaCompliance jpaCompliance) { public JpaMetamodelImpl(TypeConfiguration typeConfiguration, MappingMetamodel mappingMetamodel) {
this.typeConfiguration = typeConfiguration; this.typeConfiguration = typeConfiguration;
this.jpaCompliance = jpaCompliance; this.mappingMetamodel = mappingMetamodel;
} }
@Override @Override
@ -114,7 +114,7 @@ public class JpaMetamodelImpl implements JpaMetamodelImplementor, Serializable {
@Override @Override
public JpaCompliance getJpaCompliance() { public JpaCompliance getJpaCompliance() {
return jpaCompliance; return typeConfiguration.getJpaCompliance();
} }
@Override @Override
@ -455,9 +455,7 @@ public class JpaMetamodelImpl implements JpaMetamodelImplementor, Serializable {
if ( superType != null if ( superType != null
&& superType.getPersistenceType() == Type.PersistenceType.ENTITY && superType.getPersistenceType() == Type.PersistenceType.ENTITY
&& javaType.isAssignableFrom( superType.getJavaType() ) ) { && javaType.isAssignableFrom( superType.getJavaType() ) ) {
final EntityMappingType superMapping = typeConfiguration.getSessionFactory() final EntityMappingType superMapping = getMappingMetamodel()
.getRuntimeMetamodels()
.getMappingMetamodel()
.getEntityDescriptor( ( (EntityDomainType<?>) superType ).getHibernateEntityName() ); .getEntityDescriptor( ( (EntityDomainType<?>) superType ).getHibernateEntityName() );
if ( !superMapping.isExplicitPolymorphism() ) { if ( !superMapping.isExplicitPolymorphism() ) {
continue; continue;
@ -465,9 +463,7 @@ public class JpaMetamodelImpl implements JpaMetamodelImplementor, Serializable {
} }
// it should not be added if it is mapped with explicit polymorphism itself // it should not be added if it is mapped with explicit polymorphism itself
final EntityMappingType entityPersister = typeConfiguration.getSessionFactory() final EntityMappingType entityPersister = getMappingMetamodel()
.getRuntimeMetamodels()
.getMappingMetamodel()
.getEntityDescriptor( entityDomainType.getHibernateEntityName() ); .getEntityDescriptor( entityDomainType.getHibernateEntityName() );
if ( entityPersister.isExplicitPolymorphism() ) { if ( entityPersister.isExplicitPolymorphism() ) {
continue; continue;
@ -492,6 +488,11 @@ public class JpaMetamodelImpl implements JpaMetamodelImplementor, Serializable {
throw new IllegalArgumentException( "Could not resolve entity reference : " + javaType.getName() ); throw new IllegalArgumentException( "Could not resolve entity reference : " + javaType.getName() );
} }
@Override
public MappingMetamodel getMappingMetamodel() {
return mappingMetamodel;
}
public void processJpa( public void processJpa(
MetadataImplementor bootMetamodel, MetadataImplementor bootMetamodel,
MappingMetamodel mappingMetamodel, MappingMetamodel mappingMetamodel,

View File

@ -13,10 +13,10 @@ import org.hibernate.metamodel.UnsupportedMappingException;
import org.hibernate.metamodel.mapping.EntityIdentifierMapping; import org.hibernate.metamodel.mapping.EntityIdentifierMapping;
import org.hibernate.metamodel.model.domain.AbstractIdentifiableType; import org.hibernate.metamodel.model.domain.AbstractIdentifiableType;
import org.hibernate.metamodel.model.domain.IdentifiableDomainType; import org.hibernate.metamodel.model.domain.IdentifiableDomainType;
import org.hibernate.metamodel.model.domain.JpaMetamodel;
import org.hibernate.metamodel.model.domain.MappedSuperclassDomainType; import org.hibernate.metamodel.model.domain.MappedSuperclassDomainType;
import org.hibernate.metamodel.model.domain.PersistentAttribute; import org.hibernate.metamodel.model.domain.PersistentAttribute;
import org.hibernate.metamodel.model.domain.SingularPersistentAttribute; import org.hibernate.metamodel.model.domain.SingularPersistentAttribute;
import org.hibernate.metamodel.model.domain.spi.JpaMetamodelImplementor;
import org.hibernate.query.sqm.SqmPathSource; import org.hibernate.query.sqm.SqmPathSource;
import org.hibernate.query.sqm.tree.domain.SqmPath; import org.hibernate.query.sqm.tree.domain.SqmPath;
import org.hibernate.type.descriptor.java.JavaType; import org.hibernate.type.descriptor.java.JavaType;
@ -30,7 +30,7 @@ public class MappedSuperclassTypeImpl<J> extends AbstractIdentifiableType<J> imp
JavaType<J> javaType, JavaType<J> javaType,
MappedSuperclass mappedSuperclass, MappedSuperclass mappedSuperclass,
IdentifiableDomainType<? super J> superType, IdentifiableDomainType<? super J> superType,
JpaMetamodel jpaMetamodel) { JpaMetamodelImplementor jpaMetamodel) {
super( super(
javaType.getJavaType().getTypeName(), javaType.getJavaType().getTypeName(),
javaType, javaType,

View File

@ -79,6 +79,7 @@ import jakarta.persistence.metamodel.EmbeddableType;
import jakarta.persistence.metamodel.EntityType; import jakarta.persistence.metamodel.EntityType;
import jakarta.persistence.metamodel.ManagedType; import jakarta.persistence.metamodel.ManagedType;
import static org.hibernate.internal.util.collections.ArrayHelper.EMPTY_STRING_ARRAY;
import static org.hibernate.metamodel.internal.JpaMetaModelPopulationSetting.determineJpaMetaModelPopulationSetting; import static org.hibernate.metamodel.internal.JpaMetaModelPopulationSetting.determineJpaMetaModelPopulationSetting;
import static org.hibernate.metamodel.internal.JpaStaticMetaModelPopulationSetting.determineJpaStaticMetaModelPopulationSetting; import static org.hibernate.metamodel.internal.JpaStaticMetaModelPopulationSetting.determineJpaStaticMetaModelPopulationSetting;
@ -99,7 +100,7 @@ public class MappingMetamodelImpl implements MappingMetamodelImplementor, Metamo
//NOTE: we suppress deprecation warnings because at the moment we //NOTE: we suppress deprecation warnings because at the moment we
//implement a deprecated API so have to override deprecated things //implement a deprecated API so have to override deprecated things
private static final String[] EMPTY_IMPLEMENTORS = ArrayHelper.EMPTY_STRING_ARRAY; private static final String[] EMPTY_IMPLEMENTORS = EMPTY_STRING_ARRAY;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// JpaMetamodel // JpaMetamodel
@ -161,13 +162,10 @@ public class MappingMetamodelImpl implements MappingMetamodelImplementor, Metamo
private final Map<String, String[]> implementorsCache = new ConcurrentHashMap<>(); private final Map<String, String[]> implementorsCache = new ConcurrentHashMap<>();
private final Map<TupleType<?>, MappingModelExpressible<?>> tupleTypeCache = new ConcurrentHashMap<>(); private final Map<TupleType<?>, MappingModelExpressible<?>> tupleTypeCache = new ConcurrentHashMap<>();
public MappingMetamodelImpl( public MappingMetamodelImpl(TypeConfiguration typeConfiguration, ServiceRegistry serviceRegistry) {
TypeConfiguration typeConfiguration,
ServiceRegistry serviceRegistry,
JpaCompliance jpaCompliance) {
this.serviceRegistry = serviceRegistry; this.serviceRegistry = serviceRegistry;
this.typeConfiguration = typeConfiguration; this.typeConfiguration = typeConfiguration;
this.jpaMetamodel = new JpaMetamodelImpl( typeConfiguration, jpaCompliance ); this.jpaMetamodel = new JpaMetamodelImpl( typeConfiguration, this );
} }
public JpaMetamodelImplementor getJpaMetamodel() { public JpaMetamodelImplementor getJpaMetamodel() {
@ -743,7 +741,7 @@ public class MappingMetamodelImpl implements MappingMetamodelImplementor, Metamo
} }
} }
return results.toArray( ArrayHelper.EMPTY_STRING_ARRAY ); return results.toArray( EMPTY_STRING_ARRAY );
} }
@Override @Override

View File

@ -6,6 +6,7 @@
*/ */
package org.hibernate.metamodel.model.domain.spi; package org.hibernate.metamodel.model.domain.spi;
import org.hibernate.metamodel.MappingMetamodel;
import org.hibernate.metamodel.model.domain.JpaMetamodel; import org.hibernate.metamodel.model.domain.JpaMetamodel;
/** /**
@ -14,4 +15,5 @@ import org.hibernate.metamodel.model.domain.JpaMetamodel;
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public interface JpaMetamodelImplementor extends JpaMetamodel { public interface JpaMetamodelImplementor extends JpaMetamodel {
MappingMetamodel getMappingMetamodel();
} }

View File

@ -105,7 +105,7 @@ public class QueryParameterBindingImpl<T> implements QueryParameterBinding<T>, J
return; return;
} }
if ( ! getTypeConfiguration().getSessionFactory().getJpaMetamodel().getJpaCompliance().isLoadByIdComplianceEnabled() ) { if ( ! getTypeConfiguration().getJpaCompliance().isLoadByIdComplianceEnabled() ) {
try { try {
if ( bindType != null ) { if ( bindType != null ) {
value = coerce( value, bindType ); value = coerce( value, bindType );
@ -211,7 +211,7 @@ public class QueryParameterBindingImpl<T> implements QueryParameterBinding<T>, J
bindType = queryParameter.getHibernateType(); bindType = queryParameter.getHibernateType();
} }
if ( ! getTypeConfiguration().getSessionFactory().getJpaMetamodel().getJpaCompliance().isLoadByIdComplianceEnabled() ) { if ( ! getTypeConfiguration().getJpaCompliance().isLoadByIdComplianceEnabled() ) {
if ( bindType != null ) { if ( bindType != null ) {
try { try {
value = coerce( value, bindType ); value = coerce( value, bindType );

View File

@ -7,7 +7,6 @@
package org.hibernate.query.spi; package org.hibernate.query.spi;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
@ -28,6 +27,7 @@ import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.internal.util.config.ConfigurationHelper;
import org.hibernate.jpa.spi.JpaCompliance; import org.hibernate.jpa.spi.JpaCompliance;
import org.hibernate.metamodel.model.domain.spi.JpaMetamodelImplementor; import org.hibernate.metamodel.model.domain.spi.JpaMetamodelImplementor;
import org.hibernate.query.BindableType;
import org.hibernate.query.criteria.ValueHandlingMode; import org.hibernate.query.criteria.ValueHandlingMode;
import org.hibernate.query.hql.HqlTranslator; import org.hibernate.query.hql.HqlTranslator;
import org.hibernate.query.hql.internal.StandardHqlTranslator; import org.hibernate.query.hql.internal.StandardHqlTranslator;
@ -49,6 +49,8 @@ import org.hibernate.type.spi.TypeConfiguration;
import org.jboss.logging.Logger; import org.jboss.logging.Logger;
import static java.util.Comparator.comparingInt;
/** /**
* Aggregation and encapsulation of the components Hibernate uses * Aggregation and encapsulation of the components Hibernate uses
* to execute queries (HQL, Criteria and native) * to execute queries (HQL, Criteria and native)
@ -56,7 +58,7 @@ import org.jboss.logging.Logger;
* @author Steve Ebersole * @author Steve Ebersole
*/ */
@Incubating @Incubating
public class QueryEngine { public class QueryEngine implements QueryParameterBindingTypeResolver {
/** /**
* The default soft reference count. * The default soft reference count.
@ -67,33 +69,58 @@ public class QueryEngine {
public static QueryEngine from(SessionFactoryImplementor sessionFactory, MetadataImplementor metadata) { public static QueryEngine from(SessionFactoryImplementor sessionFactory, MetadataImplementor metadata) {
final QueryEngineOptions queryEngineOptions = sessionFactory.getSessionFactoryOptions(); final QueryEngineOptions queryEngineOptions = sessionFactory.getSessionFactoryOptions();
final SqmCreationOptions sqmCreationOptions = new SqmCreationOptionsStandard( sessionFactory );
final Dialect dialect = sessionFactory.getJdbcServices().getDialect(); final Dialect dialect = sessionFactory.getJdbcServices().getDialect();
final HqlTranslator hqlTranslator = resolveHqlTranslator( return new QueryEngine(
sessionFactory,
resolveHqlTranslator(
queryEngineOptions, queryEngineOptions,
dialect, dialect,
sessionFactory, sessionFactory,
sqmCreationOptions new SqmCreationOptionsStandard( queryEngineOptions )
),
resolveSqmTranslatorFactory( queryEngineOptions, dialect ),
metadata,
dialect,
buildCustomFunctionRegistry( queryEngineOptions )
); );
}
final SqmTranslatorFactory sqmTranslatorFactory = resolveSqmTranslatorFactory( queryEngineOptions, dialect ); private static SqmFunctionRegistry buildCustomFunctionRegistry(QueryEngineOptions queryEngineOptions) {
final SqmFunctionRegistry customSqmFunctionRegistry;
if ( queryEngineOptions.getCustomSqmFunctionRegistry() == null ) { if ( queryEngineOptions.getCustomSqmFunctionRegistry() == null ) {
final Map<String, SqmFunctionDescriptor> customSqlFunctionMap = queryEngineOptions.getCustomSqlFunctionMap(); final Map<String, SqmFunctionDescriptor> customSqlFunctionMap = queryEngineOptions.getCustomSqlFunctionMap();
if ( customSqlFunctionMap == null || customSqlFunctionMap.isEmpty() ) { if ( customSqlFunctionMap == null || customSqlFunctionMap.isEmpty() ) {
customSqmFunctionRegistry = null; return null;
} }
else { else {
customSqmFunctionRegistry = new SqmFunctionRegistry(); SqmFunctionRegistry customSqmFunctionRegistry = new SqmFunctionRegistry();
customSqlFunctionMap.forEach( customSqmFunctionRegistry::register ); customSqlFunctionMap.forEach( customSqmFunctionRegistry::register );
return customSqmFunctionRegistry;
} }
} }
else { else {
customSqmFunctionRegistry = queryEngineOptions.getCustomSqmFunctionRegistry(); return queryEngineOptions.getCustomSqmFunctionRegistry();
}
} }
return new QueryEngine( private final NamedObjectRepository namedObjectRepository;
private final SqmCriteriaNodeBuilder criteriaBuilder;
private final HqlTranslator hqlTranslator;
private final SqmTranslatorFactory sqmTranslatorFactory;
private final NativeQueryInterpreter nativeQueryInterpreter;
private final QueryInterpretationCache interpretationCache;
private final SqmFunctionRegistry sqmFunctionRegistry;
private final TypeConfiguration typeConfiguration;
private final int preferredSqlTypeCodeForBoolean;
private final QueryParameterBindingTypeResolver queryParameterBindingTypeResolver;
private QueryEngine(
SessionFactoryImplementor sessionFactory,
HqlTranslator hqlTranslator,
SqmTranslatorFactory sqmTranslatorFactory,
MetadataImplementor metadata,
Dialect dialect,
SqmFunctionRegistry customFunctionRegistry) {
this(
sessionFactory.getUuid(), sessionFactory.getUuid(),
sessionFactory.getName(), sessionFactory.getName(),
sessionFactory.getSessionFactoryOptions().getJpaCompliance(), sessionFactory.getSessionFactoryOptions().getJpaCompliance(),
@ -107,22 +134,13 @@ public class QueryEngine {
buildInterpretationCache( sessionFactory::getStatistics, sessionFactory.getProperties() ), buildInterpretationCache( sessionFactory::getStatistics, sessionFactory.getProperties() ),
metadata.getTypeConfiguration(), metadata.getTypeConfiguration(),
dialect, dialect,
customSqmFunctionRegistry, customFunctionRegistry,
sessionFactory.getServiceRegistry() sessionFactory.getServiceRegistry(),
sessionFactory
); );
} }
private final NamedObjectRepository namedObjectRepository; private QueryEngine(
private final SqmCriteriaNodeBuilder criteriaBuilder;
private final HqlTranslator hqlTranslator;
private final SqmTranslatorFactory sqmTranslatorFactory;
private final NativeQueryInterpreter nativeQueryInterpreter;
private final QueryInterpretationCache interpretationCache;
private final SqmFunctionRegistry sqmFunctionRegistry;
private final TypeConfiguration typeConfiguration;
private final int preferredSqlTypeCodeForBoolean;
public QueryEngine(
String uuid, String uuid,
String name, String name,
JpaCompliance jpaCompliance, JpaCompliance jpaCompliance,
@ -137,7 +155,9 @@ public class QueryEngine {
TypeConfiguration typeConfiguration, TypeConfiguration typeConfiguration,
Dialect dialect, Dialect dialect,
SqmFunctionRegistry userDefinedRegistry, SqmFunctionRegistry userDefinedRegistry,
ServiceRegistry serviceRegistry) { ServiceRegistry serviceRegistry,
SessionFactoryImplementor sessionFactory) {
this.queryParameterBindingTypeResolver = sessionFactory;
this.namedObjectRepository = Objects.requireNonNull( namedObjectRepository ); this.namedObjectRepository = Objects.requireNonNull( namedObjectRepository );
this.sqmTranslatorFactory = sqmTranslatorFactory; this.sqmTranslatorFactory = sqmTranslatorFactory;
this.nativeQueryInterpreter = Objects.requireNonNull( nativeQueryInterpreter ); this.nativeQueryInterpreter = Objects.requireNonNull( nativeQueryInterpreter );
@ -151,7 +171,8 @@ public class QueryEngine {
this, this,
jpaMetamodelAccess, jpaMetamodelAccess,
serviceRegistry, serviceRegistry,
criteriaValueHandlingMode criteriaValueHandlingMode,
sessionFactory
); );
this.sqmFunctionRegistry = new SqmFunctionRegistry(); this.sqmFunctionRegistry = new SqmFunctionRegistry();
@ -212,6 +233,8 @@ public class QueryEngine {
this.preferredSqlTypeCodeForBoolean = preferredSqlTypeCodeForBoolean; this.preferredSqlTypeCodeForBoolean = preferredSqlTypeCodeForBoolean;
dialect.initializeFunctionRegistry( this ); dialect.initializeFunctionRegistry( this );
SessionFactoryImplementor sessionFactory = jpaMetamodel.getTypeConfiguration().getSessionFactory();
this.queryParameterBindingTypeResolver = sessionFactory;
this.criteriaBuilder = new SqmCriteriaNodeBuilder( this.criteriaBuilder = new SqmCriteriaNodeBuilder(
uuid, uuid,
name, name,
@ -219,7 +242,8 @@ public class QueryEngine {
this, this,
() -> jpaMetamodel, () -> jpaMetamodel,
serviceRegistry, serviceRegistry,
criteriaValueHandlingMode criteriaValueHandlingMode,
sessionFactory
); );
final SqmCreationContext sqmCreationContext = new SqmCreationContext() { final SqmCreationContext sqmCreationContext = new SqmCreationContext() {
@ -261,51 +285,6 @@ public class QueryEngine {
); );
} }
// public QueryEngine(
// JpaMetamodel domainModel,
// ServiceRegistry serviceRegistry,
// SessionFactoryOptions runtimeOptions,
// SqmCreationContext sqmCreationContext,
// SqmCreationOptions sqmCreationOptions,
// Map properties,
// NamedQueryRepository namedQueryRepository) {
// final JdbcServices jdbcServices = serviceRegistry.getService( JdbcServices.class );
// final JdbcEnvironment jdbcEnvironment = jdbcServices.getJdbcEnvironment();
// final Dialect dialect = jdbcEnvironment.getDialect();
//
// this.namedQueryRepository = namedQueryRepository;
//
// this.hqlTranslator = resolveHqlTranslator(
// runtimeOptions,
// dialect,
// sqmCreationContext,
// sqmCreationOptions
// );
//
// this.sqmTranslatorFactory = resolveSqmTranslatorFactory(
// runtimeOptions,
// dialect,
// sqmCreationContext,
// sqmCreationOptions
// );
//
// this.criteriaBuilder = new SqmCriteriaNodeBuilder(
// this,
// domainModel,
// serviceRegistry
// );
//
// this.nativeQueryInterpreter = serviceRegistry.getService( NativeQueryInterpreter.class );
//
// this.interpretationCache = buildInterpretationCache( properties );
//
// this.sqmFunctionRegistry = new SqmFunctionRegistry();
// dialect.initializeFunctionRegistry( this );
// if ( runtimeOptions.getSqmFunctionRegistry() != null ) {
// runtimeOptions.getSqmFunctionRegistry().overlay( sqmFunctionRegistry );
// }
// }
private static HqlTranslator resolveHqlTranslator( private static HqlTranslator resolveHqlTranslator(
QueryEngineOptions runtimeOptions, QueryEngineOptions runtimeOptions,
Dialect dialect, Dialect dialect,
@ -314,13 +293,13 @@ public class QueryEngine {
if ( runtimeOptions.getCustomHqlTranslator() != null ) { if ( runtimeOptions.getCustomHqlTranslator() != null ) {
return runtimeOptions.getCustomHqlTranslator(); return runtimeOptions.getCustomHqlTranslator();
} }
else if ( dialect.getHqlTranslator() != null ) {
if ( dialect.getHqlTranslator() != null ) {
return dialect.getHqlTranslator(); return dialect.getHqlTranslator();
} }
else {
return new StandardHqlTranslator( sqmCreationContext, sqmCreationOptions ); return new StandardHqlTranslator( sqmCreationContext, sqmCreationOptions );
} }
}
private static SqmTranslatorFactory resolveSqmTranslatorFactory( private static SqmTranslatorFactory resolveSqmTranslatorFactory(
QueryEngineOptions runtimeOptions, QueryEngineOptions runtimeOptions,
@ -328,26 +307,26 @@ public class QueryEngine {
if ( runtimeOptions.getCustomSqmTranslatorFactory() != null ) { if ( runtimeOptions.getCustomSqmTranslatorFactory() != null ) {
return runtimeOptions.getCustomSqmTranslatorFactory(); return runtimeOptions.getCustomSqmTranslatorFactory();
} }
else if ( dialect.getSqmTranslatorFactory() != null ) {
if ( dialect.getSqmTranslatorFactory() != null ) {
return dialect.getSqmTranslatorFactory(); return dialect.getSqmTranslatorFactory();
} }
else {
return new StandardSqmTranslatorFactory(); return new StandardSqmTranslatorFactory();
} }
}
private static List<FunctionContributor> sortedFunctionContributors(ServiceRegistry serviceRegistry) { private static List<FunctionContributor> sortedFunctionContributors(ServiceRegistry serviceRegistry) {
List<FunctionContributor> contributors = new ArrayList<>( List<FunctionContributor> contributors = new ArrayList<>(
serviceRegistry.getService( ClassLoaderService.class ) serviceRegistry.getService( ClassLoaderService.class )
.loadJavaServices( FunctionContributor.class ) ); .loadJavaServices( FunctionContributor.class ) );
contributors.sort( Comparator.comparingInt( FunctionContributor::ordinal ) contributors.sort( comparingInt( FunctionContributor::ordinal )
.thenComparing( a -> a.getClass().getCanonicalName() ) ); .thenComparing( a -> a.getClass().getCanonicalName() ) );
return contributors; return contributors;
} }
private static QueryInterpretationCache buildInterpretationCache( private static QueryInterpretationCache buildInterpretationCache(
Supplier<StatisticsImplementor> statisticsSupplier, Supplier<StatisticsImplementor> statisticsSupplier,
Map properties) { Map<String,Object> properties) {
final boolean explicitUseCache = ConfigurationHelper.getBoolean( final boolean explicitUseCache = ConfigurationHelper.getBoolean(
AvailableSettings.QUERY_PLAN_CACHE_ENABLED, AvailableSettings.QUERY_PLAN_CACHE_ENABLED,
properties, properties,
@ -437,4 +416,14 @@ public class QueryEngine {
public int getPreferredSqlTypeCodeForBoolean() { public int getPreferredSqlTypeCodeForBoolean() {
return preferredSqlTypeCodeForBoolean; return preferredSqlTypeCodeForBoolean;
} }
@Override
public <T> BindableType<? extends T> resolveParameterBindType(T bindValue) {
return queryParameterBindingTypeResolver.resolveParameterBindType( bindValue );
}
@Override
public <T> BindableType<T> resolveParameterBindType(Class<T> clazz) {
return queryParameterBindingTypeResolver.resolveParameterBindType( clazz );
}
} }

View File

@ -8,6 +8,7 @@ package org.hibernate.query.spi;
import java.util.Map; import java.util.Map;
import org.hibernate.jpa.spi.JpaCompliance;
import org.hibernate.query.hql.HqlTranslator; import org.hibernate.query.hql.HqlTranslator;
import org.hibernate.query.sqm.function.SqmFunctionDescriptor; import org.hibernate.query.sqm.function.SqmFunctionDescriptor;
import org.hibernate.query.sqm.function.SqmFunctionRegistry; import org.hibernate.query.sqm.function.SqmFunctionRegistry;
@ -66,4 +67,6 @@ public interface QueryEngineOptions {
* target of the mutation is a multi-table entity. * target of the mutation is a multi-table entity.
*/ */
SqmMultiTableInsertStrategy getCustomSqmMultiTableInsertStrategy(); SqmMultiTableInsertStrategy getCustomSqmMultiTableInsertStrategy();
JpaCompliance getJpaCompliance();
} }

View File

@ -17,6 +17,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.metamodel.model.domain.JpaMetamodel; import org.hibernate.metamodel.model.domain.JpaMetamodel;
import org.hibernate.query.criteria.HibernateCriteriaBuilder; import org.hibernate.query.criteria.HibernateCriteriaBuilder;
import org.hibernate.query.criteria.JpaCoalesce; import org.hibernate.query.criteria.JpaCoalesce;
@ -646,4 +647,6 @@ public interface NodeBuilder extends HibernateCriteriaBuilder {
BasicType<Integer> getIntegerType(); BasicType<Integer> getIntegerType();
BasicType<Character> getCharacterType(); BasicType<Character> getCharacterType();
SessionFactoryImplementor getSessionFactory();
} }

View File

@ -6,21 +6,21 @@
*/ */
package org.hibernate.query.sqm.internal; package org.hibernate.query.sqm.internal;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.query.hql.spi.SqmCreationOptions; import org.hibernate.query.hql.spi.SqmCreationOptions;
import org.hibernate.query.spi.QueryEngineOptions;
/** /**
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public class SqmCreationOptionsStandard implements SqmCreationOptions { public class SqmCreationOptionsStandard implements SqmCreationOptions {
private final SessionFactoryImplementor sessionFactory; private final QueryEngineOptions queryEngineOptions;
public SqmCreationOptionsStandard(SessionFactoryImplementor sessionFactory) { public SqmCreationOptionsStandard(QueryEngineOptions queryEngineOptions) {
this.sessionFactory = sessionFactory; this.queryEngineOptions = queryEngineOptions;
} }
@Override @Override
public boolean useStrictJpaCompliance() { public boolean useStrictJpaCompliance() {
return sessionFactory.getSessionFactoryOptions().getJpaCompliance().isJpaQueryComplianceEnabled(); return queryEngineOptions.getJpaCompliance().isJpaQueryComplianceEnabled();
} }
} }

View File

@ -176,21 +176,6 @@ public class SqmCriteriaNodeBuilder implements NodeBuilder, SqmCreationContext,
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( SqmCriteriaNodeBuilder.class ); private static final CoreMessageLogger LOG = CoreLogging.messageLogger( SqmCriteriaNodeBuilder.class );
/**
* Simplified creation from a SessionFactory
*/
public static SqmCriteriaNodeBuilder create(SessionFactoryImplementor sf) {
return new SqmCriteriaNodeBuilder(
sf.getUuid(),
sf.getName(),
sf.getSessionFactoryOptions().getJpaCompliance().isJpaQueryComplianceEnabled(),
sf.getQueryEngine(),
() -> sf.getRuntimeMetamodels().getJpaMetamodel(),
sf.getServiceRegistry(),
sf.getSessionFactoryOptions().getCriteriaValueHandlingMode()
);
}
private final String uuid; private final String uuid;
private final String name; private final String name;
private final transient boolean jpaComplianceEnabled; private final transient boolean jpaComplianceEnabled;
@ -198,6 +183,7 @@ public class SqmCriteriaNodeBuilder implements NodeBuilder, SqmCreationContext,
private final transient Supplier<JpaMetamodelImplementor> domainModelAccess; private final transient Supplier<JpaMetamodelImplementor> domainModelAccess;
private final transient ServiceRegistry serviceRegistry; private final transient ServiceRegistry serviceRegistry;
private final transient ValueHandlingMode criteriaValueHandlingMode; private final transient ValueHandlingMode criteriaValueHandlingMode;
private final transient SessionFactoryImplementor sessionFactory;
private transient BasicType<Boolean> booleanType; private transient BasicType<Boolean> booleanType;
private transient BasicType<Integer> integerType; private transient BasicType<Integer> integerType;
private transient BasicType<Character> characterType; private transient BasicType<Character> characterType;
@ -210,7 +196,9 @@ public class SqmCriteriaNodeBuilder implements NodeBuilder, SqmCreationContext,
QueryEngine queryEngine, QueryEngine queryEngine,
Supplier<JpaMetamodelImplementor> domainModelAccess, Supplier<JpaMetamodelImplementor> domainModelAccess,
ServiceRegistry serviceRegistry, ServiceRegistry serviceRegistry,
ValueHandlingMode criteriaValueHandlingMode) { ValueHandlingMode criteriaValueHandlingMode,
SessionFactoryImplementor sessionFactory) {
this.sessionFactory = sessionFactory;
this.uuid = uuid; this.uuid = uuid;
this.name = name; this.name = name;
this.jpaComplianceEnabled = jpaComplianceEnabled; this.jpaComplianceEnabled = jpaComplianceEnabled;
@ -236,6 +224,11 @@ public class SqmCriteriaNodeBuilder implements NodeBuilder, SqmCreationContext,
return jpaComplianceEnabled; return jpaComplianceEnabled;
} }
@Override
public SessionFactoryImplementor getSessionFactory() {
return sessionFactory;
}
@Override @Override
public BasicType<Boolean> getBooleanType() { public BasicType<Boolean> getBooleanType() {
final BasicType<Boolean> booleanType = this.booleanType; final BasicType<Boolean> booleanType = this.booleanType;
@ -466,7 +459,7 @@ public class SqmCriteriaNodeBuilder implements NodeBuilder, SqmCreationContext,
throw new SemanticException( "Path should refer to a to-one attribute : " + path ); throw new SemanticException( "Path should refer to a to-one attribute : " + path );
} }
return new SqmFkExpression<>( (SqmEntityValuedSimplePath) path, this ); return new SqmFkExpression<>( (SqmEntityValuedSimplePath<?>) path, this );
} }
@Override @Override
@ -623,7 +616,7 @@ public class SqmCriteriaNodeBuilder implements NodeBuilder, SqmCreationContext,
expressibleType = (DomainType<R>) typeConfiguration.resolveTupleType( sqmExpressions ); expressibleType = (DomainType<R>) typeConfiguration.resolveTupleType( sqmExpressions );
} }
else { else {
expressibleType = typeConfiguration.getSessionFactory().getJpaMetamodel().embeddable( tupleType ); expressibleType = domainModelAccess.get().embeddable( tupleType );
} }
return tuple( expressibleType, sqmExpressions ); return tuple( expressibleType, sqmExpressions );
} }
@ -1194,12 +1187,10 @@ public class SqmCriteriaNodeBuilder implements NodeBuilder, SqmCreationContext,
return new SqmLiteralNull<>( this ); return new SqmLiteralNull<>( this );
} }
final BindableType<? extends T> valueParamType = queryEngine.getTypeConfiguration() final BindableType<? extends T> valueParamType = queryEngine.resolveParameterBindType( value );
.getSessionFactory()
.resolveParameterBindType( value );
final SqmExpressible<? extends T> sqmExpressible = valueParamType == null final SqmExpressible<? extends T> sqmExpressible = valueParamType == null
? null ? null
: valueParamType.resolveExpressible( getTypeConfiguration().getSessionFactory() ); : valueParamType.resolveExpressible( sessionFactory );
return new SqmLiteral<>( value, sqmExpressible, this ); return new SqmLiteral<>( value, sqmExpressible, this );
} }
@ -1235,7 +1226,7 @@ public class SqmCriteriaNodeBuilder implements NodeBuilder, SqmCreationContext,
final TypeConfiguration typeConfiguration = getTypeConfiguration(); final TypeConfiguration typeConfiguration = getTypeConfiguration();
final BasicType<T> basicTypeForJavaType = typeConfiguration.getBasicTypeForJavaType( resultClass ); final BasicType<T> basicTypeForJavaType = typeConfiguration.getBasicTypeForJavaType( resultClass );
final SqmExpressible<T> sqmExpressible = basicTypeForJavaType == null final SqmExpressible<T> sqmExpressible = basicTypeForJavaType == null
? typeConfiguration.getSessionFactory().getJpaMetamodel().managedType( resultClass ) ? domainModelAccess.get().managedType( resultClass )
: basicTypeForJavaType; : basicTypeForJavaType;
return new SqmLiteralNull<>(sqmExpressible, this ); return new SqmLiteralNull<>(sqmExpressible, this );
} }
@ -1263,7 +1254,7 @@ public class SqmCriteriaNodeBuilder implements NodeBuilder, SqmCreationContext,
@Override @Override
public <T> JpaCriteriaParameter<T> parameter(Class<T> paramClass) { public <T> JpaCriteriaParameter<T> parameter(Class<T> paramClass) {
return parameter( paramClass, (String) null ); return parameter( paramClass, null );
} }
@Override @Override
@ -1727,7 +1718,7 @@ public class SqmCriteriaNodeBuilder implements NodeBuilder, SqmCreationContext,
this this
); );
} }
final SqmExpressible<T> expressible = bindableType.resolveExpressible( getTypeConfiguration().getSessionFactory() ); final SqmExpressible<T> expressible = bindableType.resolveExpressible( sessionFactory );
T coercedValue = expressible.getExpressibleJavaType().coerce( value, this::getTypeConfiguration ); T coercedValue = expressible.getExpressibleJavaType().coerce( value, this::getTypeConfiguration );
if ( isInstance( bindableType, coercedValue ) ) { if ( isInstance( bindableType, coercedValue ) ) {
return new ValueBindJpaCriteriaParameter<>( return new ValueBindJpaCriteriaParameter<>(
@ -1739,7 +1730,7 @@ public class SqmCriteriaNodeBuilder implements NodeBuilder, SqmCreationContext,
else { else {
// ignore typeInferenceSource and fallback the value type // ignore typeInferenceSource and fallback the value type
return new ValueBindJpaCriteriaParameter<>( return new ValueBindJpaCriteriaParameter<>(
queryEngine.getTypeConfiguration().getSessionFactory().resolveParameterBindType( value ), queryEngine.resolveParameterBindType( value ),
value, value,
this this
); );
@ -1753,7 +1744,7 @@ public class SqmCriteriaNodeBuilder implements NodeBuilder, SqmCreationContext,
if ( bindableType.getBindableJavaType().isInstance( value ) ) { if ( bindableType.getBindableJavaType().isInstance( value ) ) {
return true; return true;
} }
return bindableType.resolveExpressible( getTypeConfiguration().getSessionFactory() ) return bindableType.resolveExpressible( sessionFactory )
.getExpressibleJavaType() .getExpressibleJavaType()
.isInstance( value ); .isInstance( value );
} }
@ -1792,7 +1783,7 @@ public class SqmCriteriaNodeBuilder implements NodeBuilder, SqmCreationContext,
} }
else { else {
return new ValueBindJpaCriteriaParameter<>( return new ValueBindJpaCriteriaParameter<>(
queryEngine.getTypeConfiguration().getSessionFactory().resolveParameterBindType( value ), queryEngine.resolveParameterBindType( value ),
value, value,
this this
); );

View File

@ -7,12 +7,12 @@
package org.hibernate.query.sqm.produce.function; package org.hibernate.query.sqm.produce.function;
import org.hibernate.QueryException; import org.hibernate.QueryException;
import org.hibernate.metamodel.MappingMetamodel;
import org.hibernate.metamodel.mapping.JdbcMapping; import org.hibernate.metamodel.mapping.JdbcMapping;
import org.hibernate.metamodel.mapping.JdbcMappingContainer; import org.hibernate.metamodel.mapping.JdbcMappingContainer;
import org.hibernate.metamodel.mapping.ModelPart; import org.hibernate.metamodel.mapping.ModelPart;
import org.hibernate.metamodel.mapping.ModelPartContainer; import org.hibernate.metamodel.mapping.ModelPartContainer;
import org.hibernate.metamodel.model.domain.EntityDomainType; import org.hibernate.metamodel.model.domain.EntityDomainType;
import org.hibernate.query.spi.QueryEngine;
import org.hibernate.query.sqm.SqmExpressible; import org.hibernate.query.sqm.SqmExpressible;
import org.hibernate.query.sqm.tree.SqmTypedNode; import org.hibernate.query.sqm.tree.SqmTypedNode;
import org.hibernate.query.sqm.tree.domain.SqmPath; import org.hibernate.query.sqm.tree.domain.SqmPath;
@ -75,18 +75,21 @@ public class ArgumentTypesValidator implements ArgumentsValidator {
* that is run at startup for named queries, and can be done in an IDE. * that is run at startup for named queries, and can be done in an IDE.
*/ */
@Override @Override
public void validate(List<? extends SqmTypedNode<?>> arguments, String functionName, QueryEngine queryEngine) { public void validate(
delegate.validate(arguments, functionName, queryEngine); List<? extends SqmTypedNode<?>> arguments,
String functionName,
MappingMetamodel metamodel) {
delegate.validate( arguments, functionName, metamodel );
int count = 0; int count = 0;
for (SqmTypedNode<?> argument : arguments) { for (SqmTypedNode<?> argument : arguments) {
JdbcTypeIndicators indicators = queryEngine.getTypeConfiguration().getCurrentBaseSqlTypeIndicators(); JdbcTypeIndicators indicators = metamodel.getTypeConfiguration().getCurrentBaseSqlTypeIndicators();
SqmExpressible<?> nodeType = argument.getNodeType(); SqmExpressible<?> nodeType = argument.getNodeType();
FunctionParameterType type = count < types.length ? types[count++] : types[types.length - 1]; FunctionParameterType type = count < types.length ? types[count++] : types[types.length - 1];
if ( nodeType!=null ) { if ( nodeType!=null ) {
JavaType<?> javaType = nodeType.getExpressibleJavaType(); JavaType<?> javaType = nodeType.getExpressibleJavaType();
if (javaType != null) { if (javaType != null) {
try { try {
final JdbcType jdbcType = getJdbcType( queryEngine, argument, indicators, javaType ); final JdbcType jdbcType = getJdbcType( metamodel, argument, indicators, javaType );
checkType( checkType(
count, functionName, type, count, functionName, type,
jdbcType.getDefaultSqlTypeCode(), jdbcType.getDefaultSqlTypeCode(),
@ -126,14 +129,14 @@ public class ArgumentTypesValidator implements ArgumentsValidator {
} }
private JdbcType getJdbcType( private JdbcType getJdbcType(
QueryEngine queryEngine, MappingMetamodel metamodel,
SqmTypedNode<?> argument, SqmTypedNode<?> argument,
JdbcTypeIndicators indicators, JdbcTypeIndicators indicators,
JavaType<?> javaType) { JavaType<?> javaType) {
// For enum types, we must try to resolve the JdbcMapping of a possible path // For enum types, we must try to resolve the JdbcMapping of a possible path
// to be sure we use the correct JdbcType for the validation // to be sure we use the correct JdbcType for the validation
final JdbcMapping mapping = javaType.getJavaTypeClass().isEnum() final JdbcMapping mapping = javaType.getJavaTypeClass().isEnum()
? getJdbcMapping( argument, queryEngine ) ? getJdbcMapping( argument, metamodel )
: null; : null;
if ( mapping == null ) { if ( mapping == null ) {
return javaType.getRecommendedJdbcType( indicators ); return javaType.getRecommendedJdbcType( indicators );
@ -143,25 +146,25 @@ public class ArgumentTypesValidator implements ArgumentsValidator {
} }
} }
private JdbcMapping getJdbcMapping(SqmTypedNode<?> argument, QueryEngine queryEngine) { private JdbcMapping getJdbcMapping(SqmTypedNode<?> argument, MappingMetamodel metamodel) {
if ( argument instanceof SqmPath<?> ) { if ( argument instanceof SqmPath<?> ) {
final SqmPath<?> path = (SqmPath<?>) argument; final SqmPath<?> path = (SqmPath<?>) argument;
final ModelPartContainer modelPartContainer = getModelPartContainer( path.getLhs(), queryEngine ); final ModelPartContainer modelPartContainer = getModelPartContainer( path.getLhs(), metamodel );
final ModelPart part = modelPartContainer.findSubPart( path.getReferencedPathSource().getPathName(), null ); final ModelPart part = modelPartContainer.findSubPart( path.getReferencedPathSource().getPathName(), null );
return part.getJdbcMappings().get( 0 ); return part.getJdbcMappings().get( 0 );
} }
return null; return null;
} }
private ModelPartContainer getModelPartContainer(SqmPath<?> path, QueryEngine queryEngine) { private ModelPartContainer getModelPartContainer(SqmPath<?> path, MappingMetamodel metamodel) {
final SqmPath<?> lhs = path.getLhs(); final SqmPath<?> lhs = path.getLhs();
if ( lhs == null ) { if ( lhs == null ) {
assert path instanceof SqmFrom<?, ?>; assert path instanceof SqmFrom<?, ?>;
final EntityDomainType<?> entityDomainType = (EntityDomainType<?>) path.getNodeType().getSqmPathType(); final EntityDomainType<?> entityDomainType = (EntityDomainType<?>) path.getNodeType().getSqmPathType();
return queryEngine.getTypeConfiguration().getSessionFactory().getRuntimeMetamodels().getEntityMappingType( entityDomainType.getHibernateEntityName() ); return metamodel.getEntityDescriptor( entityDomainType.getHibernateEntityName() );
} }
else { else {
final ModelPartContainer modelPartContainer = getModelPartContainer( lhs, queryEngine ); final ModelPartContainer modelPartContainer = getModelPartContainer( lhs, metamodel );
return (ModelPartContainer) modelPartContainer.findSubPart( path.getReferencedPathSource().getPathName(), null ); return (ModelPartContainer) modelPartContainer.findSubPart( path.getReferencedPathSource().getPathName(), null );
} }
} }

View File

@ -6,6 +6,7 @@
*/ */
package org.hibernate.query.sqm.produce.function; package org.hibernate.query.sqm.produce.function;
import org.hibernate.metamodel.MappingMetamodel;
import org.hibernate.query.spi.QueryEngine; import org.hibernate.query.spi.QueryEngine;
import org.hibernate.query.sqm.tree.SqmTypedNode; import org.hibernate.query.sqm.tree.SqmTypedNode;
import org.hibernate.sql.ast.tree.SqlAstNode; import org.hibernate.sql.ast.tree.SqlAstNode;
@ -22,10 +23,19 @@ import java.util.List;
*/ */
public interface ArgumentsValidator { public interface ArgumentsValidator {
/** /**
* Perform validation that may be done using the {@link SqmTypedNode} * Perform validation that may be done using the {@link SqmTypedNode} tree and assigned Java types.
* tree and assigned Java types. *
* @deprecated Use {@link #validate(List, String, MappingMetamodel)}
*/ */
void validate(List<? extends SqmTypedNode<?>> arguments, String functionName, QueryEngine queryEngine); @Deprecated(since = "6.2")
default void validate(List<? extends SqmTypedNode<?>> arguments, String functionName, QueryEngine queryEngine) {
validate( arguments, functionName, queryEngine.getTypeConfiguration().getSessionFactory().getMappingMetamodel() );
}
/**
* Perform validation that may be done using the {@link SqmTypedNode} tree and assigned Java types.
*/
default void validate(List<? extends SqmTypedNode<?>> arguments, String functionName, MappingMetamodel metamodel) {}
/** /**
* Pretty-print the signature of the argument list. * Pretty-print the signature of the argument list.
@ -35,8 +45,7 @@ public interface ArgumentsValidator {
} }
/** /**
* Perform validation that requires the {@link SqlAstNode} tree and * Perform validation that requires the {@link SqlAstNode} tree and assigned JDBC types.
* assigned JDBC types.
*/ */
default void validateSqlTypes(List<? extends SqlAstNode> arguments, String functionName) {} default void validateSqlTypes(List<? extends SqlAstNode> arguments, String functionName) {}

View File

@ -7,13 +7,14 @@
package org.hibernate.query.sqm.produce.function; package org.hibernate.query.sqm.produce.function;
import org.hibernate.QueryException; import org.hibernate.QueryException;
import org.hibernate.query.spi.QueryEngine; import org.hibernate.metamodel.MappingMetamodel;
import org.hibernate.query.sqm.tree.SqmTypedNode; import org.hibernate.query.sqm.tree.SqmTypedNode;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import static java.util.Arrays.asList;
/** /**
* @author Steve Ebersole * @author Steve Ebersole
*/ */
@ -28,9 +29,6 @@ public final class StandardArgumentsValidators {
* Static validator for performing no validation * Static validator for performing no validation
*/ */
public static final ArgumentsValidator NONE = new ArgumentsValidator() { public static final ArgumentsValidator NONE = new ArgumentsValidator() {
@Override
public void validate(List<? extends SqmTypedNode<?>> arguments, String functionName, QueryEngine queryEngine) {}
@Override @Override
public String getSignature() { public String getSignature() {
return "([arg0[, ...]])"; return "([arg0[, ...]])";
@ -42,7 +40,10 @@ public final class StandardArgumentsValidators {
*/ */
public static final ArgumentsValidator NO_ARGS = new ArgumentsValidator() { public static final ArgumentsValidator NO_ARGS = new ArgumentsValidator() {
@Override @Override
public void validate(List<? extends SqmTypedNode<?>> arguments, String functionName, QueryEngine queryEngine) { public void validate(
List<? extends SqmTypedNode<?>> arguments,
String functionName,
MappingMetamodel metamodel) {
if ( !arguments.isEmpty() ) { if ( !arguments.isEmpty() ) {
throw new QueryException( throw new QueryException(
String.format( String.format(
@ -67,7 +68,10 @@ public final class StandardArgumentsValidators {
} }
return new ArgumentsValidator() { return new ArgumentsValidator() {
@Override @Override
public void validate(List<? extends SqmTypedNode<?>> arguments, String functionName, QueryEngine queryEngine) { public void validate(
List<? extends SqmTypedNode<?>> arguments,
String functionName,
MappingMetamodel metamodel) {
if ( arguments.size() < minNumOfArgs ) { if ( arguments.size() < minNumOfArgs ) {
throw new QueryException( throw new QueryException(
String.format( String.format(
@ -101,7 +105,10 @@ public final class StandardArgumentsValidators {
public static ArgumentsValidator exactly(int number) { public static ArgumentsValidator exactly(int number) {
return new ArgumentsValidator() { return new ArgumentsValidator() {
@Override @Override
public void validate(List<? extends SqmTypedNode<?>> arguments, String functionName, QueryEngine queryEngine) { public void validate(
List<? extends SqmTypedNode<?>> arguments,
String functionName,
MappingMetamodel metamodel) {
if ( arguments.size() != number ) { if ( arguments.size() != number ) {
throw new QueryException( throw new QueryException(
String.format( String.format(
@ -137,7 +144,10 @@ public final class StandardArgumentsValidators {
public static ArgumentsValidator max(int maxNumOfArgs) { public static ArgumentsValidator max(int maxNumOfArgs) {
return new ArgumentsValidator() { return new ArgumentsValidator() {
@Override @Override
public void validate(List<? extends SqmTypedNode<?>> arguments, String functionName, QueryEngine queryEngine) { public void validate(
List<? extends SqmTypedNode<?>> arguments,
String functionName,
MappingMetamodel metamodel) {
if ( arguments.size() > maxNumOfArgs ) { if ( arguments.size() > maxNumOfArgs ) {
throw new QueryException( throw new QueryException(
String.format( String.format(
@ -169,7 +179,10 @@ public final class StandardArgumentsValidators {
public static ArgumentsValidator between(int minNumOfArgs, int maxNumOfArgs) { public static ArgumentsValidator between(int minNumOfArgs, int maxNumOfArgs) {
return new ArgumentsValidator() { return new ArgumentsValidator() {
@Override @Override
public void validate(List<? extends SqmTypedNode<?>> arguments, String functionName, QueryEngine queryEngine) { public void validate(
List<? extends SqmTypedNode<?>> arguments,
String functionName,
MappingMetamodel metamodel) {
if (arguments.size() < minNumOfArgs || arguments.size() > maxNumOfArgs) { if (arguments.size() < minNumOfArgs || arguments.size() > maxNumOfArgs) {
throw new QueryException( throw new QueryException(
String.format( String.format(
@ -203,9 +216,14 @@ public final class StandardArgumentsValidators {
} }
public static ArgumentsValidator of(Class<?> javaType) { public static ArgumentsValidator of(Class<?> javaType) {
return (arguments, functionName, queryEngine) -> arguments.forEach( return new ArgumentsValidator() {
arg -> { @Override
Class<?> argType = arg.getNodeJavaType().getJavaTypeClass(); public void validate(
List<? extends SqmTypedNode<?>> arguments,
String functionName,
MappingMetamodel metamodel) {
for ( SqmTypedNode<?> argument : arguments ) {
Class<?> argType = argument.getNodeJavaType().getJavaTypeClass();
if ( !javaType.isAssignableFrom( argType ) ) { if ( !javaType.isAssignableFrom( argType ) ) {
throw new QueryException( throw new QueryException(
String.format( String.format(
@ -218,16 +236,27 @@ public final class StandardArgumentsValidators {
); );
} }
} }
); }
};
} }
public static ArgumentsValidator composite(ArgumentsValidator... validators) { public static ArgumentsValidator composite(ArgumentsValidator... validators) {
return composite( Arrays.asList( validators ) ); return composite( asList( validators ) );
} }
public static ArgumentsValidator composite(List<ArgumentsValidator> validators) { public static ArgumentsValidator composite(List<ArgumentsValidator> validators) {
return (arguments, functionName, queryEngine) -> validators.forEach( return new ArgumentsValidator() {
individualValidator -> individualValidator.validate( arguments, functionName, queryEngine) @Override
); public void validate(
List<? extends SqmTypedNode<?>> arguments,
String functionName,
MappingMetamodel metamodel) {
validators.forEach( individualValidator -> individualValidator.validate(
arguments,
functionName,
metamodel
) );
}
};
} }
} }

View File

@ -205,10 +205,8 @@ public abstract class AbstractSqmFrom<O,T> extends AbstractSqmPath<T> implements
final SqmAttributeJoin<?, ?> lhsAttributeJoin = (SqmAttributeJoin<?, ?>) lhs; final SqmAttributeJoin<?, ?> lhsAttributeJoin = (SqmAttributeJoin<?, ?>) lhs;
if ( lhsAttributeJoin.getReferencedPathSource() instanceof EntityDomainType<?> ) { if ( lhsAttributeJoin.getReferencedPathSource() instanceof EntityDomainType<?> ) {
final String entityName = ( (EntityDomainType<?>) lhsAttributeJoin.getReferencedPathSource() ).getHibernateEntityName(); final String entityName = ( (EntityDomainType<?>) lhsAttributeJoin.getReferencedPathSource() ).getHibernateEntityName();
return (ModelPartContainer) creationState.getCreationContext().getQueryEngine() return (ModelPartContainer) creationState.getCreationContext()
.getTypeConfiguration() .getJpaMetamodel()
.getSessionFactory()
.getRuntimeMetamodels()
.getMappingMetamodel() .getMappingMetamodel()
.getEntityDescriptor( entityName ) .getEntityDescriptor( entityName )
.findSubPart( attributeJoin.getAttribute().getName(), null ); .findSubPart( attributeJoin.getAttribute().getName(), null );
@ -230,10 +228,8 @@ public abstract class AbstractSqmFrom<O,T> extends AbstractSqmPath<T> implements
assert lhs instanceof SqmCrossJoin<?>; assert lhs instanceof SqmCrossJoin<?>;
entityName = ( (SqmCrossJoin<?>) lhs ).getEntityName(); entityName = ( (SqmCrossJoin<?>) lhs ).getEntityName();
} }
return (ModelPartContainer) creationState.getCreationContext().getQueryEngine() return (ModelPartContainer) creationState.getCreationContext()
.getTypeConfiguration() .getJpaMetamodel()
.getSessionFactory()
.getRuntimeMetamodels()
.getMappingMetamodel() .getMappingMetamodel()
.getEntityDescriptor( entityName ) .getEntityDescriptor( entityName )
.findSubPart( attributeJoin.getAttribute().getName(), null ); .findSubPart( attributeJoin.getAttribute().getName(), null );

View File

@ -20,8 +20,8 @@ import org.hibernate.query.sqm.tree.SqmCopyContext;
/** /**
* {@link JpaParameterExpression} created via JPA {@link jakarta.persistence.criteria.CriteriaBuilder}. * {@link JpaParameterExpression} created via JPA {@link jakarta.persistence.criteria.CriteriaBuilder}.
* * <p>
* Each occurrence of a JpaParameterExpression results in a unique SqmParameter * Each occurrence of a {@code JpaParameterExpression} results in a unique {@link SqmParameter}.
* *
* @see ParameterMetadata * @see ParameterMetadata
* @see NodeBuilder#parameter * @see NodeBuilder#parameter
@ -54,9 +54,7 @@ public class JpaCriteriaParameter<T>
if ( type == null ) { if ( type == null ) {
return null; return null;
} }
return type.resolveExpressible( return type.resolveExpressible( nodeBuilder.getSessionFactory() );
nodeBuilder.getQueryEngine().getTypeConfiguration().getSessionFactory()
);
} }
@Override @Override

View File

@ -36,16 +36,16 @@ import org.hibernate.usertype.internal.AbstractTimeZoneStorageCompositeUserType;
*/ */
public class SqmExpressionHelper { public class SqmExpressionHelper {
public static <T> SqmExpressible<T> toSqmType(BindableType<T> parameterType, SqmCreationState creationState) { public static <T> SqmExpressible<T> toSqmType(BindableType<T> parameterType, SqmCreationState creationState) {
return toSqmType( parameterType, creationState.getCreationContext().getJpaMetamodel().getTypeConfiguration() ); return toSqmType( parameterType, creationState.getCreationContext().getNodeBuilder().getSessionFactory() );
} }
public static <T> SqmExpressible<T> toSqmType(BindableType<T> anticipatedType, NodeBuilder nodeBuilder) { public static <T> SqmExpressible<T> toSqmType(BindableType<T> anticipatedType, NodeBuilder nodeBuilder) {
return toSqmType( anticipatedType, nodeBuilder.getTypeConfiguration() ); return toSqmType( anticipatedType, nodeBuilder.getSessionFactory() );
} }
public static <T> SqmExpressible<T> toSqmType(BindableType<T> anticipatedType, TypeConfiguration typeConfiguration) { // public static <T> SqmExpressible<T> toSqmType(BindableType<T> anticipatedType, TypeConfiguration typeConfiguration) {
return toSqmType( anticipatedType, typeConfiguration.getSessionFactory() ); // return toSqmType( anticipatedType, typeConfiguration.getSessionFactory() );
} // }
public static <T> SqmExpressible<T> toSqmType(BindableType<T> anticipatedType, SessionFactoryImplementor sessionFactory) { public static <T> SqmExpressible<T> toSqmType(BindableType<T> anticipatedType, SessionFactoryImplementor sessionFactory) {
if ( anticipatedType == null ) { if ( anticipatedType == null ) {

View File

@ -32,11 +32,12 @@ import org.hibernate.internal.util.collections.ArrayHelper;
import org.hibernate.metamodel.spi.MappingMetamodelImplementor; import org.hibernate.metamodel.spi.MappingMetamodelImplementor;
import org.hibernate.persister.entity.EntityPersister; import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.persister.entity.Joinable; import org.hibernate.persister.entity.Joinable;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.proxy.LazyInitializer; import org.hibernate.proxy.LazyInitializer;
import org.hibernate.type.spi.TypeConfiguration; import org.hibernate.type.spi.TypeConfiguration;
import static org.hibernate.pretty.MessageHelper.infoString;
import static org.hibernate.proxy.HibernateProxy.extractLazyInitializer;
/** /**
* Handles "any" mappings * Handles "any" mappings
* *
@ -121,32 +122,37 @@ public class AnyType extends AbstractType implements CompositeType, AssociationT
@Override @Override
public int compare(Object x, Object y) { public int compare(Object x, Object y) {
throw new UnsupportedOperationException( "compare() not implemented for AnyType" );
}
@Override
public int compare(Object x, Object y, SessionFactoryImplementor factory) {
if ( x == null ) { if ( x == null ) {
// if y is also null, return that they are the same (no option for "UNKNOWN") // if y is also null, return that they are the same (no option for "UNKNOWN")
// if y is not null, return that y is "greater" (-1 because the result is from the perspective of // if y is not null, return that y is "greater"
// the first arg: x) // (-1 because the result is from the perspective of the first arg: x)
return y == null ? 0 : -1; return y == null ? 0 : -1;
} }
else if ( y == null ) { else if ( y == null ) {
// x is not null, but y is. return that x is "greater" // x is not null, but y is, return that x is "greater"
return 1; return 1;
} }
// At this point we know both are non-null. // At this point we know both are non-null.
final Object xId = extractIdentifier( x ); final Object xId = extractIdentifier( x, factory );
final Object yId = extractIdentifier( y ); final Object yId = extractIdentifier( y, factory );
return getIdentifierType().compare( xId, yId ); return getIdentifierType().compare( xId, yId );
} }
private Object extractIdentifier(Object entity) { private Object extractIdentifier(Object entity, SessionFactoryImplementor factory) {
final EntityPersister concretePersister = guessEntityPersister( entity ); final EntityPersister concretePersister = guessEntityPersister( entity, factory );
return concretePersister == null return concretePersister == null
? null ? null
: concretePersister.getIdentifier( entity, null ); : concretePersister.getIdentifier( entity, null );
} }
private EntityPersister guessEntityPersister(Object object) { private EntityPersister guessEntityPersister(Object object, SessionFactoryImplementor factory) {
if ( typeConfiguration == null ) { if ( typeConfiguration == null ) {
return null; return null;
} }
@ -155,7 +161,7 @@ public class AnyType extends AbstractType implements CompositeType, AssociationT
// this code is largely copied from Session's bestGuessEntityName // this code is largely copied from Session's bestGuessEntityName
Object entity = object; Object entity = object;
final LazyInitializer lazyInitializer = HibernateProxy.extractLazyInitializer( entity ); final LazyInitializer lazyInitializer = extractLazyInitializer( entity );
if ( lazyInitializer != null ) { if ( lazyInitializer != null ) {
if ( lazyInitializer.isUninitialized() ) { if ( lazyInitializer.isUninitialized() ) {
entityName = lazyInitializer.getEntityName(); entityName = lazyInitializer.getEntityName();
@ -164,9 +170,7 @@ public class AnyType extends AbstractType implements CompositeType, AssociationT
} }
if ( entityName == null ) { if ( entityName == null ) {
final MappingMetamodelImplementor mappingMetamodel = typeConfiguration.getSessionFactory() final MappingMetamodelImplementor mappingMetamodel = factory.getRuntimeMetamodels().getMappingMetamodel();
.getRuntimeMetamodels()
.getMappingMetamodel();
for ( EntityNameResolver resolver : mappingMetamodel.getEntityNameResolvers() ) { for ( EntityNameResolver resolver : mappingMetamodel.getEntityNameResolvers() ) {
entityName = resolver.resolveEntityName( entity ); entityName = resolver.resolveEntityName( entity );
if ( entityName != null ) { if ( entityName != null ) {
@ -180,7 +184,7 @@ public class AnyType extends AbstractType implements CompositeType, AssociationT
entityName = object.getClass().getName(); entityName = object.getClass().getName();
} }
return typeConfiguration.getSessionFactory().getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor( entityName ); return factory.getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor( entityName );
} }
@Override @Override
@ -201,7 +205,7 @@ public class AnyType extends AbstractType implements CompositeType, AssociationT
final ObjectTypeCacheEntry holder = (ObjectTypeCacheEntry) old; final ObjectTypeCacheEntry holder = (ObjectTypeCacheEntry) old;
final boolean[] idCheckable = new boolean[checkable.length-1]; final boolean[] idCheckable = new boolean[checkable.length-1];
System.arraycopy( checkable, 1, idCheckable, 0, idCheckable.length ); System.arraycopy( checkable, 1, idCheckable, 0, idCheckable.length );
return ( checkable[0] && !holder.entityName.equals( session.bestGuessEntityName( current ) ) ) return checkable[0] && !holder.entityName.equals( session.bestGuessEntityName( current ) )
|| identifierType.isModified( holder.id, getIdentifier( current, session ), idCheckable, session ); || identifierType.isModified( holder.id, getIdentifier( current, session ), idCheckable, session );
} }
@ -270,11 +274,11 @@ public class AnyType extends AbstractType implements CompositeType, AssociationT
return "<uninitialized>"; return "<uninitialized>";
} }
String entityName = factory.bestGuessEntityName(value); final String entityName = factory.bestGuessEntityName(value);
final EntityPersister descriptor = entityName == null final EntityPersister descriptor = entityName == null
? null ? null
: factory.getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor( entityName ); : factory.getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor( entityName );
return MessageHelper.infoString( descriptor, value, factory ); return infoString( descriptor, value, factory );
} }
@Override @Override

View File

@ -153,8 +153,8 @@ public class BasicTypeRegistry implements Serializable {
} }
/** /**
* Find an existing BasicType registration for the given JavaType descriptor and * Find an existing {@link BasicType} registration for the given {@link JavaType}
* JdbcType descriptor combo or create (and register) one. * descriptor and {@link JdbcType} descriptor combo or create (and register) one.
*/ */
public <J> BasicType<J> resolve(JavaType<J> jtdToUse, JdbcType stdToUse) { public <J> BasicType<J> resolve(JavaType<J> jtdToUse, JdbcType stdToUse) {
return resolve( return resolve(
@ -163,10 +163,11 @@ public class BasicTypeRegistry implements Serializable {
() -> { () -> {
final BasicTypeImpl<J> basicType = new BasicTypeImpl<>( jtdToUse, stdToUse ); final BasicTypeImpl<J> basicType = new BasicTypeImpl<>( jtdToUse, stdToUse );
// if we are still building mappings, register this ad-hoc type via a // if we are still building mappings, register this ad-hoc type
// unique code. this is to support envers // via a unique code. this is to support envers
try { try {
typeConfiguration.getMetadataBuildingContext().getBootstrapContext().registerAdHocBasicType( basicType ); typeConfiguration.getMetadataBuildingContext().getBootstrapContext()
.registerAdHocBasicType( basicType );
} }
catch (Exception ignore) { catch (Exception ignore) {
} }

View File

@ -217,11 +217,7 @@ public abstract class EntityType extends AbstractType implements AssociationType
return ReflectHelper.classForName( entityName ); return ReflectHelper.classForName( entityName );
} }
catch ( ClassNotFoundException cnfe ) { catch ( ClassNotFoundException cnfe ) {
return typeConfiguration.getSessionFactory() return typeConfiguration.entityClassForEntityName( entityName );
.getRuntimeMetamodels()
.getMappingMetamodel()
.getEntityDescriptor( entityName )
.getMappedClass();
} }
} }
@ -256,7 +252,35 @@ public abstract class EntityType extends AbstractType implements AssociationType
@Override @Override
public int compare(Object x, Object y) { public int compare(Object x, Object y) {
return 0; //TODO: entities CAN be compared, by PK, fix this! -> only if/when we can extract the id values.... throw new UnsupportedOperationException( "compare() not implemented for EntityType" );
}
@Override
public int compare(Object x, Object y, SessionFactoryImplementor factory) {
if ( x == null ) {
// if y is also null, return that they are the same (no option for "UNKNOWN")
// if y is not null, return that y is "greater"
// (-1 because the result is from the perspective of the first arg: x)
return y == null ? 0 : -1;
}
else if ( y == null ) {
// x is not null, but y is, return that x is "greater"
return 1;
}
// At this point we know both are non-null.
final Object xId = extractIdentifier( x, factory );
final Object yId = extractIdentifier( y, factory );
return getIdentifierType( factory ).compare( xId, yId );
}
private Object extractIdentifier(Object entity, SessionFactoryImplementor factory) {
final EntityPersister concretePersister =
factory.getMappingMetamodel().getEntityDescriptor( associatedEntityName );
return concretePersister == null
? null
: concretePersister.getIdentifier( entity, null );
} }
@Override @Override

View File

@ -30,7 +30,6 @@ import org.hibernate.metamodel.model.convert.spi.BasicValueConverter;
import org.hibernate.metamodel.model.convert.spi.EnumValueConverter; import org.hibernate.metamodel.model.convert.spi.EnumValueConverter;
import org.hibernate.type.descriptor.ValueBinder; import org.hibernate.type.descriptor.ValueBinder;
import org.hibernate.type.descriptor.ValueExtractor; import org.hibernate.type.descriptor.ValueExtractor;
import org.hibernate.type.descriptor.java.BasicJavaType;
import org.hibernate.type.descriptor.java.EnumJavaType; import org.hibernate.type.descriptor.java.EnumJavaType;
import org.hibernate.type.descriptor.java.JavaType; import org.hibernate.type.descriptor.java.JavaType;
import org.hibernate.type.descriptor.jdbc.JdbcType; import org.hibernate.type.descriptor.jdbc.JdbcType;

View File

@ -218,6 +218,9 @@ public interface Type extends Serializable {
*/ */
int compare(Object x, Object y); int compare(Object x, Object y);
default int compare(Object x, Object y, SessionFactoryImplementor sessionFactory) {
return compare( x, y );
}
/** /**
* Should the parent be considered dirty, given both the old and current value? * Should the parent be considered dirty, given both the old and current value?
* *
@ -480,5 +483,4 @@ public interface Type extends Serializable {
* @return array indicating column nullness for a value instance * @return array indicating column nullness for a value instance
*/ */
boolean[] toColumnNullness(Object value, Mapping mapping); boolean[] toColumnNullness(Object value, Mapping mapping);
} }

View File

@ -32,6 +32,7 @@ import java.util.function.Function;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.Incubating; import org.hibernate.Incubating;
import org.hibernate.Internal;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
import org.hibernate.SessionFactoryObserver; import org.hibernate.SessionFactoryObserver;
import org.hibernate.TimeZoneStorageStrategy; import org.hibernate.TimeZoneStorageStrategy;
@ -44,6 +45,7 @@ import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.id.uuid.LocalObjectUuidHelper; import org.hibernate.id.uuid.LocalObjectUuidHelper;
import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.SessionFactoryRegistry; import org.hibernate.internal.SessionFactoryRegistry;
import org.hibernate.jpa.spi.JpaCompliance;
import org.hibernate.metamodel.mapping.BasicValuedMapping; import org.hibernate.metamodel.mapping.BasicValuedMapping;
import org.hibernate.metamodel.mapping.JdbcMapping; import org.hibernate.metamodel.mapping.JdbcMapping;
import org.hibernate.metamodel.mapping.JdbcMappingContainer; import org.hibernate.metamodel.mapping.JdbcMappingContainer;
@ -147,7 +149,7 @@ public class TypeConfiguration implements SessionFactoryObserver, Serializable {
} }
public JdbcTypeIndicators getCurrentBaseSqlTypeIndicators() { public JdbcTypeIndicators getCurrentBaseSqlTypeIndicators() {
return scope.getCurrentBaseSqlTypeIndicators(); return scope;
} }
public Map<Integer, Set<String>> getJdbcToHibernateTypeContributionMap() { public Map<Integer, Set<String>> getJdbcToHibernateTypeContributionMap() {
@ -165,7 +167,10 @@ public class TypeConfiguration implements SessionFactoryObserver, Serializable {
* stages a {@code TypeConfiguration} passes through. * stages a {@code TypeConfiguration} passes through.
* *
* @return The {@link MetadataBuildingContext} * @return The {@link MetadataBuildingContext}
*
* @deprecated This operation is not very typesafe, and we're migrating away from its use
*/ */
@Deprecated(since = "6.2")
public MetadataBuildingContext getMetadataBuildingContext() { public MetadataBuildingContext getMetadataBuildingContext() {
return scope.getMetadataBuildingContext(); return scope.getMetadataBuildingContext();
} }
@ -211,7 +216,10 @@ public class TypeConfiguration implements SessionFactoryObserver, Serializable {
* *
* @throws HibernateException if the {@code TypeConfiguration} is not currently scoped * @throws HibernateException if the {@code TypeConfiguration} is not currently scoped
* to a {@link SessionFactory} (in a "runtime stage"). * to a {@link SessionFactory} (in a "runtime stage").
*
* @deprecated This operation is not very typesafe, and we're migrating away from its use
*/ */
@Deprecated(since = "6.2")
public SessionFactoryImplementor getSessionFactory() { public SessionFactoryImplementor getSessionFactory() {
return scope.getSessionFactory(); return scope.getSessionFactory();
} }
@ -228,6 +236,21 @@ public class TypeConfiguration implements SessionFactoryObserver, Serializable {
return scope.getServiceRegistry(); return scope.getServiceRegistry();
} }
/**
* Obtain the {@link JpaCompliance} setting.
*/
public JpaCompliance getJpaCompliance() {
return scope.getJpaCompliance();
}
/**
* Workaround for an issue faced in {@link org.hibernate.type.EntityType#getReturnedClass()}.
*/
@Internal
public Class<?> entityClassForEntityName(String entityName) {
return scope.entityClassForEntityName(entityName);
}
@Override @Override
public void sessionFactoryCreated(SessionFactory factory) { public void sessionFactoryCreated(SessionFactory factory) {
// Instead of allowing scope#setSessionFactory to influence this, we use the SessionFactoryObserver callback // Instead of allowing scope#setSessionFactory to influence this, we use the SessionFactoryObserver callback
@ -365,7 +388,7 @@ public class TypeConfiguration implements SessionFactoryObserver, Serializable {
* <p> * <p>
* Each stage or phase is considered a scope for the {@link TypeConfiguration}. * Each stage or phase is considered a scope for the {@link TypeConfiguration}.
*/ */
private static class Scope implements Serializable { private static class Scope implements JdbcTypeIndicators, Serializable {
private final TypeConfiguration typeConfiguration; private final TypeConfiguration typeConfiguration;
private transient MetadataBuildingContext metadataBuildingContext; private transient MetadataBuildingContext metadataBuildingContext;
@ -374,7 +397,6 @@ public class TypeConfiguration implements SessionFactoryObserver, Serializable {
private String sessionFactoryName; private String sessionFactoryName;
private String sessionFactoryUuid; private String sessionFactoryUuid;
private final transient JdbcTypeIndicators currentSqlTypeIndicators = new JdbcTypeIndicators() {
@Override @Override
public TypeConfiguration getTypeConfiguration() { public TypeConfiguration getTypeConfiguration() {
return typeConfiguration; return typeConfiguration;
@ -383,62 +405,57 @@ public class TypeConfiguration implements SessionFactoryObserver, Serializable {
@Override @Override
public TimeZoneStorageStrategy getDefaultTimeZoneStorageStrategy() { public TimeZoneStorageStrategy getDefaultTimeZoneStorageStrategy() {
return sessionFactory == null return sessionFactory == null
? getMetadataBuildingContext().getBuildingOptions().getDefaultTimeZoneStorage() ? metadataBuildingContext.getBuildingOptions().getDefaultTimeZoneStorage()
: getTypeConfiguration().getSessionFactory().getSessionFactoryOptions().getDefaultTimeZoneStorageStrategy(); : sessionFactory.getSessionFactoryOptions().getDefaultTimeZoneStorageStrategy();
} }
@Override @Override
public int getPreferredSqlTypeCodeForBoolean() { public int getPreferredSqlTypeCodeForBoolean() {
return sessionFactory == null return sessionFactory == null
? getMetadataBuildingContext().getPreferredSqlTypeCodeForBoolean() ? metadataBuildingContext.getPreferredSqlTypeCodeForBoolean()
: getTypeConfiguration().getSessionFactory().getSessionFactoryOptions().getPreferredSqlTypeCodeForBoolean(); : sessionFactory.getSessionFactoryOptions().getPreferredSqlTypeCodeForBoolean();
} }
@Override @Override
public int getPreferredSqlTypeCodeForDuration() { public int getPreferredSqlTypeCodeForDuration() {
return sessionFactory == null return sessionFactory == null
? getMetadataBuildingContext().getPreferredSqlTypeCodeForDuration() ? metadataBuildingContext.getPreferredSqlTypeCodeForDuration()
: getTypeConfiguration().getSessionFactory().getSessionFactoryOptions().getPreferredSqlTypeCodeForDuration(); : sessionFactory.getSessionFactoryOptions().getPreferredSqlTypeCodeForDuration();
} }
@Override @Override
public int getPreferredSqlTypeCodeForUuid() { public int getPreferredSqlTypeCodeForUuid() {
return sessionFactory == null return sessionFactory == null
? getMetadataBuildingContext().getPreferredSqlTypeCodeForUuid() ? metadataBuildingContext.getPreferredSqlTypeCodeForUuid()
: getTypeConfiguration().getSessionFactory().getSessionFactoryOptions().getPreferredSqlTypeCodeForUuid(); : sessionFactory.getSessionFactoryOptions().getPreferredSqlTypeCodeForUuid();
} }
@Override @Override
public int getPreferredSqlTypeCodeForInstant() { public int getPreferredSqlTypeCodeForInstant() {
return sessionFactory == null return sessionFactory == null
? getMetadataBuildingContext().getPreferredSqlTypeCodeForInstant() ? metadataBuildingContext.getPreferredSqlTypeCodeForInstant()
: getTypeConfiguration().getSessionFactory().getSessionFactoryOptions().getPreferredSqlTypeCodeForInstant(); : sessionFactory.getSessionFactoryOptions().getPreferredSqlTypeCodeForInstant();
} }
@Override @Override
public int getPreferredSqlTypeCodeForArray() { public int getPreferredSqlTypeCodeForArray() {
return sessionFactory == null return sessionFactory == null
? getMetadataBuildingContext().getPreferredSqlTypeCodeForArray() ? metadataBuildingContext.getPreferredSqlTypeCodeForArray()
: getTypeConfiguration().getSessionFactory().getSessionFactoryOptions().getPreferredSqlTypeCodeForArray(); : sessionFactory.getSessionFactoryOptions().getPreferredSqlTypeCodeForArray();
} }
};
public Scope(TypeConfiguration typeConfiguration) { private Scope(TypeConfiguration typeConfiguration) {
this.typeConfiguration = typeConfiguration; this.typeConfiguration = typeConfiguration;
} }
public JdbcTypeIndicators getCurrentBaseSqlTypeIndicators() { private MetadataBuildingContext getMetadataBuildingContext() {
return currentSqlTypeIndicators;
}
public MetadataBuildingContext getMetadataBuildingContext() {
if ( metadataBuildingContext == null ) { if ( metadataBuildingContext == null ) {
throw new HibernateException( "TypeConfiguration is not currently scoped to MetadataBuildingContext" ); throw new HibernateException( "TypeConfiguration is not currently scoped to MetadataBuildingContext" );
} }
return metadataBuildingContext; return metadataBuildingContext;
} }
public ServiceRegistry getServiceRegistry() { private ServiceRegistry getServiceRegistry() {
if ( metadataBuildingContext != null ) { if ( metadataBuildingContext != null ) {
return metadataBuildingContext.getBootstrapContext().getServiceRegistry(); return metadataBuildingContext.getBootstrapContext().getServiceRegistry();
} }
@ -448,11 +465,21 @@ public class TypeConfiguration implements SessionFactoryObserver, Serializable {
return null; return null;
} }
public void setMetadataBuildingContext(MetadataBuildingContext metadataBuildingContext) { private JpaCompliance getJpaCompliance() {
if ( metadataBuildingContext != null ) {
return metadataBuildingContext.getBootstrapContext().getJpaCompliance();
}
else if ( sessionFactory != null ) {
return sessionFactory.getSessionFactoryOptions().getJpaCompliance();
}
return null;
}
private void setMetadataBuildingContext(MetadataBuildingContext metadataBuildingContext) {
this.metadataBuildingContext = metadataBuildingContext; this.metadataBuildingContext = metadataBuildingContext;
} }
public SessionFactoryImplementor getSessionFactory() { private SessionFactoryImplementor getSessionFactory() {
if ( sessionFactory == null ) { if ( sessionFactory == null ) {
if ( sessionFactoryName == null && sessionFactoryUuid == null ) { if ( sessionFactoryName == null && sessionFactoryUuid == null ) {
throw new HibernateException( "TypeConfiguration was not yet scoped to SessionFactory" ); throw new HibernateException( "TypeConfiguration was not yet scoped to SessionFactory" );
@ -477,26 +504,30 @@ public class TypeConfiguration implements SessionFactoryObserver, Serializable {
* *
* @param factory The {@link SessionFactory} to which the {@link TypeConfiguration} is being bound * @param factory The {@link SessionFactory} to which the {@link TypeConfiguration} is being bound
*/ */
void setSessionFactory(SessionFactoryImplementor factory) { private void setSessionFactory(SessionFactoryImplementor factory) {
if ( this.sessionFactory != null ) { if ( this.sessionFactory != null ) {
log.scopingTypesToSessionFactoryAfterAlreadyScoped( this.sessionFactory, factory ); log.scopingTypesToSessionFactoryAfterAlreadyScoped( this.sessionFactory, factory );
} }
else { else {
this.sessionFactoryUuid = factory.getUuid(); this.sessionFactoryUuid = factory.getUuid();
String factoryName = factory.getSessionFactoryOptions().getSessionFactoryName(); this.sessionFactoryName = getFactoryName( factory );
if ( factoryName == null ) {
final CfgXmlAccessService cfgXmlAccessService = factory.getServiceRegistry()
.getService( CfgXmlAccessService.class );
if ( cfgXmlAccessService.getAggregatedConfig() != null ) {
factoryName = cfgXmlAccessService.getAggregatedConfig().getSessionFactoryName();
}
}
this.sessionFactoryName = factoryName;
} }
this.sessionFactory = factory; this.sessionFactory = factory;
} }
public void unsetSessionFactory(SessionFactory factory) { private static String getFactoryName(SessionFactoryImplementor factory) {
final String factoryName = factory.getSessionFactoryOptions().getSessionFactoryName();
if ( factoryName == null ) {
final CfgXmlAccessService cfgXmlAccessService = factory.getServiceRegistry()
.getService( CfgXmlAccessService.class );
if ( cfgXmlAccessService.getAggregatedConfig() != null ) {
return cfgXmlAccessService.getAggregatedConfig().getSessionFactoryName();
}
}
return factoryName;
}
private void unsetSessionFactory(SessionFactory factory) {
log.debugf( "Un-scoping TypeConfiguration [%s] from SessionFactory [%s]", this, factory ); log.debugf( "Un-scoping TypeConfiguration [%s] from SessionFactory [%s]", this, factory );
this.sessionFactory = null; this.sessionFactory = null;
} }
@ -522,6 +553,12 @@ public class TypeConfiguration implements SessionFactoryObserver, Serializable {
return this; return this;
} }
private Class<?> entityClassForEntityName(String entityName) {
return sessionFactory == null
? metadataBuildingContext.getMetadataCollector().getEntityBinding( entityName ).getMappedClass()
: sessionFactory.getMappingMetamodel().findEntityDescriptor( entityName ).getMappedClass();
}
} }

View File

@ -31,6 +31,7 @@ import org.hibernate.boot.registry.BootstrapServiceRegistry;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.spi.BootstrapContext;
import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Environment; import org.hibernate.cfg.Environment;
@ -223,8 +224,12 @@ public class DefaultCatalogAndSchemaTest {
break; break;
case SESSION_FACTORY_SERVICE_REGISTRY: case SESSION_FACTORY_SERVICE_REGISTRY:
serviceRegistry = createStandardServiceRegistry( configuredDefaultCatalog, configuredDefaultSchema ); serviceRegistry = createStandardServiceRegistry( configuredDefaultCatalog, configuredDefaultSchema );
sfb = new SessionFactoryBuilderImpl( metadata, new SessionFactoryOptionsBuilder( serviceRegistry, BootstrapContext bootstrapContext = ((MetadataImpl) metadata).getBootstrapContext();
((MetadataImpl) metadata).getBootstrapContext() ) ); sfb = new SessionFactoryBuilderImpl(
metadata,
new SessionFactoryOptionsBuilder( serviceRegistry, bootstrapContext),
bootstrapContext
);
break; break;
default: default:
throw new IllegalStateException( "Unknown settings mode: " + settingsMode ); throw new IllegalStateException( "Unknown settings mode: " + settingsMode );

View File

@ -72,7 +72,7 @@ public class CascadeDeleteCollectionWithCollectionInDefaultFetchGroupFalseTest e
// We want to test with this setting set to false explicitly, // We want to test with this setting set to false explicitly,
// because another test already takes care of the default. // because another test already takes care of the default.
optionsBuilder.enableCollectionInDefaultFetchGroup( false ); optionsBuilder.enableCollectionInDefaultFetchGroup( false );
return new SessionFactoryBuilderImpl( metadata, optionsBuilder ); return new SessionFactoryBuilderImpl( metadata, optionsBuilder, bootstrapContext );
} }
); );
} }

View File

@ -80,7 +80,7 @@ public class CascadeOnUninitializedWithCollectionInDefaultFetchGroupFalseTest ex
// We want to test with this setting set to false explicitly, // We want to test with this setting set to false explicitly,
// because another test already takes care of the default. // because another test already takes care of the default.
optionsBuilder.enableCollectionInDefaultFetchGroup( false ); optionsBuilder.enableCollectionInDefaultFetchGroup( false );
return new SessionFactoryBuilderImpl( metadata, optionsBuilder ); return new SessionFactoryBuilderImpl( metadata, optionsBuilder, bootstrapContext );
} }
); );
} }

View File

@ -67,7 +67,7 @@ public class DirtyTrackingCollectionInDefaultFetchGroupFalseTest extends BaseCor
// We want to test with this setting set to false explicitly, // We want to test with this setting set to false explicitly,
// because another test already takes care of the default. // because another test already takes care of the default.
optionsBuilder.enableCollectionInDefaultFetchGroup( false ); optionsBuilder.enableCollectionInDefaultFetchGroup( false );
return new SessionFactoryBuilderImpl( metadata, optionsBuilder ); return new SessionFactoryBuilderImpl( metadata, optionsBuilder, bootstrapContext );
} }
); );
} }

View File

@ -22,7 +22,6 @@ import org.hibernate.boot.internal.SessionFactoryBuilderImpl;
import org.hibernate.boot.internal.SessionFactoryOptionsBuilder; import org.hibernate.boot.internal.SessionFactoryOptionsBuilder;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.spi.SessionFactoryBuilderService; import org.hibernate.boot.spi.SessionFactoryBuilderService;
import org.hibernate.orm.test.bytecode.enhancement.dirty.DirtyTrackingCollectionInDefaultFetchGroupTest;
import org.hibernate.proxy.HibernateProxy; import org.hibernate.proxy.HibernateProxy;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
@ -72,7 +71,7 @@ public class LazyCollectionDetachWithCollectionInDefaultFetchGroupFalseTest exte
// We want to test with this setting set to false explicitly, // We want to test with this setting set to false explicitly,
// because another test already takes care of the default. // because another test already takes care of the default.
optionsBuilder.enableCollectionInDefaultFetchGroup( false ); optionsBuilder.enableCollectionInDefaultFetchGroup( false );
return new SessionFactoryBuilderImpl( metadata, optionsBuilder ); return new SessionFactoryBuilderImpl( metadata, optionsBuilder, bootstrapContext );
} }
); );
} }

View File

@ -65,7 +65,7 @@ public class UninitializedAssociationsInCacheTest extends BaseCoreFunctionalTest
); );
// This test only makes sense if association properties *can* be uninitialized. // This test only makes sense if association properties *can* be uninitialized.
optionsBuilder.enableCollectionInDefaultFetchGroup( false ); optionsBuilder.enableCollectionInDefaultFetchGroup( false );
return new SessionFactoryBuilderImpl( metadata, optionsBuilder ); return new SessionFactoryBuilderImpl( metadata, optionsBuilder, bootstrapContext );
} }
); );
} }

View File

@ -63,7 +63,7 @@ public class BytecodeEnhancedLazyLoadingOnDeletedEntityTest
); );
// This test only makes sense if association properties *can* be uninitialized. // This test only makes sense if association properties *can* be uninitialized.
optionsBuilder.enableCollectionInDefaultFetchGroup( false ); optionsBuilder.enableCollectionInDefaultFetchGroup( false );
return new SessionFactoryBuilderImpl( metadata, optionsBuilder ); return new SessionFactoryBuilderImpl( metadata, optionsBuilder, bootstrapContext );
} }
); );
} }

View File

@ -80,7 +80,7 @@ public class SimpleUpdateWithLazyLoadingWithCollectionInDefaultFetchGroupFalseTe
// We want to test with this setting set to false explicitly, // We want to test with this setting set to false explicitly,
// because another test already takes care of the default. // because another test already takes care of the default.
optionsBuilder.enableCollectionInDefaultFetchGroup( false ); optionsBuilder.enableCollectionInDefaultFetchGroup( false );
return new SessionFactoryBuilderImpl( metadata, optionsBuilder ); return new SessionFactoryBuilderImpl( metadata, optionsBuilder, bootstrapContext );
} }
); );
} }

View File

@ -26,7 +26,6 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.spi.SessionFactoryBuilderService; import org.hibernate.boot.spi.SessionFactoryBuilderService;
import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Configuration;
import org.hibernate.orm.test.bytecode.enhancement.lazy.proxy.SimpleUpdateTestWithLazyLoading;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.bytecode.enhancement.BytecodeEnhancerRunner; import org.hibernate.testing.bytecode.enhancement.BytecodeEnhancerRunner;
@ -83,7 +82,7 @@ public class OnDemandLoadWithCollectionInDefaultFetchGroupFalseTest extends Base
// We want to test with this setting set to false explicitly, // We want to test with this setting set to false explicitly,
// because another test already takes care of the default. // because another test already takes care of the default.
optionsBuilder.enableCollectionInDefaultFetchGroup( false ); optionsBuilder.enableCollectionInDefaultFetchGroup( false );
return new SessionFactoryBuilderImpl( metadata, optionsBuilder ); return new SessionFactoryBuilderImpl( metadata, optionsBuilder, bootstrapContext );
} }
); );
} }

View File

@ -12,7 +12,6 @@ import java.util.Properties;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import org.hibernate.annotations.common.reflection.ReflectionManager; import org.hibernate.annotations.common.reflection.ReflectionManager;
import org.hibernate.boot.internal.MetadataImpl;
import org.hibernate.boot.registry.classloading.spi.ClassLoadingException; import org.hibernate.boot.registry.classloading.spi.ClassLoadingException;
import org.hibernate.boot.registry.selector.spi.StrategySelector; import org.hibernate.boot.registry.selector.spi.StrategySelector;
import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.boot.spi.MetadataImplementor;
@ -186,7 +185,10 @@ public class Configuration {
// todo: there are places that need bits built from the revinfo entity configuration // todo: there are places that need bits built from the revinfo entity configuration
// this exists here as a way to pass it down in an immutable way to any consumer of this class // this exists here as a way to pass it down in an immutable way to any consumer of this class
final ReflectionManager reflectionManager = metadata.getMetadataBuildingOptions().getTypeConfiguration().getMetadataBuildingContext().getBootstrapContext().getReflectionManager(); final ReflectionManager reflectionManager =
metadata.getMetadataBuildingOptions().getTypeConfiguration()
.getMetadataBuildingContext().getBootstrapContext()
.getReflectionManager();
this.revisionInfo = new RevisionInfoConfiguration( this, metadata, reflectionManager ); this.revisionInfo = new RevisionInfoConfiguration( this, metadata, reflectionManager );
} }