various cleanups

This commit is contained in:
Gavin King 2024-12-14 10:51:19 +01:00
parent 8b4d6b75bc
commit a1b0fac8f1
14 changed files with 160 additions and 209 deletions

View File

@ -7,7 +7,6 @@ package org.hibernate.boot.internal;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.concurrent.Callable;
import org.hibernate.AnnotationException; import org.hibernate.AnnotationException;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
@ -72,8 +71,6 @@ import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.internal.CoreLogging; import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.log.DeprecationLogger; import org.hibernate.internal.log.DeprecationLogger;
import org.hibernate.internal.util.NullnessHelper;
import org.hibernate.internal.util.collections.CollectionHelper;
import org.hibernate.metamodel.CollectionClassification; import org.hibernate.metamodel.CollectionClassification;
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;
@ -95,7 +92,9 @@ import static org.hibernate.cfg.AvailableSettings.JPA_COMPLIANCE;
import static org.hibernate.cfg.AvailableSettings.WRAPPER_ARRAY_HANDLING; import static org.hibernate.cfg.AvailableSettings.WRAPPER_ARRAY_HANDLING;
import static org.hibernate.cfg.MappingSettings.XML_FORMAT_MAPPER_LEGACY_FORMAT; import static org.hibernate.cfg.MappingSettings.XML_FORMAT_MAPPER_LEGACY_FORMAT;
import static org.hibernate.engine.config.spi.StandardConverters.BOOLEAN; import static org.hibernate.engine.config.spi.StandardConverters.BOOLEAN;
import static org.hibernate.internal.util.NullnessHelper.coalesceSuppliedValues;
import static org.hibernate.internal.util.StringHelper.nullIfEmpty; import static org.hibernate.internal.util.StringHelper.nullIfEmpty;
import static org.hibernate.internal.util.collections.CollectionHelper.isNotEmpty;
/** /**
* @author Steve Ebersole * @author Steve Ebersole
@ -115,16 +114,15 @@ public class MetadataBuilderImpl implements MetadataBuilderImplementor, TypeCont
if ( serviceRegistry == null ) { if ( serviceRegistry == null ) {
throw new HibernateException( "ServiceRegistry passed to MetadataBuilder cannot be null" ); throw new HibernateException( "ServiceRegistry passed to MetadataBuilder cannot be null" );
} }
else if ( serviceRegistry instanceof StandardServiceRegistry standardServiceRegistry ) {
if ( serviceRegistry instanceof StandardServiceRegistry ) { return standardServiceRegistry;
return (StandardServiceRegistry) serviceRegistry;
} }
else if ( serviceRegistry instanceof BootstrapServiceRegistry ) { else if ( serviceRegistry instanceof BootstrapServiceRegistry bootstrapServiceRegistry ) {
log.debug( log.debug(
"ServiceRegistry passed to MetadataBuilder was a BootstrapServiceRegistry; this likely won't end well " + "ServiceRegistry passed to MetadataBuilder was a BootstrapServiceRegistry; this likely won't end well " +
"if attempt is made to build SessionFactory" "if attempt is made to build SessionFactory"
); );
return new StandardServiceRegistryBuilder( (BootstrapServiceRegistry) serviceRegistry ).build(); return new StandardServiceRegistryBuilder( bootstrapServiceRegistry ).build();
} }
else { else {
throw new HibernateException( throw new HibernateException(
@ -443,8 +441,9 @@ public class MetadataBuilderImpl implements MetadataBuilderImplementor, TypeCont
final MetadataImplementor bootModel = MetadataBuildingProcess.build( sources, bootstrapContext, options ); final MetadataImplementor bootModel = MetadataBuildingProcess.build( sources, bootstrapContext, options );
if ( CollectionHelper.isNotEmpty( sources.getHbmXmlBindings() ) ) { if ( isNotEmpty( sources.getHbmXmlBindings() ) ) {
final ConfigurationService configurationService = bootstrapContext.getServiceRegistry().getService( ConfigurationService.class ); final ConfigurationService configurationService =
bootstrapContext.getServiceRegistry().getService( ConfigurationService.class );
final boolean transformHbm = configurationService != null final boolean transformHbm = configurationService != null
&& configurationService.getSetting( MappingSettings.TRANSFORM_HBM_XML, BOOLEAN,false ); && configurationService.getSetting( MappingSettings.TRANSFORM_HBM_XML, BOOLEAN,false );
@ -664,7 +663,7 @@ public class MetadataBuilderImpl implements MetadataBuilderImplementor, TypeCont
mappingDefaults = new MappingDefaultsImpl( serviceRegistry ); mappingDefaults = new MappingDefaultsImpl( serviceRegistry );
defaultTimezoneStorage = resolveTimeZoneStorageStrategy( configService ); defaultTimezoneStorage = resolveTimeZoneStorageStrategy( configService );
wrapperArrayHandling = resolveWrapperArrayHandling( configService, serviceRegistry ); wrapperArrayHandling = resolveWrapperArrayHandling( configService );
multiTenancyEnabled = JdbcEnvironmentImpl.isMultiTenancyEnabled( serviceRegistry ); multiTenancyEnabled = JdbcEnvironmentImpl.isMultiTenancyEnabled( serviceRegistry );
xmlMappingEnabled = configService.getSetting( xmlMappingEnabled = configService.getSetting(
@ -750,19 +749,14 @@ public class MetadataBuilderImpl implements MetadataBuilderImplementor, TypeCont
null null
) ); ) );
implicitNamingStrategy = strategySelector.resolveDefaultableStrategy( implicitNamingStrategy = strategySelector.<ImplicitNamingStrategy>resolveDefaultableStrategy(
ImplicitNamingStrategy.class, ImplicitNamingStrategy.class,
configService.getSettings().get( AvailableSettings.IMPLICIT_NAMING_STRATEGY ), configService.getSettings().get( AvailableSettings.IMPLICIT_NAMING_STRATEGY ),
new Callable<>() { () -> strategySelector.resolveDefaultableStrategy(
@Override ImplicitNamingStrategy.class,
public ImplicitNamingStrategy call() { "default",
return strategySelector.resolveDefaultableStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE
ImplicitNamingStrategy.class, )
"default",
ImplicitNamingStrategyJpaCompliantImpl.INSTANCE
);
}
}
); );
physicalNamingStrategy = strategySelector.resolveDefaultableStrategy( physicalNamingStrategy = strategySelector.resolveDefaultableStrategy(
@ -771,19 +765,14 @@ public class MetadataBuilderImpl implements MetadataBuilderImplementor, TypeCont
PhysicalNamingStrategyStandardImpl.INSTANCE PhysicalNamingStrategyStandardImpl.INSTANCE
); );
columnOrderingStrategy = strategySelector.resolveDefaultableStrategy( columnOrderingStrategy = strategySelector.<ColumnOrderingStrategy>resolveDefaultableStrategy(
ColumnOrderingStrategy.class, ColumnOrderingStrategy.class,
configService.getSettings().get( AvailableSettings.COLUMN_ORDERING_STRATEGY ), configService.getSettings().get( AvailableSettings.COLUMN_ORDERING_STRATEGY ),
new Callable<>() { () -> strategySelector.resolveDefaultableStrategy(
@Override ColumnOrderingStrategy.class,
public ColumnOrderingStrategy call() { "default",
return strategySelector.resolveDefaultableStrategy( ColumnOrderingStrategyStandard.INSTANCE
ColumnOrderingStrategy.class, )
"default",
ColumnOrderingStrategyStandard.INSTANCE
);
}
}
); );
useNationalizedCharacterData = configService.getSetting( useNationalizedCharacterData = configService.getSetting(
@ -820,12 +809,14 @@ public class MetadataBuilderImpl implements MetadataBuilderImplementor, TypeCont
return toTimeZoneStorageStrategy( getTimeZoneSupport() ); return toTimeZoneStorageStrategy( getTimeZoneSupport() );
} }
private Dialect getDialect() {
return serviceRegistry.requireService( JdbcServices.class ).getDialect();
}
@Override @Override
public TimeZoneSupport getTimeZoneSupport() { public TimeZoneSupport getTimeZoneSupport() {
try { try {
return serviceRegistry.requireService( JdbcServices.class ) return getDialect().getTimeZoneSupport();
.getDialect()
.getTimeZoneSupport();
} }
catch ( ServiceException se ) { catch ( ServiceException se ) {
return TimeZoneSupport.NONE; return TimeZoneSupport.NONE;
@ -844,27 +835,25 @@ public class MetadataBuilderImpl implements MetadataBuilderImplementor, TypeCont
case NORMALIZE -> TimeZoneStorageStrategy.NORMALIZE; case NORMALIZE -> TimeZoneStorageStrategy.NORMALIZE;
case NORMALIZE_UTC -> TimeZoneStorageStrategy.NORMALIZE_UTC; case NORMALIZE_UTC -> TimeZoneStorageStrategy.NORMALIZE_UTC;
case AUTO -> switch (timeZoneSupport) { case AUTO -> switch (timeZoneSupport) {
case NATIVE -> // if the db has native support for timezones, we use that, not a column
// if the db has native support for timezones, we use that, not a column case NATIVE -> TimeZoneStorageStrategy.NATIVE;
TimeZoneStorageStrategy.NATIVE; // otherwise we use a separate column
case NORMALIZE, NONE -> case NORMALIZE, NONE -> TimeZoneStorageStrategy.COLUMN;
// otherwise we use a separate column
TimeZoneStorageStrategy.COLUMN;
}; };
case DEFAULT -> switch (timeZoneSupport) { case DEFAULT -> switch (timeZoneSupport) {
case NATIVE -> // if the db has native support for timezones, we use that, and don't normalize
// if the db has native support for timezones, we use that, and don't normalize case NATIVE -> TimeZoneStorageStrategy.NATIVE;
TimeZoneStorageStrategy.NATIVE; // otherwise we normalize things to UTC
case NORMALIZE, NONE -> case NORMALIZE, NONE -> TimeZoneStorageStrategy.NORMALIZE_UTC;
// otherwise we normalize things to UTC
TimeZoneStorageStrategy.NORMALIZE_UTC;
}; };
}; };
} }
@Override @Override
public WrapperArrayHandling getWrapperArrayHandling() { public WrapperArrayHandling getWrapperArrayHandling() {
return wrapperArrayHandling; return wrapperArrayHandling == WrapperArrayHandling.PICK
? pickWrapperArrayHandling( getDialect() )
: wrapperArrayHandling;
} }
@Override @Override
@ -979,9 +968,7 @@ public class MetadataBuilderImpl implements MetadataBuilderImplementor, TypeCont
} }
if ( mappingDefaults.getImplicitSchemaName() == null ) { if ( mappingDefaults.getImplicitSchemaName() == null ) {
mappingDefaults.implicitSchemaName = nullIfEmpty( mappingDefaults.implicitSchemaName = nullIfEmpty( jpaOrmXmlPersistenceUnitDefaults.getDefaultSchemaName() );
jpaOrmXmlPersistenceUnitDefaults.getDefaultSchemaName()
);
} }
} }
@ -1015,29 +1002,25 @@ public class MetadataBuilderImpl implements MetadataBuilderImplementor, TypeCont
} }
private static WrapperArrayHandling resolveWrapperArrayHandling( private static WrapperArrayHandling resolveWrapperArrayHandling(
ConfigurationService configService, ConfigurationService configService) {
StandardServiceRegistry serviceRegistry) { return coalesceSuppliedValues(
final WrapperArrayHandling setting = NullnessHelper.coalesceSuppliedValues(
() -> configService.getSetting( () -> configService.getSetting(
WRAPPER_ARRAY_HANDLING, WRAPPER_ARRAY_HANDLING,
WrapperArrayHandling::interpretExternalSettingLeniently WrapperArrayHandling::interpretExternalSettingLeniently
), ),
() -> resolveFallbackWrapperArrayHandling( configService ) () -> resolveFallbackWrapperArrayHandling( configService )
); );
}
if ( setting == WrapperArrayHandling.PICK ) { private static WrapperArrayHandling pickWrapperArrayHandling(Dialect dialect) {
final Dialect dialect = serviceRegistry.requireService( JdbcServices.class ).getDialect(); if ( dialect.supportsStandardArrays()
if ( dialect.supportsStandardArrays() && ( dialect.getPreferredSqlTypeCodeForArray() == SqlTypes.ARRAY
&& ( dialect.getPreferredSqlTypeCodeForArray() == SqlTypes.ARRAY || dialect.getPreferredSqlTypeCodeForArray() == SqlTypes.SQLXML ) ) {
|| dialect.getPreferredSqlTypeCodeForArray() == SqlTypes.SQLXML ) ) { return WrapperArrayHandling.ALLOW;
return WrapperArrayHandling.ALLOW; }
} else {
else { return WrapperArrayHandling.LEGACY;
return WrapperArrayHandling.LEGACY;
}
} }
return setting;
} }
private static WrapperArrayHandling resolveFallbackWrapperArrayHandling( private static WrapperArrayHandling resolveFallbackWrapperArrayHandling(

View File

@ -1124,19 +1124,15 @@ public class XmlHelper {
} }
//noinspection unchecked //noinspection unchecked
final JavaType<Object> javaType = (JavaType<Object>) pluralJavaType; final JavaType<Object> javaType = (JavaType<Object>) pluralJavaType;
final LazySessionWrapperOptions lazySessionWrapperOptions = new LazySessionWrapperOptions( sessionFactory );
// Produce the XML string for a collection with a null element to find out the root and element tag names // Produce the XML string for a collection with a null element to find out the root and element tag names
final String nullElementXml; final String nullElementXml;
try { try ( final LazySessionWrapperOptions lazySessionWrapperOptions = new LazySessionWrapperOptions( sessionFactory ) ) {
nullElementXml = sessionFactory.getSessionFactoryOptions().getXmlFormatMapper().toString( nullElementXml = sessionFactory.getSessionFactoryOptions().getXmlFormatMapper().toString(
javaType.fromString( "{null}" ), javaType.fromString( "{null}" ),
javaType, javaType,
lazySessionWrapperOptions lazySessionWrapperOptions
); );
} }
finally {
lazySessionWrapperOptions.cleanup();
}
// There must be an end tag for the root, so find that first // There must be an end tag for the root, so find that first
final int rootCloseTagPosition = nullElementXml.lastIndexOf( '<' ); final int rootCloseTagPosition = nullElementXml.lastIndexOf( '<' );

View File

@ -312,6 +312,7 @@ public class OracleAggregateSupport extends AggregateSupportImpl {
return typeConfiguration.getSessionFactory().getWrapperOptions(); return typeConfiguration.getSessionFactory().getWrapperOptions();
} }
catch (HibernateException e) { catch (HibernateException e) {
// before we have a SessionFactory, no useful WrapperOptions to pass
return null; return null;
} }
} }
@ -549,16 +550,11 @@ public class OracleAggregateSupport extends AggregateSupportImpl {
final String columnDefinition = aggregateColumn.getColumnDefinition(); final String columnDefinition = aggregateColumn.getColumnDefinition();
if ( columnDefinition == null ) { if ( columnDefinition == null ) {
assert aggregateColumn.getJdbcMapping().getJdbcType().getDefaultSqlTypeCode() == JSON; assert aggregateColumn.getJdbcMapping().getJdbcType().getDefaultSqlTypeCode() == JSON;
switch ( jsonSupport ) { return switch ( jsonSupport ) {
case OSON: case OSON -> "json";
return "json"; case MERGEPATCH, QUERY_AND_PATH, QUERY -> "blob";
case MERGEPATCH: case NONE -> "clob";
case QUERY_AND_PATH: };
case QUERY:
return "blob";
case NONE:
return "clob";
}
} }
return columnDefinition; return columnDefinition;
} }

View File

@ -485,8 +485,7 @@ public abstract class NumberSeriesGenerateSeriesFunction extends GenerateSeriesF
private String getExpression(Expression expression, String tableIdentifierVariable, String syntheticColumnName, SqmToSqlAstConverter walker) { private String getExpression(Expression expression, String tableIdentifierVariable, String syntheticColumnName, SqmToSqlAstConverter walker) {
if ( expression instanceof Literal literal ) { if ( expression instanceof Literal literal ) {
final SessionFactoryImplementor sessionFactory = walker.getCreationContext().getSessionFactory(); final SessionFactoryImplementor sessionFactory = walker.getCreationContext().getSessionFactory();
final LazySessionWrapperOptions wrapperOptions = new LazySessionWrapperOptions( sessionFactory ); try ( final LazySessionWrapperOptions wrapperOptions = new LazySessionWrapperOptions( sessionFactory ) ) {
try {
//noinspection unchecked //noinspection unchecked
return literal.getJdbcMapping().getJdbcLiteralFormatter().toJdbcLiteral( return literal.getJdbcMapping().getJdbcLiteralFormatter().toJdbcLiteral(
literal.getLiteralValue(), literal.getLiteralValue(),
@ -494,9 +493,6 @@ public abstract class NumberSeriesGenerateSeriesFunction extends GenerateSeriesF
wrapperOptions wrapperOptions
); );
} }
finally {
wrapperOptions.cleanup();
}
} }
else if ( expression instanceof ColumnReference columnReference ) { else if ( expression instanceof ColumnReference columnReference ) {
return columnReference.getExpressionText(); return columnReference.getExpressionText();

View File

@ -12,7 +12,11 @@ import org.hibernate.type.descriptor.WrapperOptions;
/** /**
* @author Christian Beikov * @author Christian Beikov
* @author Andrea Boriero * @author Andrea Boriero
*
* @deprecated This isn't bringing any value, since {@link SessionImplementor}
* already extends {@link WrapperOptions}.
*/ */
@Deprecated(since = "7", forRemoval = true)
public abstract class AbstractDelegatingWrapperOptions implements WrapperOptions { public abstract class AbstractDelegatingWrapperOptions implements WrapperOptions {
/** /**

View File

@ -7,23 +7,37 @@ package org.hibernate.engine.spi;
import java.util.TimeZone; import java.util.TimeZone;
import org.hibernate.Internal; import org.hibernate.Internal;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.jdbc.LobCreator;
import org.hibernate.internal.FastSessionServices;
import org.hibernate.type.descriptor.WrapperOptions; import org.hibernate.type.descriptor.WrapperOptions;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
/** /**
* A lazy session implementation that is needed for rendering literals. * An implementation of {@link WrapperOptions} used for rendering SQL literals,
* Usually, only the {@link WrapperOptions} interface is needed, * which is backed by the {@link SessionFactoryImplementor}, and which
* but for creating LOBs, it might be to have a full-blown session. * {@linkplain SessionFactoryImplementor#openTemporarySession lazily creates a
* temporary session if needed.} The temporary session will only be created when
* dealing with LOBs.
* <p>
* This object is {@link AutoCloseable}, and <em>must</em> be explicitly cleaned
* up by its creator.
*
* @apiNote This thing is nasty, and we should find a better way to solve the problem.
* Whenever possible, just use {@link SessionFactoryImplementor#getWrapperOptions()}
* instead.
*/ */
@Internal @Internal
public class LazySessionWrapperOptions extends AbstractDelegatingWrapperOptions { public class LazySessionWrapperOptions implements WrapperOptions, AutoCloseable {
private final SessionFactoryImplementor sessionFactory; private final SessionFactoryImplementor sessionFactory;
private final FastSessionServices fastSessionServices;
private @Nullable SessionImplementor session; private @Nullable SessionImplementor session;
public LazySessionWrapperOptions(SessionFactoryImplementor sessionFactory) { public LazySessionWrapperOptions(SessionFactoryImplementor sessionFactory) {
this.sessionFactory = sessionFactory; this.sessionFactory = sessionFactory;
fastSessionServices = sessionFactory.getFastSessionServices();
} }
public void cleanup() { public void cleanup() {
@ -34,16 +48,14 @@ public class LazySessionWrapperOptions extends AbstractDelegatingWrapperOptions
} }
@Override @Override
protected SessionImplementor delegate() { public void close() {
if ( session == null ) { cleanup();
session = sessionFactory.openTemporarySession();
}
return session;
} }
@Override @Override
public SharedSessionContractImplementor getSession() { public SharedSessionContractImplementor getSession() {
return delegate(); session = sessionFactory.openTemporarySession();
return session;
} }
@Override @Override
@ -53,16 +65,26 @@ public class LazySessionWrapperOptions extends AbstractDelegatingWrapperOptions
@Override @Override
public boolean useStreamForLobBinding() { public boolean useStreamForLobBinding() {
return sessionFactory.getFastSessionServices().useStreamForLobBinding(); return fastSessionServices.useStreamForLobBinding;
} }
@Override @Override
public int getPreferredSqlTypeCodeForBoolean() { public int getPreferredSqlTypeCodeForBoolean() {
return sessionFactory.getFastSessionServices().getPreferredSqlTypeCodeForBoolean(); return fastSessionServices.preferredSqlTypeCodeForBoolean;
} }
@Override @Override
public TimeZone getJdbcTimeZone() { public TimeZone getJdbcTimeZone() {
return sessionFactory.getSessionFactoryOptions().getJdbcTimeZone(); return fastSessionServices.jdbcTimeZone;
}
@Override
public Dialect getDialect() {
return fastSessionServices.dialect;
}
@Override
public LobCreator getLobCreator() {
return fastSessionServices.jdbcServices.getLobCreator( getSession() );
} }
} }

View File

@ -7,7 +7,6 @@ package org.hibernate.engine.spi;
import java.util.Collection; import java.util.Collection;
import org.hibernate.CustomEntityDirtinessStrategy; import org.hibernate.CustomEntityDirtinessStrategy;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
import org.hibernate.SessionFactoryObserver; import org.hibernate.SessionFactoryObserver;
import org.hibernate.boot.model.relational.SqlStringGenerationContext; import org.hibernate.boot.model.relational.SqlStringGenerationContext;
@ -94,7 +93,7 @@ public interface SessionFactoryImplementor
/** /**
* Get a non-transactional "current" session (used by hibernate-envers) * Get a non-transactional "current" session (used by hibernate-envers)
*/ */
SessionImplementor openTemporarySession() throws HibernateException; SessionImplementor openTemporarySession();
@Override @Override
CacheImplementor getCache(); CacheImplementor getCache();

View File

@ -34,6 +34,7 @@ import org.hibernate.UnknownEntityTypeException;
import org.hibernate.binder.internal.TenantIdBinder; import org.hibernate.binder.internal.TenantIdBinder;
import org.hibernate.cache.spi.CacheTransactionSynchronization; import org.hibernate.cache.spi.CacheTransactionSynchronization;
import org.hibernate.context.spi.CurrentTenantIdentifierResolver; import org.hibernate.context.spi.CurrentTenantIdentifierResolver;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.internal.SessionEventListenerManagerImpl; import org.hibernate.engine.internal.SessionEventListenerManagerImpl;
import org.hibernate.engine.jdbc.LobCreator; import org.hibernate.engine.jdbc.LobCreator;
import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess; import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess;
@ -702,6 +703,11 @@ public abstract class AbstractSharedSessionContract implements SharedSessionCont
return new EntityKey( id, persister ); return new EntityKey( id, persister );
} }
@Override
public SessionFactoryImplementor getSessionFactory() {
return factory;
}
@Override @Override
public boolean useStreamForLobBinding() { public boolean useStreamForLobBinding() {
return fastSessionServices.useStreamForLobBinding; return fastSessionServices.useStreamForLobBinding;
@ -714,7 +720,12 @@ public abstract class AbstractSharedSessionContract implements SharedSessionCont
@Override @Override
public LobCreator getLobCreator() { public LobCreator getLobCreator() {
return getFactory().getFastSessionServices().jdbcServices.getLobCreator( this ); return fastSessionServices.jdbcServices.getLobCreator( this );
}
@Override
public Dialect getDialect() {
return fastSessionServices.dialect;
} }
@Override @Override
@ -1417,7 +1428,7 @@ public abstract class AbstractSharedSessionContract implements SharedSessionCont
@Override @Override
public EventManager getEventManager() { public EventManager getEventManager() {
return fastSessionServices.getEventManager(); return fastSessionServices.eventManager;
} }
@Override @Override

View File

@ -8,59 +8,24 @@ import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.TimeZone;
import org.hibernate.CacheMode; import org.hibernate.CacheMode;
import org.hibernate.FlushMode; import org.hibernate.FlushMode;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.LockOptions; import org.hibernate.LockOptions;
import org.hibernate.TimeZoneStorageStrategy;
import org.hibernate.boot.registry.classloading.spi.ClassLoaderService; import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
import org.hibernate.boot.spi.SessionFactoryOptions; import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.dialect.Dialect; import org.hibernate.dialect.Dialect;
import org.hibernate.engine.jdbc.batch.spi.BatchBuilder; import org.hibernate.engine.jdbc.batch.spi.BatchBuilder;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider; import org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider;
import org.hibernate.engine.jdbc.mutation.spi.MutationExecutorService;
import org.hibernate.engine.jdbc.spi.JdbcServices; import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.event.internal.EmptyEventManager; import org.hibernate.event.internal.EmptyEventManager;
import org.hibernate.event.service.spi.EventListenerGroup; import org.hibernate.event.service.spi.EventListenerGroup;
import org.hibernate.event.service.spi.EventListenerRegistry; import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.AutoFlushEventListener; import org.hibernate.event.spi.*;
import org.hibernate.event.spi.ClearEventListener;
import org.hibernate.event.spi.DeleteEventListener;
import org.hibernate.event.spi.DirtyCheckEventListener;
import org.hibernate.event.spi.EntityCopyObserverFactory;
import org.hibernate.event.spi.EventManager;
import org.hibernate.event.spi.EventType;
import org.hibernate.event.spi.EvictEventListener;
import org.hibernate.event.spi.FlushEntityEventListener;
import org.hibernate.event.spi.FlushEventListener;
import org.hibernate.event.spi.InitializeCollectionEventListener;
import org.hibernate.event.spi.LoadEventListener;
import org.hibernate.event.spi.LockEventListener;
import org.hibernate.event.spi.MergeEventListener;
import org.hibernate.event.spi.PersistEventListener;
import org.hibernate.event.spi.PostCollectionRecreateEventListener;
import org.hibernate.event.spi.PostCollectionRemoveEventListener;
import org.hibernate.event.spi.PostCollectionUpdateEventListener;
import org.hibernate.event.spi.PostDeleteEventListener;
import org.hibernate.event.spi.PostInsertEventListener;
import org.hibernate.event.spi.PostLoadEvent;
import org.hibernate.event.spi.PostLoadEventListener;
import org.hibernate.event.spi.PostUpdateEventListener;
import org.hibernate.event.spi.PostUpsertEventListener;
import org.hibernate.event.spi.PreCollectionRecreateEventListener;
import org.hibernate.event.spi.PreCollectionRemoveEventListener;
import org.hibernate.event.spi.PreCollectionUpdateEventListener;
import org.hibernate.event.spi.PreDeleteEventListener;
import org.hibernate.event.spi.PreInsertEventListener;
import org.hibernate.event.spi.PreLoadEventListener;
import org.hibernate.event.spi.PreUpdateEventListener;
import org.hibernate.event.spi.PreUpsertEventListener;
import org.hibernate.event.spi.RefreshEventListener;
import org.hibernate.event.spi.ReplicateEventListener;
import org.hibernate.event.spi.ResolveNaturalIdEventListener;
import org.hibernate.jpa.HibernateHints; import org.hibernate.jpa.HibernateHints;
import org.hibernate.jpa.LegacySpecHints; import org.hibernate.jpa.LegacySpecHints;
import org.hibernate.jpa.SpecHints; import org.hibernate.jpa.SpecHints;
@ -152,17 +117,14 @@ public final class FastSessionServices {
public final EventListenerGroup<ReplicateEventListener> eventListenerGroup_REPLICATE; public final EventListenerGroup<ReplicateEventListener> eventListenerGroup_REPLICATE;
public final EventListenerGroup<ResolveNaturalIdEventListener> eventListenerGroup_RESOLVE_NATURAL_ID; public final EventListenerGroup<ResolveNaturalIdEventListener> eventListenerGroup_RESOLVE_NATURAL_ID;
//Intentionally Package private: // Fields used only from within this package
final boolean disallowOutOfTransactionUpdateOperations; final boolean disallowOutOfTransactionUpdateOperations;
final boolean useStreamForLobBinding;
final int preferredSqlTypeCodeForBoolean;
final TimeZoneStorageStrategy defaultTimeZoneStorageStrategy;
final boolean requiresMultiTenantConnectionProvider; final boolean requiresMultiTenantConnectionProvider;
final ConnectionProvider connectionProvider; final ConnectionProvider connectionProvider;
final MultiTenantConnectionProvider<Object> multiTenantConnectionProvider; final MultiTenantConnectionProvider<Object> multiTenantConnectionProvider;
final ClassLoaderService classLoaderService; final ClassLoaderService classLoaderService;
final TransactionCoordinatorBuilder transactionCoordinatorBuilder; final TransactionCoordinatorBuilder transactionCoordinatorBuilder;
public final JdbcServices jdbcServices; final EventManager eventManager;
final boolean isJtaTransactionAccessible; final boolean isJtaTransactionAccessible;
final CacheMode initialSessionCacheMode; final CacheMode initialSessionCacheMode;
final FlushMode initialSessionFlushMode; final FlushMode initialSessionFlushMode;
@ -171,20 +133,23 @@ public final class FastSessionServices {
final LockOptions defaultLockOptions; final LockOptions defaultLockOptions;
final int defaultJdbcBatchSize; final int defaultJdbcBatchSize;
//Some fields are handy as public - still considered internal. // Expose certain fields outside this package
// (but they are still considered internal)
public final Dialect dialect;
public final JdbcServices jdbcServices;
public final boolean useStreamForLobBinding;
public final int preferredSqlTypeCodeForBoolean;
public final TimeZone jdbcTimeZone;
public final EntityCopyObserverFactory entityCopyObserverFactory; public final EntityCopyObserverFactory entityCopyObserverFactory;
public final BatchBuilder batchBuilder; public final BatchBuilder batchBuilder;
public final Dialect dialect;
public final ParameterMarkerStrategy parameterMarkerStrategy; public final ParameterMarkerStrategy parameterMarkerStrategy;
//Private fields: // Private fields (probably don't really belong here)
private final CacheStoreMode defaultCacheStoreMode; private final CacheStoreMode defaultCacheStoreMode;
private final CacheRetrieveMode defaultCacheRetrieveMode; private final CacheRetrieveMode defaultCacheRetrieveMode;
private final FormatMapper jsonFormatMapper; private final FormatMapper jsonFormatMapper;
private final FormatMapper xmlFormatMapper; private final FormatMapper xmlFormatMapper;
private final MutationExecutorService mutationExecutorService;
private final JdbcValuesMappingProducerProvider jdbcValuesMappingProducerProvider; private final JdbcValuesMappingProducerProvider jdbcValuesMappingProducerProvider;
private final EventManager eventManager;
FastSessionServices(SessionFactoryImplementor sessionFactory) { FastSessionServices(SessionFactoryImplementor sessionFactory) {
Objects.requireNonNull( sessionFactory ); Objects.requireNonNull( sessionFactory );
@ -235,11 +200,10 @@ public final class FastSessionServices {
this.disallowOutOfTransactionUpdateOperations = !sessionFactoryOptions.isAllowOutOfTransactionUpdateOperations(); this.disallowOutOfTransactionUpdateOperations = !sessionFactoryOptions.isAllowOutOfTransactionUpdateOperations();
this.useStreamForLobBinding = dialect.useInputStreamToInsertBlob(); this.useStreamForLobBinding = dialect.useInputStreamToInsertBlob();
this.preferredSqlTypeCodeForBoolean = sessionFactoryOptions.getPreferredSqlTypeCodeForBoolean(); this.preferredSqlTypeCodeForBoolean = sessionFactoryOptions.getPreferredSqlTypeCodeForBoolean();
this.defaultTimeZoneStorageStrategy = sessionFactoryOptions.getDefaultTimeZoneStorageStrategy();
this.defaultJdbcBatchSize = sessionFactoryOptions.getJdbcBatchSize(); this.defaultJdbcBatchSize = sessionFactoryOptions.getJdbcBatchSize();
this.jdbcTimeZone = sessionFactoryOptions.getJdbcTimeZone();
this.requiresMultiTenantConnectionProvider = sessionFactory.getSessionFactoryOptions().isMultiTenancyEnabled(); this.requiresMultiTenantConnectionProvider = sessionFactory.getSessionFactoryOptions().isMultiTenancyEnabled();
this.parameterMarkerStrategy = serviceRegistry.getService( ParameterMarkerStrategy.class ); this.parameterMarkerStrategy = serviceRegistry.getService( ParameterMarkerStrategy.class );
this.mutationExecutorService = serviceRegistry.getService( MutationExecutorService.class );
//Some "hot" services: //Some "hot" services:
this.connectionProvider = requiresMultiTenantConnectionProvider this.connectionProvider = requiresMultiTenantConnectionProvider
@ -254,7 +218,6 @@ public final class FastSessionServices {
this.entityCopyObserverFactory = serviceRegistry.requireService( EntityCopyObserverFactory.class ); this.entityCopyObserverFactory = serviceRegistry.requireService( EntityCopyObserverFactory.class );
this.jdbcValuesMappingProducerProvider = serviceRegistry.getService( JdbcValuesMappingProducerProvider.class ); this.jdbcValuesMappingProducerProvider = serviceRegistry.getService( JdbcValuesMappingProducerProvider.class );
this.isJtaTransactionAccessible = isTransactionAccessible( sessionFactory, transactionCoordinatorBuilder ); this.isJtaTransactionAccessible = isTransactionAccessible( sessionFactory, transactionCoordinatorBuilder );
this.defaultSessionProperties = initializeDefaultSessionProperties( sessionFactory ); this.defaultSessionProperties = initializeDefaultSessionProperties( sessionFactory );
@ -268,10 +231,9 @@ public final class FastSessionServices {
this.jsonFormatMapper = sessionFactoryOptions.getJsonFormatMapper(); this.jsonFormatMapper = sessionFactoryOptions.getJsonFormatMapper();
this.xmlFormatMapper = sessionFactoryOptions.getXmlFormatMapper(); this.xmlFormatMapper = sessionFactoryOptions.getXmlFormatMapper();
this.batchBuilder = serviceRegistry.getService( BatchBuilder.class ); this.batchBuilder = serviceRegistry.getService( BatchBuilder.class );
final Collection<EventManager> eventManagers = classLoaderService.loadJavaServices( EventManager.class ); final Collection<EventManager> eventManagers = classLoaderService.loadJavaServices( EventManager.class );
this.eventManager = eventManagers.isEmpty() this.eventManager = eventManagers.isEmpty() ? new EmptyEventManager() : eventManagers.iterator().next();
? new EmptyEventManager()
: eventManagers.iterator().next();
} }
private static FlushMode initializeDefaultFlushMode(Map<String, Object> defaultSessionProperties) { private static FlushMode initializeDefaultFlushMode(Map<String, Object> defaultSessionProperties) {
@ -374,27 +336,10 @@ public final class FastSessionServices {
return this.jdbcValuesMappingProducerProvider; return this.jdbcValuesMappingProducerProvider;
} }
public EventManager getEventManager() {
return eventManager;
}
public boolean useStreamForLobBinding() {
return useStreamForLobBinding;
}
public void firePostLoadEvent(final PostLoadEvent postLoadEvent) { public void firePostLoadEvent(final PostLoadEvent postLoadEvent) {
eventListenerGroup_POST_LOAD.fireEventOnEachListener( postLoadEvent, PostLoadEventListener::onPostLoad ); eventListenerGroup_POST_LOAD.fireEventOnEachListener( postLoadEvent, PostLoadEventListener::onPostLoad );
} }
public int getPreferredSqlTypeCodeForBoolean() {
return preferredSqlTypeCodeForBoolean;
}
@Deprecated(forRemoval = true) //This seems no longer used - cleanup?
public TimeZoneStorageStrategy getDefaultTimeZoneStorageStrategy() {
return defaultTimeZoneStorageStrategy;
}
public FormatMapper getJsonFormatMapper() { public FormatMapper getJsonFormatMapper() {
if ( jsonFormatMapper == null ) { if ( jsonFormatMapper == null ) {
throw new HibernateException( throw new HibernateException(
@ -412,10 +357,4 @@ public final class FastSessionServices {
} }
return xmlFormatMapper; return xmlFormatMapper;
} }
@Deprecated(forRemoval = true) //This seems no longer used - cleanup?
public MutationExecutorService getMutationExecutorService() {
return mutationExecutorService;
}
} }

View File

@ -2,11 +2,11 @@
* SPDX-License-Identifier: LGPL-2.1-or-later * SPDX-License-Identifier: LGPL-2.1-or-later
* Copyright Red Hat Inc. and Hibernate Authors * Copyright Red Hat Inc. and Hibernate Authors
*/ */
package org.hibernate.persister.entity; package org.hibernate.internal;
import java.util.TimeZone; import java.util.TimeZone;
import org.hibernate.Internal; import org.hibernate.dialect.Dialect;
import org.hibernate.engine.jdbc.LobCreator; import org.hibernate.engine.jdbc.LobCreator;
import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
@ -16,13 +16,14 @@ import org.hibernate.type.descriptor.WrapperOptions;
* *
* @author Christian Beikov * @author Christian Beikov
*/ */
@Internal class SessionFactoryBasedWrapperOptions implements WrapperOptions {
public class SessionFactoryBasedWrapperOptions implements WrapperOptions {
private final SessionFactoryImplementor factory; private final SessionFactoryImplementor factory;
private final FastSessionServices fastSessionServices;
public SessionFactoryBasedWrapperOptions(SessionFactoryImplementor factory) { SessionFactoryBasedWrapperOptions(SessionFactoryImplementor factory) {
this.factory = factory; this.factory = factory;
fastSessionServices = factory.getFastSessionServices();
} }
@Override @Override
@ -37,21 +38,26 @@ public class SessionFactoryBasedWrapperOptions implements WrapperOptions {
@Override @Override
public boolean useStreamForLobBinding() { public boolean useStreamForLobBinding() {
return factory.getFastSessionServices().useStreamForLobBinding(); return fastSessionServices.useStreamForLobBinding;
} }
@Override @Override
public int getPreferredSqlTypeCodeForBoolean() { public int getPreferredSqlTypeCodeForBoolean() {
return factory.getFastSessionServices().getPreferredSqlTypeCodeForBoolean(); return fastSessionServices.preferredSqlTypeCodeForBoolean;
} }
@Override @Override
public LobCreator getLobCreator() { public LobCreator getLobCreator() {
return factory.getJdbcServices().getLobCreator( getSession() ); return fastSessionServices.jdbcServices.getLobCreator( getSession() );
} }
@Override @Override
public TimeZone getJdbcTimeZone() { public TimeZone getJdbcTimeZone() {
return factory.getSessionFactoryOptions().getJdbcTimeZone(); return fastSessionServices.jdbcTimeZone;
}
@Override
public Dialect getDialect() {
return fastSessionServices.dialect;
} }
} }

View File

@ -83,7 +83,6 @@ import org.hibernate.metamodel.model.domain.spi.JpaMetamodelImplementor;
import org.hibernate.metamodel.spi.MappingMetamodelImplementor; import org.hibernate.metamodel.spi.MappingMetamodelImplementor;
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.SessionFactoryBasedWrapperOptions;
import org.hibernate.procedure.spi.ProcedureCallImplementor; import org.hibernate.procedure.spi.ProcedureCallImplementor;
import org.hibernate.proxy.EntityNotFoundDelegate; import org.hibernate.proxy.EntityNotFoundDelegate;
import org.hibernate.proxy.LazyInitializer; import org.hibernate.proxy.LazyInitializer;

View File

@ -1646,12 +1646,6 @@ public class SessionImpl
return super.createStoredProcedureCall( procedureName, resultClasses ); return super.createStoredProcedureCall( procedureName, resultClasses );
} }
@Override
public SessionFactoryImplementor getSessionFactory() {
// checkTransactionSynchStatus();
return getFactory();
}
@Override @Override
public <T> QueryImplementor<T> createQuery(CriteriaSelect<T> selectQuery) { public <T> QueryImplementor<T> createQuery(CriteriaSelect<T> selectQuery) {
checkOpen(); checkOpen();

View File

@ -47,7 +47,9 @@ public interface WrapperOptions {
* *
* @see org.hibernate.dialect.Dialect#useInputStreamToInsertBlob() * @see org.hibernate.dialect.Dialect#useInputStreamToInsertBlob()
*/ */
boolean useStreamForLobBinding(); default boolean useStreamForLobBinding() {
return getDialect().useInputStreamToInsertBlob();
}
/** /**
* The JDBC {@link java.sql.Types type code} used to bind a null boolean value. * The JDBC {@link java.sql.Types type code} used to bind a null boolean value.
@ -55,7 +57,9 @@ public interface WrapperOptions {
* @see org.hibernate.cfg.AvailableSettings#PREFERRED_BOOLEAN_JDBC_TYPE * @see org.hibernate.cfg.AvailableSettings#PREFERRED_BOOLEAN_JDBC_TYPE
* @see org.hibernate.dialect.Dialect#getPreferredSqlTypeCodeForBoolean() * @see org.hibernate.dialect.Dialect#getPreferredSqlTypeCodeForBoolean()
*/ */
int getPreferredSqlTypeCodeForBoolean(); default int getPreferredSqlTypeCodeForBoolean() {
return getSessionFactory().getSessionFactoryOptions().getPreferredSqlTypeCodeForBoolean();
}
/** /**
* Obtain access to the {@link LobCreator}. * Obtain access to the {@link LobCreator}.
@ -65,7 +69,9 @@ public interface WrapperOptions {
* @see org.hibernate.cfg.AvailableSettings#NON_CONTEXTUAL_LOB_CREATION * @see org.hibernate.cfg.AvailableSettings#NON_CONTEXTUAL_LOB_CREATION
* @see org.hibernate.dialect.Dialect#getDefaultNonContextualLobCreation() * @see org.hibernate.dialect.Dialect#getDefaultNonContextualLobCreation()
*/ */
LobCreator getLobCreator(); default LobCreator getLobCreator() {
return getSession().getLobCreator();
}
/** /**
* The JDBC {@link TimeZone} used when writing a value of type {@link java.sql.Time} * The JDBC {@link TimeZone} used when writing a value of type {@link java.sql.Time}
@ -90,5 +96,7 @@ public interface WrapperOptions {
* *
* @see org.hibernate.cfg.AvailableSettings#JDBC_TIME_ZONE * @see org.hibernate.cfg.AvailableSettings#JDBC_TIME_ZONE
*/ */
TimeZone getJdbcTimeZone(); default TimeZone getJdbcTimeZone() {
return getSessionFactory().getSessionFactoryOptions().getJdbcTimeZone();
}
} }

View File

@ -26,19 +26,17 @@ public abstract class BasicJdbcLiteralFormatter<T> extends AbstractJdbcLiteralFo
if ( unwrapType.isInstance( value ) ) { if ( unwrapType.isInstance( value ) ) {
return (X) value; return (X) value;
} }
else if ( !getJavaType().isInstance( value ) ) {
if ( !getJavaType().isInstance( value ) ) {
final T coerce = getJavaType().coerce( value, wrapperOptions.getSession() ); final T coerce = getJavaType().coerce( value, wrapperOptions.getSession() );
if ( unwrapType.isInstance( coerce ) ) { if ( unwrapType.isInstance( coerce ) ) {
return (X) coerce; return (X) coerce;
} }
return getJavaType().unwrap( else {
coerce, return getJavaType().unwrap( coerce, unwrapType, wrapperOptions );
unwrapType, }
wrapperOptions }
); else {
return getJavaType().unwrap( (T) value, unwrapType, wrapperOptions );
} }
return getJavaType().unwrap( (T) value, unwrapType, wrapperOptions );
} }
} }