simplify Generator instantiation lifecycle

remove a bunch of unused parameters from methods in this package
This commit is contained in:
Gavin King 2024-09-19 10:47:34 +02:00
parent df16ea9694
commit 8ee09481b3
19 changed files with 317 additions and 337 deletions

View File

@ -54,7 +54,6 @@
import org.hibernate.boot.model.naming.Identifier; import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.relational.AuxiliaryDatabaseObject; import org.hibernate.boot.model.relational.AuxiliaryDatabaseObject;
import org.hibernate.boot.model.relational.Database; import org.hibernate.boot.model.relational.Database;
import org.hibernate.boot.model.relational.ExportableProducer;
import org.hibernate.boot.model.relational.Namespace; import org.hibernate.boot.model.relational.Namespace;
import org.hibernate.boot.model.relational.QualifiedTableName; import org.hibernate.boot.model.relational.QualifiedTableName;
import org.hibernate.boot.model.source.internal.ImplicitColumnNamingSecondPass; import org.hibernate.boot.model.source.internal.ImplicitColumnNamingSecondPass;
@ -81,7 +80,6 @@
import org.hibernate.dialect.Dialect; import org.hibernate.dialect.Dialect;
import org.hibernate.engine.spi.FilterDefinition; import org.hibernate.engine.spi.FilterDefinition;
import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.generator.Generator;
import org.hibernate.internal.CoreLogging; import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.collections.CollectionHelper; import org.hibernate.internal.util.collections.CollectionHelper;
@ -91,6 +89,7 @@
import org.hibernate.mapping.DenormalizedTable; import org.hibernate.mapping.DenormalizedTable;
import org.hibernate.mapping.FetchProfile; import org.hibernate.mapping.FetchProfile;
import org.hibernate.mapping.ForeignKey; import org.hibernate.mapping.ForeignKey;
import org.hibernate.mapping.GeneratorSettings;
import org.hibernate.mapping.IdentifierCollection; import org.hibernate.mapping.IdentifierCollection;
import org.hibernate.mapping.Join; import org.hibernate.mapping.Join;
import org.hibernate.mapping.KeyValue; import org.hibernate.mapping.KeyValue;
@ -2204,15 +2203,22 @@ private void processExportableProducers() {
private void handleIdentifierValueBinding( private void handleIdentifierValueBinding(
KeyValue identifierValueBinding, Dialect dialect, RootClass entityBinding, Property identifierProperty) { KeyValue identifierValueBinding, Dialect dialect, RootClass entityBinding, Property identifierProperty) {
// todo : store this result (back into the entity or into the KeyValue, maybe?)
// This process of instantiating the id-generator is called multiple times.
// It was done this way in the old code too, so no "regression" here; but
// it could be done better
try { try {
final Generator generator = identifierValueBinding.createGenerator( dialect, entityBinding, identifierProperty ); // this call typically caches the new Generator in the instance of KeyValue
if ( generator instanceof ExportableProducer exportableProducer ) { identifierValueBinding.createGenerator( dialect, entityBinding, identifierProperty,
exportableProducer.registerExportables( getDatabase() ); new GeneratorSettings() {
@Override
public String getDefaultCatalog() {
//TODO: does not have access to property-configured default
return persistenceUnitMetadata.getDefaultCatalog();
} }
@Override
public String getDefaultSchema() {
//TODO: does not have access to property-configured default
return persistenceUnitMetadata.getDefaultSchema();
}
} );
} }
catch (MappingException e) { catch (MappingException e) {
// ignore this for now. The reasoning being "non-reflective" binding as needed // ignore this for now. The reasoning being "non-reflective" binding as needed

View File

@ -94,7 +94,8 @@ public static <A extends Annotation> A findLocalizedMatch(
// lastly, on the package // lastly, on the package
final String packageInfoFqn = StringHelper.qualifier( idMember.getDeclaringType().getClassName() ) + ".package-info"; final String packageInfoFqn = StringHelper.qualifier( idMember.getDeclaringType().getClassName() ) + ".package-info";
try { try {
final ClassDetails packageInfo = context.getMetadataCollector() final ClassDetails packageInfo =
context.getMetadataCollector()
.getSourceModelBuildingContext() .getSourceModelBuildingContext()
.getClassDetailsRegistry() .getClassDetailsRegistry()
.resolveClassDetails( packageInfoFqn ); .resolveClassDetails( packageInfoFqn );
@ -138,10 +139,7 @@ public static void handleUuidStrategy(
idValue.setCustomIdGeneratorCreator( (creationContext) -> new UuidGenerator( generatorConfig, idMember ) ); idValue.setCustomIdGeneratorCreator( (creationContext) -> new UuidGenerator( generatorConfig, idMember ) );
} }
public static void handleIdentityStrategy( public static void handleIdentityStrategy(SimpleValue idValue) {
SimpleValue idValue,
MemberDetails idMember,
MetadataBuildingContext context) {
idValue.setCustomIdGeneratorCreator( (creationContext) -> new IdentityGenerator() ); idValue.setCustomIdGeneratorCreator( (creationContext) -> new IdentityGenerator() );
idValue.setColumnToIdentity(); idValue.setColumnToIdentity();
} }
@ -189,7 +187,6 @@ public static void handleGenericGenerator(
GenericGenerator generatorConfig, GenericGenerator generatorConfig,
PersistentClass entityMapping, PersistentClass entityMapping,
SimpleValue idValue, SimpleValue idValue,
MemberDetails idMember,
MetadataBuildingContext context) { MetadataBuildingContext context) {
//generator settings //generator settings
final Map<String,String> configuration = new HashMap<>(); final Map<String,String> configuration = new HashMap<>();
@ -206,9 +203,7 @@ public static void handleGenericGenerator(
GeneratorBinder.createGeneratorFrom( GeneratorBinder.createGeneratorFrom(
new IdentifierGeneratorDefinition( generatorName, determineStrategyName( generatorConfig ), configuration ), new IdentifierGeneratorDefinition( generatorName, determineStrategyName( generatorConfig ), configuration ),
idMember,
idValue, idValue,
entityMapping,
context context
); );
} }
@ -232,17 +227,14 @@ public static void handleTableGenerator(
TableGenerator generatorConfig, TableGenerator generatorConfig,
PersistentClass entityMapping, PersistentClass entityMapping,
SimpleValue idValue, SimpleValue idValue,
MemberDetails idMember,
MetadataBuildingContext context) { MetadataBuildingContext context) {
final Map<String,String> configuration = new HashMap<>(); final Map<String,String> configuration = new HashMap<>();
applyBaselineConfiguration( generatorConfig, idValue, entityMapping.getRootClass(), context, configuration::put ); applyBaselineConfiguration( generatorConfig, idValue, entityMapping.getRootClass(), context, configuration::put );
org.hibernate.id.enhanced.TableGenerator.applyConfiguration( generatorConfig, idValue, configuration::put ); org.hibernate.id.enhanced.TableGenerator.applyConfiguration( generatorConfig, configuration::put );
GeneratorBinder.createGeneratorFrom( GeneratorBinder.createGeneratorFrom(
new IdentifierGeneratorDefinition( generatorName, org.hibernate.id.enhanced.TableGenerator.class.getName(), configuration ), new IdentifierGeneratorDefinition( generatorName, org.hibernate.id.enhanced.TableGenerator.class.getName(), configuration ),
idMember,
idValue, idValue,
entityMapping,
context context
); );

View File

@ -7,7 +7,6 @@
import java.lang.annotation.Annotation; import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member; import java.lang.reflect.Member;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
@ -46,6 +45,7 @@
import org.hibernate.internal.util.StringHelper; import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.collections.CollectionHelper; import org.hibernate.internal.util.collections.CollectionHelper;
import org.hibernate.mapping.GeneratorCreator; import org.hibernate.mapping.GeneratorCreator;
import org.hibernate.mapping.KeyValue;
import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.SimpleValue; import org.hibernate.mapping.SimpleValue;
import org.hibernate.models.spi.AnnotationTarget; import org.hibernate.models.spi.AnnotationTarget;
@ -283,22 +283,6 @@ private static GenerationType interpretGenerationType(GeneratedValue generatedVa
return strategy == null ? AUTO : strategy; return strategy == null ? AUTO : strategy;
} }
/**
* Collects definition objects for all generators defined using any of {@link TableGenerator},
* {@link SequenceGenerator}, and {@link GenericGenerator} on the given annotated element.
*/
public static List<IdentifierGeneratorDefinition> collectIdGeneratorDefinitions(
AnnotationTarget annotatedElement,
MetadataBuildingContext context) {
final ArrayList<IdentifierGeneratorDefinition> definitions = new ArrayList<>();
visitIdGeneratorDefinitions(
annotatedElement,
definitions::add,
context
);
return definitions;
}
public static void visitIdGeneratorDefinitions( public static void visitIdGeneratorDefinitions(
AnnotationTarget annotatedElement, AnnotationTarget annotatedElement,
Consumer<IdentifierGeneratorDefinition> consumer, Consumer<IdentifierGeneratorDefinition> consumer,
@ -693,7 +677,7 @@ public static void callConfigure(
Generator generator, Generator generator,
Map<String, Object> configuration, Map<String, Object> configuration,
SimpleValue identifierValue) { SimpleValue identifierValue) {
if ( generator instanceof final Configurable configurable ) { if ( generator instanceof Configurable configurable ) {
final Properties parameters = collectParameters( final Properties parameters = collectParameters(
identifierValue, identifierValue,
creationContext.getDatabase().getDialect(), creationContext.getDatabase().getDialect(),
@ -702,6 +686,12 @@ public static void callConfigure(
); );
configurable.configure( creationContext, parameters ); configurable.configure( creationContext, parameters );
} }
if ( generator instanceof ExportableProducer exportableProducer ) {
exportableProducer.registerExportables( creationContext.getDatabase() );
}
if ( generator instanceof Configurable configurable ) {
configurable.initialize( creationContext.getSqlStringGenerationContext() );
}
} }
private static void checkIdGeneratorTiming(Class<? extends Annotation> annotationType, Generator generator) { private static void checkIdGeneratorTiming(Class<? extends Annotation> annotationType, Generator generator) {
@ -726,11 +716,12 @@ private static void createIdGenerator(
// NOTE: `generatedValue` is never null here // NOTE: `generatedValue` is never null here
final GeneratedValue generatedValue = castNonNull( idMember.getDirectAnnotationUsage( GeneratedValue.class ) ); final GeneratedValue generatedValue = castNonNull( idMember.getDirectAnnotationUsage( GeneratedValue.class ) );
final InFlightMetadataCollector metadataCollector = context.getMetadataCollector();
if ( isGlobalGeneratorNameGlobal( context ) ) { if ( isGlobalGeneratorNameGlobal( context ) ) {
// process and register any generators defined on the member. // process and register any generators defined on the member.
// according to JPA these are also global. // according to JPA these are also global.
context.getMetadataCollector().getGlobalRegistrations().as( GlobalRegistrar.class ).collectIdGenerators( idMember ); metadataCollector.getGlobalRegistrations().as( GlobalRegistrar.class ).collectIdGenerators( idMember );
context.getMetadataCollector().addSecondPass( new StrictIdGeneratorResolverSecondPass( metadataCollector.addSecondPass( new StrictIdGeneratorResolverSecondPass(
persistentClass, persistentClass,
idValue, idValue,
idMember, idMember,
@ -738,7 +729,7 @@ private static void createIdGenerator(
) ); ) );
} }
else { else {
context.getMetadataCollector().addSecondPass( new IdGeneratorResolverSecondPass( metadataCollector.addSecondPass( new IdGeneratorResolverSecondPass(
persistentClass, persistentClass,
idValue, idValue,
idMember, idMember,
@ -750,7 +741,6 @@ private static void createIdGenerator(
public static void createGeneratorFrom( public static void createGeneratorFrom(
IdentifierGeneratorDefinition defaultedGenerator, IdentifierGeneratorDefinition defaultedGenerator,
MemberDetails idMember,
SimpleValue idValue, SimpleValue idValue,
Map<String, Object> configuration, Map<String, Object> configuration,
MetadataBuildingContext context) { MetadataBuildingContext context) {
@ -766,11 +756,6 @@ public static void createGeneratorFrom(
if ( identifierGenerator instanceof IdentityGenerator) { if ( identifierGenerator instanceof IdentityGenerator) {
idValue.setColumnToIdentity(); idValue.setColumnToIdentity();
} }
if ( identifierGenerator instanceof ExportableProducer exportableProducer ) {
exportableProducer.registerExportables( creationContext.getDatabase() );
}
return identifierGenerator; return identifierGenerator;
} ); } );
} }
@ -778,31 +763,22 @@ public static void createGeneratorFrom(
public static void createGeneratorFrom( public static void createGeneratorFrom(
IdentifierGeneratorDefinition defaultedGenerator, IdentifierGeneratorDefinition defaultedGenerator,
MemberDetails idMember,
SimpleValue idValue, SimpleValue idValue,
PersistentClass persistentClass,
MetadataBuildingContext context) { MetadataBuildingContext context) {
createGeneratorFrom( createGeneratorFrom(
defaultedGenerator, defaultedGenerator,
idMember,
idValue, idValue,
buildConfigurationMap( defaultedGenerator, idValue, persistentClass ), buildConfigurationMap( idValue ),
context context
); );
} }
public static Map<String, Object> buildConfigurationMap( private static Map<String, Object> buildConfigurationMap(KeyValue idValue) {
IdentifierGeneratorDefinition defaultedGenerator,
SimpleValue idValue,
PersistentClass persistentClass) {
final Map<String,Object> configuration = new HashMap<>(); final Map<String,Object> configuration = new HashMap<>();
configuration.put( PersistentIdentifierGenerator.TABLE, idValue.getTable().getName() ); configuration.put( PersistentIdentifierGenerator.TABLE, idValue.getTable().getName() );
if ( idValue.getColumnSpan() == 1 ) { if ( idValue.getColumnSpan() == 1 ) {
configuration.put( PersistentIdentifierGenerator.PK, idValue.getColumns().get( 0).getName() ); configuration.put( PersistentIdentifierGenerator.PK, idValue.getColumns().get(0).getName() );
} }
return configuration; return configuration;
} }
@ -941,15 +917,12 @@ static GeneratorCreator createValueGeneratorFromAnnotations(
final List<? extends Annotation> generatorAnnotations = final List<? extends Annotation> generatorAnnotations =
property.getMetaAnnotated( ValueGenerationType.class, property.getMetaAnnotated( ValueGenerationType.class,
context.getMetadataCollector().getSourceModelBuildingContext() ); context.getMetadataCollector().getSourceModelBuildingContext() );
switch ( generatorAnnotations.size() ) { return switch ( generatorAnnotations.size() ) {
case 0: case 0 -> null;
return null; case 1 -> generatorCreator( property, generatorAnnotations.get(0), beanContainer( context ) );
case 1: default -> throw new AnnotationException( "Property '" + qualify( holder.getPath(), propertyName )
return generatorCreator( property, generatorAnnotations.get(0), beanContainer( context ) );
default:
throw new AnnotationException( "Property '" + qualify( holder.getPath(), propertyName )
+ "' has too many generator annotations: " + generatorAnnotations ); + "' has too many generator annotations: " + generatorAnnotations );
} };
} }
public static void applyIfNotEmpty(String name, String value, BiConsumer<String,String> consumer) { public static void applyIfNotEmpty(String name, String value, BiConsumer<String,String> consumer) {

View File

@ -15,6 +15,7 @@
import org.hibernate.boot.models.spi.GlobalRegistrations; import org.hibernate.boot.models.spi.GlobalRegistrations;
import org.hibernate.boot.models.spi.SequenceGeneratorRegistration; import org.hibernate.boot.models.spi.SequenceGeneratorRegistration;
import org.hibernate.boot.models.spi.TableGeneratorRegistration; import org.hibernate.boot.models.spi.TableGeneratorRegistration;
import org.hibernate.boot.spi.InFlightMetadataCollector;
import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.MetadataBuildingContext;
import org.hibernate.generator.Generator; import org.hibernate.generator.Generator;
import org.hibernate.id.PersistentIdentifierGenerator; import org.hibernate.id.PersistentIdentifierGenerator;
@ -68,7 +69,7 @@ public void doSecondPass(Map<String, PersistentClass> idGeneratorDefinitionMap)
final GeneratedValue generatedValue = idAttributeMember.getDirectAnnotationUsage( GeneratedValue.class ); final GeneratedValue generatedValue = idAttributeMember.getDirectAnnotationUsage( GeneratedValue.class );
switch ( generatedValue.strategy() ) { switch ( generatedValue.strategy() ) {
case UUID -> GeneratorAnnotationHelper.handleUuidStrategy( idValue, idAttributeMember, buildingContext ); case UUID -> GeneratorAnnotationHelper.handleUuidStrategy( idValue, idAttributeMember, buildingContext );
case IDENTITY -> GeneratorAnnotationHelper.handleIdentityStrategy( idValue, idAttributeMember, buildingContext ); case IDENTITY -> GeneratorAnnotationHelper.handleIdentityStrategy( idValue );
case SEQUENCE -> handleSequenceStrategy( case SEQUENCE -> handleSequenceStrategy(
generatorName, generatorName,
idValue, idValue,
@ -80,15 +81,12 @@ public void doSecondPass(Map<String, PersistentClass> idGeneratorDefinitionMap)
entityMapping, entityMapping,
idValue, idValue,
idAttributeMember, idAttributeMember,
generatedValue,
buildingContext buildingContext
); );
case AUTO -> handleAutoStrategy( case AUTO -> handleAutoStrategy(
generatorName, generatorName,
entityMapping,
idValue, idValue,
idAttributeMember, idAttributeMember,
generatedValue,
buildingContext buildingContext
); );
} }
@ -99,17 +97,18 @@ private void handleTableStrategy(
PersistentClass entityMapping, PersistentClass entityMapping,
SimpleValue idValue, SimpleValue idValue,
MemberDetails idAttributeMember, MemberDetails idAttributeMember,
GeneratedValue generatedValue,
MetadataBuildingContext buildingContext) { MetadataBuildingContext buildingContext) {
final GlobalRegistrations globalRegistrations = buildingContext.getMetadataCollector().getGlobalRegistrations(); final InFlightMetadataCollector metadataCollector = buildingContext.getMetadataCollector();
final TableGeneratorRegistration globalTableGenerator = globalRegistrations.getTableGeneratorRegistrations().get( generatorName ); final GlobalRegistrations globalRegistrations = metadataCollector.getGlobalRegistrations();
final TableGeneratorRegistration globalTableGenerator =
globalRegistrations.getTableGeneratorRegistrations().get( generatorName );
if ( globalTableGenerator != null ) { if ( globalTableGenerator != null ) {
handleTableGenerator( handleTableGenerator(
generatorName, generatorName,
globalTableGenerator.configuration(), globalTableGenerator.configuration(),
configuration, configuration,
idValue, idValue,
idAttributeMember,
buildingContext buildingContext
); );
return; return;
@ -123,16 +122,15 @@ private void handleTableStrategy(
buildingContext buildingContext
); );
if ( localizedTableMatch != null ) { if ( localizedTableMatch != null ) {
handleTableGenerator( generatorName, localizedTableMatch, configuration, idValue, idAttributeMember, buildingContext ); handleTableGenerator( generatorName, localizedTableMatch, configuration, idValue, buildingContext );
return; return;
} }
GeneratorAnnotationHelper.handleTableGenerator( GeneratorAnnotationHelper.handleTableGenerator(
generatorName, generatorName,
new TableGeneratorJpaAnnotation( buildingContext.getMetadataCollector().getSourceModelBuildingContext() ), new TableGeneratorJpaAnnotation( metadataCollector.getSourceModelBuildingContext() ),
entityMapping, entityMapping,
idValue, idValue,
idAttributeMember,
buildingContext buildingContext
); );
} }
@ -142,16 +140,17 @@ private void handleSequenceStrategy(
SimpleValue idValue, SimpleValue idValue,
MemberDetails idAttributeMember, MemberDetails idAttributeMember,
MetadataBuildingContext buildingContext) { MetadataBuildingContext buildingContext) {
final GlobalRegistrations globalRegistrations = buildingContext.getMetadataCollector().getGlobalRegistrations(); final InFlightMetadataCollector metadataCollector = buildingContext.getMetadataCollector();
final GlobalRegistrations globalRegistrations = metadataCollector.getGlobalRegistrations();
final SequenceGeneratorRegistration globalSequenceGenerator = globalRegistrations.getSequenceGeneratorRegistrations().get( generatorName ); final SequenceGeneratorRegistration globalSequenceGenerator =
globalRegistrations.getSequenceGeneratorRegistrations().get( generatorName );
if ( globalSequenceGenerator != null ) { if ( globalSequenceGenerator != null ) {
handleSequenceGenerator( handleSequenceGenerator(
generatorName, generatorName,
globalSequenceGenerator.configuration(), globalSequenceGenerator.configuration(),
configuration, configuration,
idValue, idValue,
idAttributeMember,
buildingContext buildingContext
); );
return; return;
@ -165,57 +164,56 @@ private void handleSequenceStrategy(
buildingContext buildingContext
); );
if ( localizedSequencedMatch != null ) { if ( localizedSequencedMatch != null ) {
handleSequenceGenerator( generatorName, localizedSequencedMatch, configuration, idValue, idAttributeMember, buildingContext ); handleSequenceGenerator( generatorName, localizedSequencedMatch, configuration, idValue, buildingContext );
return; return;
} }
handleSequenceGenerator( handleSequenceGenerator(
generatorName, generatorName,
new SequenceGeneratorJpaAnnotation( buildingContext.getMetadataCollector().getSourceModelBuildingContext() ), new SequenceGeneratorJpaAnnotation( metadataCollector.getSourceModelBuildingContext() ),
configuration, configuration,
idValue, idValue,
idAttributeMember,
buildingContext buildingContext
); );
} }
private void handleAutoStrategy( private void handleAutoStrategy(
String generatorName, String generatorName,
PersistentClass entityMapping,
SimpleValue idValue, SimpleValue idValue,
MemberDetails idAttributeMember, MemberDetails idAttributeMember,
GeneratedValue generatedValue,
MetadataBuildingContext buildingContext) { MetadataBuildingContext buildingContext) {
final GlobalRegistrations globalRegistrations = buildingContext.getMetadataCollector().getGlobalRegistrations(); final GlobalRegistrations globalRegistrations =
buildingContext.getMetadataCollector().getGlobalRegistrations();
final SequenceGeneratorRegistration globalSequenceGenerator = globalRegistrations.getSequenceGeneratorRegistrations().get( generatorName ); final SequenceGeneratorRegistration globalSequenceGenerator =
globalRegistrations.getSequenceGeneratorRegistrations().get( generatorName );
if ( globalSequenceGenerator != null ) { if ( globalSequenceGenerator != null ) {
handleSequenceGenerator( handleSequenceGenerator(
generatorName, generatorName,
globalSequenceGenerator.configuration(), globalSequenceGenerator.configuration(),
configuration, configuration,
idValue, idValue,
idAttributeMember,
buildingContext buildingContext
); );
return; return;
} }
final TableGeneratorRegistration globalTableGenerator = globalRegistrations.getTableGeneratorRegistrations().get( generatorName ); final TableGeneratorRegistration globalTableGenerator =
globalRegistrations.getTableGeneratorRegistrations().get( generatorName );
if ( globalTableGenerator != null ) { if ( globalTableGenerator != null ) {
handleTableGenerator( handleTableGenerator(
generatorName, generatorName,
globalTableGenerator.configuration(), globalTableGenerator.configuration(),
configuration, configuration,
idValue, idValue,
idAttributeMember,
buildingContext buildingContext
); );
return; return;
} }
final Class<? extends Generator> legacyNamedGenerator = GeneratorStrategies.mapLegacyNamedGenerator( generatorName, idValue ); final Class<? extends Generator> legacyNamedGenerator =
GeneratorStrategies.mapLegacyNamedGenerator( generatorName, idValue );
if ( legacyNamedGenerator != null ) { if ( legacyNamedGenerator != null ) {
//generator settings //generator settings
if ( idValue.getColumnSpan() == 1 ) { if ( idValue.getColumnSpan() == 1 ) {
@ -223,7 +221,6 @@ private void handleAutoStrategy(
} }
createGeneratorFrom( createGeneratorFrom(
new IdentifierGeneratorDefinition( generatorName, legacyNamedGenerator.getName(), configuration ), new IdentifierGeneratorDefinition( generatorName, legacyNamedGenerator.getName(), configuration ),
idAttributeMember,
idValue, idValue,
(Map) configuration, (Map) configuration,
buildingContext buildingContext
@ -231,7 +228,6 @@ private void handleAutoStrategy(
return; return;
} }
final SequenceGenerator localizedSequencedMatch = GeneratorAnnotationHelper.findLocalizedMatch( final SequenceGenerator localizedSequencedMatch = GeneratorAnnotationHelper.findLocalizedMatch(
JpaAnnotations.SEQUENCE_GENERATOR, JpaAnnotations.SEQUENCE_GENERATOR,
idAttributeMember, idAttributeMember,
@ -240,7 +236,7 @@ private void handleAutoStrategy(
buildingContext buildingContext
); );
if ( localizedSequencedMatch != null ) { if ( localizedSequencedMatch != null ) {
handleSequenceGenerator( generatorName, localizedSequencedMatch, configuration, idValue, idAttributeMember, buildingContext ); handleSequenceGenerator( generatorName, localizedSequencedMatch, configuration, idValue, buildingContext );
return; return;
} }
@ -252,7 +248,7 @@ private void handleAutoStrategy(
buildingContext buildingContext
); );
if ( localizedTableMatch != null ) { if ( localizedTableMatch != null ) {
handleTableGenerator( generatorName, localizedTableMatch, configuration, idValue, idAttributeMember, buildingContext ); handleTableGenerator( generatorName, localizedTableMatch, configuration, idValue, buildingContext );
return; return;
} }
@ -264,19 +260,15 @@ public static void handleSequenceGenerator(
SequenceGenerator generatorConfig, SequenceGenerator generatorConfig,
Map<String,String> configuration, Map<String,String> configuration,
SimpleValue idValue, SimpleValue idValue,
MemberDetails idMember,
MetadataBuildingContext context) { MetadataBuildingContext context) {
applyBaselineConfiguration( generatorConfig, idValue, null, context, configuration::put ); applyBaselineConfiguration( generatorConfig, idValue, null, context, configuration::put );
SequenceStyleGenerator.applyConfiguration( generatorConfig, idValue, configuration::put ); SequenceStyleGenerator.applyConfiguration( generatorConfig, configuration::put );
createGeneratorFrom( createGeneratorFrom(
new IdentifierGeneratorDefinition( generatorName, SequenceStyleGenerator.class.getName(), configuration ), new IdentifierGeneratorDefinition( generatorName, SequenceStyleGenerator.class.getName(), configuration ),
idMember,
idValue, idValue,
(Map) configuration, (Map) configuration,
context context
); );
} }
public static void handleTableGenerator( public static void handleTableGenerator(
@ -284,14 +276,12 @@ public static void handleTableGenerator(
TableGenerator generatorConfig, TableGenerator generatorConfig,
Map<String,String> configuration, Map<String,String> configuration,
SimpleValue idValue, SimpleValue idValue,
MemberDetails idMember,
MetadataBuildingContext context) { MetadataBuildingContext context) {
GeneratorAnnotationHelper.applyBaselineConfiguration( generatorConfig, idValue, null, context, configuration::put ); GeneratorAnnotationHelper.applyBaselineConfiguration( generatorConfig, idValue, null, context, configuration::put );
org.hibernate.id.enhanced.TableGenerator.applyConfiguration( generatorConfig, idValue, configuration::put ); org.hibernate.id.enhanced.TableGenerator.applyConfiguration( generatorConfig, configuration::put );
createGeneratorFrom( createGeneratorFrom(
new IdentifierGeneratorDefinition( generatorName, org.hibernate.id.enhanced.TableGenerator.class.getName(), configuration ), new IdentifierGeneratorDefinition( generatorName, org.hibernate.id.enhanced.TableGenerator.class.getName(), configuration ),
idMember,
idValue, idValue,
(Map) configuration, (Map) configuration,
context context

View File

@ -15,15 +15,14 @@
import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.IdGeneratorType; import org.hibernate.annotations.IdGeneratorType;
import org.hibernate.boot.model.IdentifierGeneratorDefinition; import org.hibernate.boot.model.IdentifierGeneratorDefinition;
import org.hibernate.boot.model.relational.ExportableProducer;
import org.hibernate.boot.models.HibernateAnnotations; import org.hibernate.boot.models.HibernateAnnotations;
import org.hibernate.boot.models.JpaAnnotations; import org.hibernate.boot.models.JpaAnnotations;
import org.hibernate.boot.models.spi.GenericGeneratorRegistration; import org.hibernate.boot.models.spi.GenericGeneratorRegistration;
import org.hibernate.boot.models.spi.GlobalRegistrations;
import org.hibernate.boot.models.spi.SequenceGeneratorRegistration; import org.hibernate.boot.models.spi.SequenceGeneratorRegistration;
import org.hibernate.boot.models.spi.TableGeneratorRegistration; import org.hibernate.boot.models.spi.TableGeneratorRegistration;
import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.spi.InFlightMetadataCollector;
import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.MetadataBuildingContext;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.engine.config.spi.ConfigurationService; import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.engine.config.spi.StandardConverters; import org.hibernate.engine.config.spi.StandardConverters;
import org.hibernate.generator.Generator; import org.hibernate.generator.Generator;
@ -43,7 +42,9 @@
import jakarta.persistence.TableGenerator; import jakarta.persistence.TableGenerator;
import static org.hibernate.boot.model.internal.GeneratorBinder.callConfigure; import static org.hibernate.boot.model.internal.GeneratorBinder.callConfigure;
import static org.hibernate.boot.model.internal.GeneratorBinder.instantiateGenerator;
import static org.hibernate.boot.model.internal.GeneratorStrategies.mapLegacyNamedGenerator; import static org.hibernate.boot.model.internal.GeneratorStrategies.mapLegacyNamedGenerator;
import static org.hibernate.cfg.MappingSettings.ID_DB_STRUCTURE_NAMING_STRATEGY;
import static org.hibernate.id.IdentifierGenerator.GENERATOR_NAME; import static org.hibernate.id.IdentifierGenerator.GENERATOR_NAME;
import static org.hibernate.id.OptimizableGenerator.INCREMENT_PARAM; import static org.hibernate.id.OptimizableGenerator.INCREMENT_PARAM;
@ -78,7 +79,7 @@ public IdGeneratorResolverSecondPass(
public void doSecondPass(Map<String, PersistentClass> persistentClasses) throws MappingException { public void doSecondPass(Map<String, PersistentClass> persistentClasses) throws MappingException {
switch ( generatedValue.strategy() ) { switch ( generatedValue.strategy() ) {
case UUID -> GeneratorAnnotationHelper.handleUuidStrategy( idValue, idMember, buildingContext ); case UUID -> GeneratorAnnotationHelper.handleUuidStrategy( idValue, idMember, buildingContext );
case IDENTITY -> GeneratorAnnotationHelper.handleIdentityStrategy( idValue, idMember, buildingContext ); case IDENTITY -> GeneratorAnnotationHelper.handleIdentityStrategy( idValue );
case SEQUENCE -> handleSequenceStrategy(); case SEQUENCE -> handleSequenceStrategy();
case TABLE -> handleTableStrategy(); case TABLE -> handleTableStrategy();
case AUTO -> handleAutoStrategy(); case AUTO -> handleAutoStrategy();
@ -113,62 +114,65 @@ private void handleUnnamedSequenceGenerator() {
} }
private void handleNamedSequenceGenerator() { private void handleNamedSequenceGenerator() {
final String generator = generatedValue.generator();
final SequenceGenerator localizedMatch = GeneratorAnnotationHelper.findLocalizedMatch( final SequenceGenerator localizedMatch = GeneratorAnnotationHelper.findLocalizedMatch(
JpaAnnotations.SEQUENCE_GENERATOR, JpaAnnotations.SEQUENCE_GENERATOR,
idMember, idMember,
SequenceGenerator::name, SequenceGenerator::name,
generatedValue.generator(), generator,
buildingContext buildingContext
); );
if ( localizedMatch != null ) { if ( localizedMatch != null ) {
handleSequenceGenerator( generatedValue.generator(), localizedMatch ); handleSequenceGenerator( generator, localizedMatch );
return; return;
} }
// look for the matching global registration, if one. // look for the matching global registration, if one.
final SequenceGeneratorRegistration globalMatch = buildingContext.getMetadataCollector() final SequenceGeneratorRegistration globalMatch =
buildingContext.getMetadataCollector()
.getGlobalRegistrations() .getGlobalRegistrations()
.getSequenceGeneratorRegistrations() .getSequenceGeneratorRegistrations()
.get( generatedValue.generator() ); .get( generator );
if ( globalMatch != null ) { if ( globalMatch != null ) {
handleSequenceGenerator( generatedValue.generator(), globalMatch.configuration() ); handleSequenceGenerator( generator, globalMatch.configuration() );
return; return;
} }
validateSequenceGeneration(); validateSequenceGeneration();
handleSequenceGenerator( generatedValue.generator(), null ); handleSequenceGenerator( generator, null );
} }
private void validateSequenceGeneration() { private void validateSequenceGeneration() {
// basically, make sure there is neither a TableGenerator nor GenericGenerator with this name // basically, make sure there is neither a TableGenerator nor GenericGenerator with this name
final TableGeneratorRegistration globalTableMatch = buildingContext.getMetadataCollector() final GlobalRegistrations globalRegistrations =
.getGlobalRegistrations() buildingContext.getMetadataCollector().getGlobalRegistrations();
.getTableGeneratorRegistrations() final String generator = generatedValue.generator();
.get( generatedValue.generator() );
final TableGeneratorRegistration globalTableMatch =
globalRegistrations.getTableGeneratorRegistrations().get( generator );
if ( globalTableMatch != null ) { if ( globalTableMatch != null ) {
throw new MappingException( throw new MappingException(
String.format( String.format(
Locale.ROOT, Locale.ROOT,
"@GeneratedValue for %s (%s) specified SEQUENCE generation, but referred to a @TableGenerator", "@GeneratedValue for %s (%s) specified SEQUENCE generation, but referred to a @TableGenerator",
entityMapping.getEntityName(), entityMapping.getEntityName(),
generatedValue.generator() generator
) )
); );
} }
final GenericGeneratorRegistration globalGenericMatch = buildingContext.getMetadataCollector() final GenericGeneratorRegistration globalGenericMatch =
.getGlobalRegistrations() globalRegistrations.getGenericGeneratorRegistrations().get( generator );
.getGenericGeneratorRegistrations()
.get( generatedValue.generator() );
if ( globalGenericMatch != null ) { if ( globalGenericMatch != null ) {
throw new MappingException( throw new MappingException(
String.format( String.format(
Locale.ROOT, Locale.ROOT,
"@GeneratedValue for %s (%s) specified SEQUENCE generation, but referred to a @GenericGenerator", "@GeneratedValue for %s (%s) specified SEQUENCE generation, but referred to a @GenericGenerator",
entityMapping.getEntityName(), entityMapping.getEntityName(),
generatedValue.generator() generator
) )
); );
} }
@ -193,71 +197,67 @@ private void handleUnnamedTableGenerator() {
null, null,
buildingContext buildingContext
); );
if ( localizedMatch != null ) {
handleTableGenerator( null, localizedMatch ); handleTableGenerator( null, localizedMatch );
return;
}
handleTableGenerator( null, null );
} }
private void handleNamedTableGenerator() { private void handleNamedTableGenerator() {
final String generator = generatedValue.generator();
final TableGenerator localizedTableMatch = GeneratorAnnotationHelper.findLocalizedMatch( final TableGenerator localizedTableMatch = GeneratorAnnotationHelper.findLocalizedMatch(
JpaAnnotations.TABLE_GENERATOR, JpaAnnotations.TABLE_GENERATOR,
idMember, idMember,
TableGenerator::name, TableGenerator::name,
generatedValue.generator(), generator,
buildingContext buildingContext
); );
if ( localizedTableMatch != null ) { if ( localizedTableMatch != null ) {
handleTableGenerator( generatedValue.generator(), localizedTableMatch ); handleTableGenerator( generator, localizedTableMatch );
return; return;
} }
// look for the matching global registration, if one. // look for the matching global registration, if one.
final TableGeneratorRegistration globalMatch = buildingContext.getMetadataCollector() final TableGeneratorRegistration globalMatch =
.getGlobalRegistrations() buildingContext.getMetadataCollector().getGlobalRegistrations()
.getTableGeneratorRegistrations() .getTableGeneratorRegistrations().get( generator );
.get( generatedValue.generator() );
if ( globalMatch != null ) { if ( globalMatch != null ) {
handleTableGenerator( generatedValue.generator(), globalMatch.configuration() ); handleTableGenerator( generator, globalMatch.configuration() );
return; return;
} }
validateTableGeneration(); validateTableGeneration();
handleTableGenerator( generatedValue.generator(), null ); handleTableGenerator( generator, null );
} }
private void validateTableGeneration() { private void validateTableGeneration() {
// basically, make sure there is neither a SequenceGenerator nor a GenericGenerator with this name // basically, make sure there is neither a SequenceGenerator nor a GenericGenerator with this name
final SequenceGeneratorRegistration globalSequenceMatch = buildingContext.getMetadataCollector() final GlobalRegistrations globalRegistrations =
.getGlobalRegistrations() buildingContext.getMetadataCollector().getGlobalRegistrations();
.getSequenceGeneratorRegistrations() final String generator = generatedValue.generator();
.get( generatedValue.generator() );
final SequenceGeneratorRegistration globalSequenceMatch =
globalRegistrations.getSequenceGeneratorRegistrations().get( generator );
if ( globalSequenceMatch != null ) { if ( globalSequenceMatch != null ) {
throw new MappingException( throw new MappingException(
String.format( String.format(
Locale.ROOT, Locale.ROOT,
"@GeneratedValue for %s (%s) specified TABLE generation, but referred to a @SequenceGenerator", "@GeneratedValue for %s (%s) specified TABLE generation, but referred to a @SequenceGenerator",
entityMapping.getEntityName(), entityMapping.getEntityName(),
generatedValue.generator() generator
) )
); );
} }
final GenericGeneratorRegistration globalGenericMatch = buildingContext.getMetadataCollector() final GenericGeneratorRegistration globalGenericMatch =
.getGlobalRegistrations() globalRegistrations.getGenericGeneratorRegistrations().get( generator );
.getGenericGeneratorRegistrations()
.get( generatedValue.generator() );
if ( globalGenericMatch != null ) { if ( globalGenericMatch != null ) {
throw new MappingException( throw new MappingException(
String.format( String.format(
Locale.ROOT, Locale.ROOT,
"@GeneratedValue for %s (%s) specified TABLE generation, but referred to a @GenericGenerator", "@GeneratedValue for %s (%s) specified TABLE generation, but referred to a @GenericGenerator",
entityMapping.getEntityName(), entityMapping.getEntityName(),
generatedValue.generator() generator
) )
); );
} }
@ -312,7 +312,6 @@ private void handleUnnamedAutoGenerator() {
localizedGenericMatch, localizedGenericMatch,
entityMapping, entityMapping,
idValue, idValue,
idMember,
buildingContext buildingContext
); );
return; return;
@ -336,34 +335,35 @@ private void handleNamedAutoGenerator() {
return; return;
} }
final Class<? extends Generator> legacyNamedGenerator = mapLegacyNamedGenerator( generatedValue.generator(), buildingContext ); final String generator = generatedValue.generator();
final Class<? extends Generator> legacyNamedGenerator = mapLegacyNamedGenerator( generator, buildingContext );
if ( legacyNamedGenerator != null ) { if ( legacyNamedGenerator != null ) {
//generator settings //generator settings
GeneratorBinder.createGeneratorFrom( GeneratorBinder.createGeneratorFrom(
new IdentifierGeneratorDefinition( generatedValue.generator(), legacyNamedGenerator.getName() ), new IdentifierGeneratorDefinition( generator, legacyNamedGenerator.getName() ),
idMember,
idValue, idValue,
entityMapping,
buildingContext buildingContext
); );
return; return;
} }
final List<? extends Annotation> metaAnnotated = idMember.getMetaAnnotated( IdGeneratorType.class, buildingContext.getMetadataCollector().getSourceModelBuildingContext() ); final InFlightMetadataCollector metadataCollector = buildingContext.getMetadataCollector();
final List<? extends Annotation> metaAnnotated =
idMember.getMetaAnnotated( IdGeneratorType.class, metadataCollector.getSourceModelBuildingContext() );
if ( CollectionHelper.size( metaAnnotated ) > 0 ) { if ( CollectionHelper.size( metaAnnotated ) > 0 ) {
final Annotation generatorAnnotation = metaAnnotated.get( 0 ); final Annotation generatorAnnotation = metaAnnotated.get( 0 );
final IdGeneratorType markerAnnotation = generatorAnnotation.annotationType().getAnnotation( IdGeneratorType.class ); final IdGeneratorType markerAnnotation = generatorAnnotation.annotationType().getAnnotation( IdGeneratorType.class );
idValue.setCustomIdGeneratorCreator( (creationContext) -> { idValue.setCustomIdGeneratorCreator( (creationContext) -> {
final BeanContainer beanContainer = GeneratorBinder.beanContainer( buildingContext ); final BeanContainer beanContainer = GeneratorBinder.beanContainer( buildingContext );
final Generator identifierGenerator = GeneratorBinder.instantiateGenerator( final Generator identifierGenerator = instantiateGenerator(
beanContainer, beanContainer,
markerAnnotation.value() markerAnnotation.value()
); );
final Map<String,Object> configuration = new HashMap<>(); final Map<String,Object> configuration = new HashMap<>();
GeneratorParameters.collectParameters( GeneratorParameters.collectParameters(
idValue, idValue,
buildingContext.getMetadataCollector().getDatabase().getDialect(), metadataCollector.getDatabase().getDialect(),
entityMapping.getRootClass(), entityMapping.getRootClass(),
configuration::put configuration::put
); );
@ -379,21 +379,22 @@ private void handleNamedAutoGenerator() {
return; return;
} }
handleSequenceGenerator( generatedValue.generator(), null ); handleSequenceGenerator(generator, null );
} }
private boolean handleAsLocalAutoGenerator() { private boolean handleAsLocalAutoGenerator() {
assert !generatedValue.generator().isEmpty(); final String generator = generatedValue.generator();
assert !generator.isEmpty();
final SequenceGenerator localizedSequenceMatch = GeneratorAnnotationHelper.findLocalizedMatch( final SequenceGenerator localizedSequenceMatch = GeneratorAnnotationHelper.findLocalizedMatch(
JpaAnnotations.SEQUENCE_GENERATOR, JpaAnnotations.SEQUENCE_GENERATOR,
idMember, idMember,
SequenceGenerator::name, SequenceGenerator::name,
generatedValue.generator(), generator,
buildingContext buildingContext
); );
if ( localizedSequenceMatch != null ) { if ( localizedSequenceMatch != null ) {
handleSequenceGenerator( generatedValue.generator(), localizedSequenceMatch ); handleSequenceGenerator( generator, localizedSequenceMatch );
return true; return true;
} }
@ -401,11 +402,11 @@ private boolean handleAsLocalAutoGenerator() {
JpaAnnotations.TABLE_GENERATOR, JpaAnnotations.TABLE_GENERATOR,
idMember, idMember,
TableGenerator::name, TableGenerator::name,
generatedValue.generator(), generator,
buildingContext buildingContext
); );
if ( localizedTableMatch != null ) { if ( localizedTableMatch != null ) {
handleTableGenerator( generatedValue.generator(), localizedTableMatch ); handleTableGenerator(generator, localizedTableMatch );
return true; return true;
} }
@ -413,16 +414,15 @@ private boolean handleAsLocalAutoGenerator() {
HibernateAnnotations.GENERIC_GENERATOR, HibernateAnnotations.GENERIC_GENERATOR,
idMember, idMember,
GenericGenerator::name, GenericGenerator::name,
generatedValue.generator(), generator,
buildingContext buildingContext
); );
if ( localizedGenericMatch != null ) { if ( localizedGenericMatch != null ) {
GeneratorAnnotationHelper.handleGenericGenerator( GeneratorAnnotationHelper.handleGenericGenerator(
generatedValue.generator(), generator,
localizedGenericMatch, localizedGenericMatch,
entityMapping, entityMapping,
idValue, idValue,
idMember,
buildingContext buildingContext
); );
return true; return true;
@ -432,35 +432,32 @@ private boolean handleAsLocalAutoGenerator() {
} }
private boolean handleAsNamedGlobalAutoGenerator() { private boolean handleAsNamedGlobalAutoGenerator() {
final SequenceGeneratorRegistration globalSequenceMatch = buildingContext.getMetadataCollector() final GlobalRegistrations globalRegistrations =
.getGlobalRegistrations() buildingContext.getMetadataCollector().getGlobalRegistrations();
.getSequenceGeneratorRegistrations() final String generator = generatedValue.generator();
.get( generatedValue.generator() );
final SequenceGeneratorRegistration globalSequenceMatch =
globalRegistrations.getSequenceGeneratorRegistrations().get( generator );
if ( globalSequenceMatch != null ) { if ( globalSequenceMatch != null ) {
handleSequenceGenerator( generatedValue.generator(), globalSequenceMatch.configuration() ); handleSequenceGenerator( generator, globalSequenceMatch.configuration() );
return true; return true;
} }
final TableGeneratorRegistration globalTableMatch = buildingContext.getMetadataCollector() final TableGeneratorRegistration globalTableMatch =
.getGlobalRegistrations() globalRegistrations.getTableGeneratorRegistrations().get( generator );
.getTableGeneratorRegistrations()
.get( generatedValue.generator() );
if ( globalTableMatch != null ) { if ( globalTableMatch != null ) {
handleTableGenerator( generatedValue.generator(), globalTableMatch.configuration() ); handleTableGenerator( generator, globalTableMatch.configuration() );
return true; return true;
} }
final GenericGeneratorRegistration globalGenericMatch = buildingContext.getMetadataCollector() final GenericGeneratorRegistration globalGenericMatch =
.getGlobalRegistrations() globalRegistrations.getGenericGeneratorRegistrations().get( generator );
.getGenericGeneratorRegistrations()
.get( generatedValue.generator() );
if ( globalGenericMatch != null ) { if ( globalGenericMatch != null ) {
GeneratorAnnotationHelper.handleGenericGenerator( GeneratorAnnotationHelper.handleGenericGenerator(
generatedValue.generator(), generator,
globalGenericMatch.configuration(), globalGenericMatch.configuration(),
entityMapping, entityMapping,
idValue, idValue,
idMember,
buildingContext buildingContext
); );
return true; return true;
@ -470,8 +467,7 @@ private boolean handleAsNamedGlobalAutoGenerator() {
} }
private void handleSequenceGenerator(String nameFromGeneratedValue, SequenceGenerator generator) { private void handleSequenceGenerator(String nameFromGeneratedValue, SequenceGenerator generator) {
final Map<String, Object> configuration = extractConfiguration( nameFromGeneratedValue, generator ); createGeneratorFrom( SequenceStyleGenerator.class, extractConfiguration( nameFromGeneratedValue, generator ) );
createGeneratorFrom( SequenceStyleGenerator.class, configuration );
} }
private Map<String,Object> extractConfiguration(String nameFromGenerated, SequenceGenerator generator) { private Map<String,Object> extractConfiguration(String nameFromGenerated, SequenceGenerator generator) {
@ -486,7 +482,7 @@ else if ( nameFromGenerated != null ) {
applyCommonConfiguration( configuration, generator ); applyCommonConfiguration( configuration, generator );
if ( generator != null ) { if ( generator != null ) {
SequenceStyleGenerator.applyConfiguration( generator, idValue, configuration::put ); SequenceStyleGenerator.applyConfiguration( generator, configuration::put );
} }
return configuration; return configuration;
@ -511,13 +507,11 @@ private static int fallbackAllocationSize(MetadataBuildingContext buildingContex
// here should be 50. As a migration aid, under the assumption that one of the legacy // here should be 50. As a migration aid, under the assumption that one of the legacy
// naming-strategies are used in such cases, we revert to the old default; otherwise we // naming-strategies are used in such cases, we revert to the old default; otherwise we
// use the compliant value. // use the compliant value.
final StandardServiceRegistry serviceRegistry = buildingContext.getBootstrapContext().getServiceRegistry(); final ConfigurationService configService =
final ConfigurationService configService = serviceRegistry.requireService( ConfigurationService.class ); buildingContext.getBootstrapContext().getServiceRegistry()
final String idNamingStrategy = configService.getSetting( .requireService( ConfigurationService.class );
AvailableSettings.ID_DB_STRUCTURE_NAMING_STRATEGY, final String idNamingStrategy =
StandardConverters.STRING, configService.getSetting( ID_DB_STRUCTURE_NAMING_STRATEGY, StandardConverters.STRING );
null
);
if ( LegacyNamingStrategy.STRATEGY_NAME.equals( idNamingStrategy ) if ( LegacyNamingStrategy.STRATEGY_NAME.equals( idNamingStrategy )
|| LegacyNamingStrategy.class.getName().equals( idNamingStrategy ) || LegacyNamingStrategy.class.getName().equals( idNamingStrategy )
|| SingleNamingStrategy.STRATEGY_NAME.equals( idNamingStrategy ) || SingleNamingStrategy.STRATEGY_NAME.equals( idNamingStrategy )
@ -530,8 +524,8 @@ private static int fallbackAllocationSize(MetadataBuildingContext buildingContex
} }
private void handleTableGenerator(String nameFromGeneratedValue, TableGenerator generator) { private void handleTableGenerator(String nameFromGeneratedValue, TableGenerator generator) {
final Map<String, Object> configuration = extractConfiguration( nameFromGeneratedValue, generator ); createGeneratorFrom( org.hibernate.id.enhanced.TableGenerator.class,
createGeneratorFrom( org.hibernate.id.enhanced.TableGenerator.class, configuration ); extractConfiguration( nameFromGeneratedValue, generator ) );
} }
private Map<String,Object> extractConfiguration(String nameFromGenerated, TableGenerator generator) { private Map<String,Object> extractConfiguration(String nameFromGenerated, TableGenerator generator) {
@ -546,7 +540,7 @@ else if ( nameFromGenerated != null ) {
applyCommonConfiguration( configuration, generator ); applyCommonConfiguration( configuration, generator );
if ( generator != null ) { if ( generator != null ) {
org.hibernate.id.enhanced.TableGenerator.applyConfiguration( generator, idValue, configuration::put ); org.hibernate.id.enhanced.TableGenerator.applyConfiguration( generator, configuration::put );
} }
return configuration; return configuration;
@ -557,16 +551,11 @@ private void createGeneratorFrom(
Map<String, Object> configuration) { Map<String, Object> configuration) {
final BeanContainer beanContainer = GeneratorBinder.beanContainer( buildingContext ); final BeanContainer beanContainer = GeneratorBinder.beanContainer( buildingContext );
idValue.setCustomIdGeneratorCreator( (creationContext) -> { idValue.setCustomIdGeneratorCreator( (creationContext) -> {
final Generator identifierGenerator = GeneratorBinder.instantiateGenerator( beanContainer, generatorClass ); final Generator identifierGenerator = instantiateGenerator( beanContainer, generatorClass );
callConfigure( creationContext, identifierGenerator, configuration, idValue ); callConfigure( creationContext, identifierGenerator, configuration, idValue );
if ( identifierGenerator instanceof IdentityGenerator ) { if ( identifierGenerator instanceof IdentityGenerator ) {
idValue.setColumnToIdentity(); idValue.setColumnToIdentity();
} }
// if we get here we have either a sequence or table generator,
// both of which are ExportableProducers
( (ExportableProducer) identifierGenerator ).registerExportables( creationContext.getDatabase() );
return identifierGenerator; return identifierGenerator;
} ); } );
} }

View File

@ -14,8 +14,10 @@
import org.hibernate.boot.models.annotations.internal.SequenceGeneratorJpaAnnotation; import org.hibernate.boot.models.annotations.internal.SequenceGeneratorJpaAnnotation;
import org.hibernate.boot.models.annotations.internal.TableGeneratorJpaAnnotation; import org.hibernate.boot.models.annotations.internal.TableGeneratorJpaAnnotation;
import org.hibernate.boot.models.spi.GenericGeneratorRegistration; import org.hibernate.boot.models.spi.GenericGeneratorRegistration;
import org.hibernate.boot.models.spi.GlobalRegistrations;
import org.hibernate.boot.models.spi.SequenceGeneratorRegistration; import org.hibernate.boot.models.spi.SequenceGeneratorRegistration;
import org.hibernate.boot.models.spi.TableGeneratorRegistration; import org.hibernate.boot.models.spi.TableGeneratorRegistration;
import org.hibernate.boot.spi.InFlightMetadataCollector;
import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.MetadataBuildingContext;
import org.hibernate.dialect.Dialect; import org.hibernate.dialect.Dialect;
import org.hibernate.generator.Generator; import org.hibernate.generator.Generator;
@ -31,6 +33,7 @@
import static org.hibernate.boot.model.internal.GeneratorAnnotationHelper.*; import static org.hibernate.boot.model.internal.GeneratorAnnotationHelper.*;
import static org.hibernate.boot.model.internal.GeneratorAnnotationHelper.handleUuidStrategy; import static org.hibernate.boot.model.internal.GeneratorAnnotationHelper.handleUuidStrategy;
import static org.hibernate.boot.model.internal.GeneratorParameters.identityTablesString; import static org.hibernate.boot.model.internal.GeneratorParameters.identityTablesString;
import static org.hibernate.boot.model.internal.GeneratorStrategies.mapLegacyNamedGenerator;
import static org.hibernate.id.IdentifierGenerator.ENTITY_NAME; import static org.hibernate.id.IdentifierGenerator.ENTITY_NAME;
import static org.hibernate.id.IdentifierGenerator.GENERATOR_NAME; import static org.hibernate.id.IdentifierGenerator.GENERATOR_NAME;
import static org.hibernate.id.IdentifierGenerator.JPA_ENTITY_NAME; import static org.hibernate.id.IdentifierGenerator.JPA_ENTITY_NAME;
@ -77,7 +80,7 @@ public void doSecondPass(Map<String, PersistentClass> persistentClasses) throws
final GeneratedValue generatedValue = idMember.getDirectAnnotationUsage( GeneratedValue.class ); final GeneratedValue generatedValue = idMember.getDirectAnnotationUsage( GeneratedValue.class );
switch ( generatedValue.strategy() ) { switch ( generatedValue.strategy() ) {
case UUID -> handleUuidStrategy( idValue, idMember, buildingContext ); case UUID -> handleUuidStrategy( idValue, idMember, buildingContext );
case IDENTITY -> handleIdentityStrategy( idValue, idMember, buildingContext ); case IDENTITY -> handleIdentityStrategy( idValue );
case SEQUENCE -> handleSequenceStrategy( generatedValue ); case SEQUENCE -> handleSequenceStrategy( generatedValue );
case TABLE -> handleTableStrategy( generatedValue ); case TABLE -> handleTableStrategy( generatedValue );
case AUTO -> handleAutoStrategy( generatedValue ); case AUTO -> handleAutoStrategy( generatedValue );
@ -94,10 +97,11 @@ private void handleSequenceStrategy(GeneratedValue generatedValue) {
} }
private void handleUnnamedSequenceGenerator() { private void handleUnnamedSequenceGenerator() {
final InFlightMetadataCollector metadataCollector = buildingContext.getMetadataCollector();
// according to the spec, this should locate a generator with the same name as the entity-name // according to the spec, this should locate a generator with the same name as the entity-name
final SequenceGeneratorRegistration globalMatch = buildingContext.getMetadataCollector() final SequenceGeneratorRegistration globalMatch =
.getGlobalRegistrations() metadataCollector.getGlobalRegistrations().getSequenceGeneratorRegistrations()
.getSequenceGeneratorRegistrations()
.get( entityMapping.getJpaEntityName() ); .get( entityMapping.getJpaEntityName() );
if ( globalMatch != null ) { if ( globalMatch != null ) {
handleSequenceGenerator( handleSequenceGenerator(
@ -113,7 +117,7 @@ private void handleUnnamedSequenceGenerator() {
handleSequenceGenerator( handleSequenceGenerator(
entityMapping.getJpaEntityName(), entityMapping.getJpaEntityName(),
new SequenceGeneratorJpaAnnotation( buildingContext.getMetadataCollector().getSourceModelBuildingContext() ), new SequenceGeneratorJpaAnnotation( metadataCollector.getSourceModelBuildingContext() ),
entityMapping, entityMapping,
idValue, idValue,
idMember, idMember,
@ -122,10 +126,11 @@ private void handleUnnamedSequenceGenerator() {
} }
private void handleNamedSequenceGenerator(GeneratedValue generatedValue) { private void handleNamedSequenceGenerator(GeneratedValue generatedValue) {
final SequenceGeneratorRegistration globalMatch = buildingContext.getMetadataCollector() final InFlightMetadataCollector metadataCollector = buildingContext.getMetadataCollector();
.getGlobalRegistrations()
.getSequenceGeneratorRegistrations() final SequenceGeneratorRegistration globalMatch =
.get( generatedValue.generator() ); metadataCollector.getGlobalRegistrations()
.getSequenceGeneratorRegistrations().get( generatedValue.generator() );
if ( globalMatch != null ) { if ( globalMatch != null ) {
handleSequenceGenerator( handleSequenceGenerator(
generatedValue.generator(), generatedValue.generator(),
@ -140,7 +145,7 @@ private void handleNamedSequenceGenerator(GeneratedValue generatedValue) {
handleSequenceGenerator( handleSequenceGenerator(
generatedValue.generator(), generatedValue.generator(),
new SequenceGeneratorJpaAnnotation( generatedValue.generator(), buildingContext.getMetadataCollector().getSourceModelBuildingContext() ), new SequenceGeneratorJpaAnnotation( generatedValue.generator(), metadataCollector.getSourceModelBuildingContext() ),
entityMapping, entityMapping,
idValue, idValue,
idMember, idMember,
@ -158,9 +163,10 @@ private void handleTableStrategy(GeneratedValue generatedValue) {
} }
private void handleUnnamedTableGenerator() { private void handleUnnamedTableGenerator() {
final TableGeneratorRegistration globalMatch = buildingContext.getMetadataCollector() final InFlightMetadataCollector metadataCollector = buildingContext.getMetadataCollector();
.getGlobalRegistrations()
.getTableGeneratorRegistrations() final TableGeneratorRegistration globalMatch =
metadataCollector.getGlobalRegistrations().getTableGeneratorRegistrations()
.get( entityMapping.getJpaEntityName() ); .get( entityMapping.getJpaEntityName() );
if ( globalMatch != null ) { if ( globalMatch != null ) {
handleTableGenerator( handleTableGenerator(
@ -168,7 +174,6 @@ private void handleUnnamedTableGenerator() {
globalMatch.configuration(), globalMatch.configuration(),
entityMapping, entityMapping,
idValue, idValue,
idMember,
buildingContext buildingContext
); );
return; return;
@ -176,18 +181,18 @@ private void handleUnnamedTableGenerator() {
handleTableGenerator( handleTableGenerator(
entityMapping.getJpaEntityName(), entityMapping.getJpaEntityName(),
new TableGeneratorJpaAnnotation( buildingContext.getMetadataCollector().getSourceModelBuildingContext() ), new TableGeneratorJpaAnnotation( metadataCollector.getSourceModelBuildingContext() ),
entityMapping, entityMapping,
idValue, idValue,
idMember,
buildingContext buildingContext
); );
} }
private void handleNamedTableGenerator(GeneratedValue generatedValue) { private void handleNamedTableGenerator(GeneratedValue generatedValue) {
final TableGeneratorRegistration globalMatch = buildingContext.getMetadataCollector() final InFlightMetadataCollector metadataCollector = buildingContext.getMetadataCollector();
.getGlobalRegistrations()
.getTableGeneratorRegistrations() final TableGeneratorRegistration globalMatch =
metadataCollector.getGlobalRegistrations().getTableGeneratorRegistrations()
.get( generatedValue.generator() ); .get( generatedValue.generator() );
if ( globalMatch != null ) { if ( globalMatch != null ) {
handleTableGenerator( handleTableGenerator(
@ -195,7 +200,6 @@ private void handleNamedTableGenerator(GeneratedValue generatedValue) {
globalMatch.configuration(), globalMatch.configuration(),
entityMapping, entityMapping,
idValue, idValue,
idMember,
buildingContext buildingContext
); );
@ -204,27 +208,22 @@ private void handleNamedTableGenerator(GeneratedValue generatedValue) {
handleTableGenerator( handleTableGenerator(
generatedValue.generator(), generatedValue.generator(),
new TableGeneratorJpaAnnotation( generatedValue.generator(), buildingContext.getMetadataCollector().getSourceModelBuildingContext() ), new TableGeneratorJpaAnnotation( generatedValue.generator(), metadataCollector.getSourceModelBuildingContext() ),
entityMapping, entityMapping,
idValue, idValue,
idMember,
buildingContext buildingContext
); );
} }
private void handleAutoStrategy(GeneratedValue generatedValue) { private void handleAutoStrategy(GeneratedValue generatedValue) {
final String globalRegistrationName; final String generator = generatedValue.generator();
if ( generatedValue.generator().isEmpty() ) { final String globalRegistrationName = generator.isEmpty() ? entityMapping.getJpaEntityName() : generator;
globalRegistrationName = entityMapping.getJpaEntityName();
}
else {
globalRegistrationName = generatedValue.generator();
}
final SequenceGeneratorRegistration globalSequenceMatch = buildingContext.getMetadataCollector() final InFlightMetadataCollector metadataCollector = buildingContext.getMetadataCollector();
.getGlobalRegistrations() final GlobalRegistrations globalRegistrations = metadataCollector.getGlobalRegistrations();
.getSequenceGeneratorRegistrations()
.get( globalRegistrationName ); final SequenceGeneratorRegistration globalSequenceMatch =
globalRegistrations.getSequenceGeneratorRegistrations().get( globalRegistrationName );
if ( globalSequenceMatch != null ) { if ( globalSequenceMatch != null ) {
handleSequenceGenerator( handleSequenceGenerator(
globalRegistrationName, globalRegistrationName,
@ -237,33 +236,27 @@ private void handleAutoStrategy(GeneratedValue generatedValue) {
return; return;
} }
final TableGeneratorRegistration globalTableMatch = buildingContext.getMetadataCollector() final TableGeneratorRegistration globalTableMatch =
.getGlobalRegistrations() globalRegistrations.getTableGeneratorRegistrations().get( globalRegistrationName );
.getTableGeneratorRegistrations()
.get( globalRegistrationName );
if ( globalTableMatch != null ) { if ( globalTableMatch != null ) {
handleTableGenerator( handleTableGenerator(
globalRegistrationName, globalRegistrationName,
globalTableMatch.configuration(), globalTableMatch.configuration(),
entityMapping, entityMapping,
idValue, idValue,
idMember,
buildingContext buildingContext
); );
return; return;
} }
final GenericGeneratorRegistration globalGenericMatch = buildingContext.getMetadataCollector() final GenericGeneratorRegistration globalGenericMatch =
.getGlobalRegistrations() globalRegistrations.getGenericGeneratorRegistrations().get( globalRegistrationName );
.getGenericGeneratorRegistrations()
.get( globalRegistrationName );
if ( globalGenericMatch != null ) { if ( globalGenericMatch != null ) {
handleGenericGenerator( handleGenericGenerator(
globalRegistrationName, globalRegistrationName,
globalGenericMatch.configuration(), globalGenericMatch.configuration(),
entityMapping, entityMapping,
idValue, idValue,
idMember,
buildingContext buildingContext
); );
return; return;
@ -271,21 +264,20 @@ private void handleAutoStrategy(GeneratedValue generatedValue) {
// Implicit handling of UUID generation // Implicit handling of UUID generation
if ( idMember.getType().isImplementor( UUID.class ) if ( idMember.getType().isImplementor( UUID.class )
|| idMember.getType().isImplementor( String.class )) { || idMember.getType().isImplementor( String.class ) ) {
handleUuidStrategy( idValue, idMember, buildingContext ); handleUuidStrategy( idValue, idMember, buildingContext );
return; return;
} }
// Handle a few legacy Hibernate generators... // Handle a few legacy Hibernate generators...
if ( !generatedValue.generator().isEmpty() ) { if ( !generator.isEmpty() ) {
final Class<? extends Generator> legacyNamedGenerator = GeneratorStrategies.mapLegacyNamedGenerator( generatedValue.generator(), idValue ); final Class<? extends Generator> legacyNamedGenerator = mapLegacyNamedGenerator( generator, idValue );
if ( legacyNamedGenerator != null ) { if ( legacyNamedGenerator != null ) {
final Map<String,String> configuration = buildLegacyGeneratorConfig(); final Map<String,String> configuration = buildLegacyGeneratorConfig();
//noinspection unchecked,rawtypes //noinspection unchecked,rawtypes
GeneratorBinder.createGeneratorFrom( GeneratorBinder.createGeneratorFrom(
new IdentifierGeneratorDefinition( generatedValue.generator(), legacyNamedGenerator.getName(), configuration ), new IdentifierGeneratorDefinition( generator, legacyNamedGenerator.getName(), configuration ),
idMember,
idValue, idValue,
(Map) configuration, (Map) configuration,
buildingContext buildingContext
@ -296,7 +288,7 @@ private void handleAutoStrategy(GeneratedValue generatedValue) {
handleSequenceGenerator( handleSequenceGenerator(
globalRegistrationName, globalRegistrationName,
new SequenceGeneratorJpaAnnotation( generatedValue.generator(), buildingContext.getMetadataCollector().getSourceModelBuildingContext() ), new SequenceGeneratorJpaAnnotation( generator, metadataCollector.getSourceModelBuildingContext() ),
entityMapping, entityMapping,
idValue, idValue,
idMember, idMember,
@ -348,14 +340,12 @@ public static void handleSequenceGenerator(
configuration.put( GENERATOR_NAME, generatorName ); configuration.put( GENERATOR_NAME, generatorName );
} }
else { else {
SequenceStyleGenerator.applyConfiguration( generatorConfig, idValue, configuration::put ); SequenceStyleGenerator.applyConfiguration( generatorConfig, configuration::put );
} }
GeneratorBinder.createGeneratorFrom( GeneratorBinder.createGeneratorFrom(
new IdentifierGeneratorDefinition( generatorName, SequenceStyleGenerator.class.getName(), configuration ), new IdentifierGeneratorDefinition( generatorName, SequenceStyleGenerator.class.getName(), configuration ),
idMember,
idValue, idValue,
entityMapping,
context context
); );

View File

@ -8,12 +8,15 @@
import org.hibernate.Incubating; import org.hibernate.Incubating;
import org.hibernate.boot.model.relational.Database; import org.hibernate.boot.model.relational.Database;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property; import org.hibernate.mapping.Property;
import org.hibernate.mapping.RootClass; import org.hibernate.mapping.RootClass;
import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.Type; import org.hibernate.type.Type;
import static org.hibernate.boot.model.relational.internal.SqlStringGenerationContextImpl.fromExplicit;
/** /**
* Access to information useful during {@linkplain Generator} creation and initialization. * Access to information useful during {@linkplain Generator} creation and initialization.
* *
@ -65,4 +68,9 @@ public interface GeneratorCreationContext {
default Type getType() { default Type getType() {
return getProperty().getType(); return getProperty().getType();
} }
default SqlStringGenerationContext getSqlStringGenerationContext() {
final Database database = getDatabase();
return fromExplicit( database.getJdbcEnvironment(), database, getDefaultCatalog(), getDefaultSchema() );
}
} }

View File

@ -31,7 +31,6 @@
import org.hibernate.id.PersistentIdentifierGenerator; import org.hibernate.id.PersistentIdentifierGenerator;
import org.hibernate.id.SequenceMismatchStrategy; import org.hibernate.id.SequenceMismatchStrategy;
import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.mapping.SimpleValue;
import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistry;
import org.hibernate.tool.schema.Action; import org.hibernate.tool.schema.Action;
import org.hibernate.tool.schema.extract.spi.SequenceInformation; import org.hibernate.tool.schema.extract.spi.SequenceInformation;
@ -206,7 +205,7 @@ public void configure(GeneratorCreationContext creationContext, Properties param
this.identifierType = creationContext.getType(); this.identifierType = creationContext.getType();
final QualifiedName sequenceName = determineSequenceName( parameters, dialect, jdbcEnvironment, serviceRegistry ); final QualifiedName sequenceName = determineSequenceName( parameters, jdbcEnvironment, serviceRegistry );
final int initialValue = determineInitialValue( parameters ); final int initialValue = determineInitialValue( parameters );
int incrementSize = determineIncrementSize( parameters ); int incrementSize = determineIncrementSize( parameters );
final OptimizerDescriptor optimizationStrategy = determineOptimizationStrategy( parameters, incrementSize ); final OptimizerDescriptor optimizationStrategy = determineOptimizationStrategy( parameters, incrementSize );
@ -330,14 +329,12 @@ public void initialize(SqlStringGenerationContext context) {
* Called during {@linkplain #configure configuration}. * Called during {@linkplain #configure configuration}.
* *
* @param params The params supplied in the generator config (plus some standard useful extras). * @param params The params supplied in the generator config (plus some standard useful extras).
* @param dialect The dialect in effect
* @param jdbcEnv The JdbcEnvironment * @param jdbcEnv The JdbcEnvironment
* @return The sequence name * @return The sequence name
*/ */
@SuppressWarnings("UnusedParameters") @SuppressWarnings("UnusedParameters")
protected QualifiedName determineSequenceName( protected QualifiedName determineSequenceName(
Properties params, Properties params,
Dialect dialect,
JdbcEnvironment jdbcEnv, JdbcEnvironment jdbcEnv,
ServiceRegistry serviceRegistry) { ServiceRegistry serviceRegistry) {
final IdentifierHelper identifierHelper = jdbcEnv.getIdentifierHelper(); final IdentifierHelper identifierHelper = jdbcEnv.getIdentifierHelper();
@ -587,7 +584,7 @@ private static boolean isDefaultSchema(JdbcEnvironment jdbcEnvironment, Identifi
&& ( schema == null || schema.equals( jdbcEnvironment.getCurrentSchema() ) ); && ( schema == null || schema.equals( jdbcEnvironment.getCurrentSchema() ) );
} }
public static void applyConfiguration(SequenceGenerator generatorConfig, SimpleValue idValue, BiConsumer<String,String> configCollector) { public static void applyConfiguration(SequenceGenerator generatorConfig, BiConsumer<String,String> configCollector) {
if ( !generatorConfig.sequenceName().isEmpty() ) { if ( !generatorConfig.sequenceName().isEmpty() ) {
configCollector.accept( SEQUENCE_PARAM, generatorConfig.sequenceName() ); configCollector.accept( SEQUENCE_PARAM, generatorConfig.sequenceName() );
} }

View File

@ -45,7 +45,6 @@
import org.hibernate.jdbc.AbstractReturningWork; import org.hibernate.jdbc.AbstractReturningWork;
import org.hibernate.mapping.Column; import org.hibernate.mapping.Column;
import org.hibernate.mapping.PrimaryKey; import org.hibernate.mapping.PrimaryKey;
import org.hibernate.mapping.SimpleValue;
import org.hibernate.mapping.Table; import org.hibernate.mapping.Table;
import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.BasicTypeRegistry; import org.hibernate.type.BasicTypeRegistry;
@ -728,14 +727,6 @@ public void initialize(SqlStringGenerationContext context) {
public static void applyConfiguration( public static void applyConfiguration(
jakarta.persistence.TableGenerator generatorConfig, jakarta.persistence.TableGenerator generatorConfig,
SimpleValue idValue,
Map<String, String> configuration) {
applyConfiguration( generatorConfig, idValue, configuration::put );
}
public static void applyConfiguration(
jakarta.persistence.TableGenerator generatorConfig,
SimpleValue idValue,
BiConsumer<String, String> configurationCollector) { BiConsumer<String, String> configurationCollector) {
configurationCollector.accept( CONFIG_PREFER_SEGMENT_PER_ENTITY, "true" ); configurationCollector.accept( CONFIG_PREFER_SEGMENT_PER_ENTITY, "true" );

View File

@ -73,10 +73,9 @@
import org.hibernate.jpa.internal.ExceptionMapperLegacyJpaImpl; import org.hibernate.jpa.internal.ExceptionMapperLegacyJpaImpl;
import org.hibernate.jpa.internal.PersistenceUnitUtilImpl; import org.hibernate.jpa.internal.PersistenceUnitUtilImpl;
import org.hibernate.mapping.Collection; import org.hibernate.mapping.Collection;
import org.hibernate.mapping.KeyValue; import org.hibernate.mapping.GeneratorSettings;
import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.RootClass; import org.hibernate.mapping.RootClass;
import org.hibernate.mapping.SimpleValue;
import org.hibernate.metamodel.internal.RuntimeMetamodelsImpl; import org.hibernate.metamodel.internal.RuntimeMetamodelsImpl;
import org.hibernate.metamodel.mapping.JdbcMapping; import org.hibernate.metamodel.mapping.JdbcMapping;
import org.hibernate.metamodel.model.domain.internal.MappingMetamodelImpl; import org.hibernate.metamodel.model.domain.internal.MappingMetamodelImpl;
@ -264,7 +263,7 @@ public SessionFactoryImpl(
try { try {
integrate( bootMetamodel, bootstrapContext, integratorObserver ); integrate( bootMetamodel, bootstrapContext, integratorObserver );
identifierGenerators = createGenerators( jdbcServices, sqlStringGenerationContext, bootMetamodel ); identifierGenerators = createGenerators( jdbcServices, bootMetamodel, options );
bootMetamodel.orderColumns( false ); bootMetamodel.orderColumns( false );
bootMetamodel.validate(); bootMetamodel.validate();
@ -415,26 +414,34 @@ public ServiceRegistry getServiceRegistry() {
}; };
} }
private static Map<String, Generator> createGenerators( private Map<String, Generator> createGenerators(
JdbcServices jdbcServices, JdbcServices jdbcServices, MetadataImplementor metamodel, SessionFactoryOptions options) {
SqlStringGenerationContext sqlStringGenerationContext,
MetadataImplementor bootMetamodel) {
final Dialect dialect = jdbcServices.getJdbcEnvironment().getDialect(); final Dialect dialect = jdbcServices.getJdbcEnvironment().getDialect();
final Map<String, Generator> generators = new HashMap<>(); final Map<String, Generator> generators = new HashMap<>();
for ( PersistentClass model : bootMetamodel.getEntityBindings() ) { for ( PersistentClass model : metamodel.getEntityBindings() ) {
if ( !model.isInherited() ) { if ( model instanceof RootClass rootClass ) {
final KeyValue id = model.getIdentifier();
final Generator generator = final Generator generator =
id.createGenerator( dialect, (RootClass) model, model.getIdentifierProperty() ); model.getIdentifier()
// returns the cached Generator if it was already created
.createGenerator( dialect, rootClass, model.getIdentifierProperty(),
new GeneratorSettings() {
@Override
public String getDefaultCatalog() {
return options.getDefaultCatalog();
}
@Override
public String getDefaultSchema() {
return options.getDefaultSchema();
}
} );
// the cached generator might have been created from
// InFlightMetadataCollectorImpl.handleIdentifierValueBinding,
// in which case it did not have access to the property-configured
// default catalog and schema, so re-render SQL here
if ( generator instanceof Configurable configurable ) { if ( generator instanceof Configurable configurable ) {
configurable.initialize( sqlStringGenerationContext ); configurable.initialize( sqlStringGenerationContext );
} }
//TODO: this isn't a great place to do this
if ( generator.allowAssignedIdentifiers()
&& id instanceof SimpleValue simpleValue
&& simpleValue.getNullValue() == null ) {
simpleValue.setNullValue( "undefined" );
}
generators.put( model.getEntityName(), generator ); generators.put( model.getEntityName(), generator );
} }
} }

View File

@ -651,17 +651,17 @@ public String toString() {
} }
@Override @Override
public Generator createGenerator(Dialect dialect, RootClass rootClass, Property property) { public Generator createGenerator(Dialect dialect, RootClass rootClass, Property property, GeneratorSettings defaults) {
if ( builtIdentifierGenerator == null ) { if ( builtIdentifierGenerator == null ) {
builtIdentifierGenerator = builtIdentifierGenerator =
getCustomIdGeneratorCreator().isAssigned() getCustomIdGeneratorCreator().isAssigned()
? buildIdentifierGenerator( dialect, rootClass ) ? buildIdentifierGenerator( dialect, rootClass, defaults )
: super.createGenerator( dialect, rootClass, property ); : super.createGenerator( dialect, rootClass, property, defaults );
} }
return builtIdentifierGenerator; return builtIdentifierGenerator;
} }
private Generator buildIdentifierGenerator(Dialect dialect, RootClass rootClass) { private Generator buildIdentifierGenerator(Dialect dialect, RootClass rootClass, GeneratorSettings defaults) {
final CompositeNestedGeneratedValueGenerator generator = final CompositeNestedGeneratedValueGenerator generator =
new CompositeNestedGeneratedValueGenerator( new CompositeNestedGeneratedValueGenerator(
new StandardGenerationContextLocator( rootClass.getEntityName() ), new StandardGenerationContextLocator( rootClass.getEntityName() ),
@ -675,7 +675,7 @@ private Generator buildIdentifierGenerator(Dialect dialect, RootClass rootClass)
if ( !value.getCustomIdGeneratorCreator().isAssigned() ) { if ( !value.getCustomIdGeneratorCreator().isAssigned() ) {
// skip any 'assigned' generators, they would have been // skip any 'assigned' generators, they would have been
// handled by the StandardGenerationContextLocator // handled by the StandardGenerationContextLocator
if ( value.createGenerator( dialect, rootClass, property ) if ( value.createGenerator( dialect, rootClass, property, defaults )
instanceof BeforeExecutionGenerator beforeExecutionGenerator ) { instanceof BeforeExecutionGenerator beforeExecutionGenerator ) {
generator.addGeneratedValuePlan( new ValueGenerationPlan( generator.addGeneratedValuePlan( new ValueGenerationPlan(
beforeExecutionGenerator, beforeExecutionGenerator,

View File

@ -0,0 +1,14 @@
/*
* SPDX-License-Identifier: LGPL-2.1-or-later
* Copyright Red Hat Inc. and Hibernate Authors
*/
package org.hibernate.mapping;
/**
* @author Gavin King
*/
public interface GeneratorSettings {
String getDefaultCatalog();
String getDefaultSchema();
}

View File

@ -27,9 +27,12 @@ public interface KeyValue extends Value {
@Deprecated(since = "7.0") @Deprecated(since = "7.0")
default Generator createGenerator(Dialect dialect, RootClass rootClass) { default Generator createGenerator(Dialect dialect, RootClass rootClass) {
return createGenerator( dialect, rootClass, null ); return createGenerator( dialect, rootClass, null, null );
} }
Generator createGenerator(Dialect dialect, RootClass rootClass, Property property); Generator createGenerator(
Dialect dialect,
RootClass rootClass,
Property property,
GeneratorSettings defaults);
} }

View File

@ -13,6 +13,7 @@
import org.hibernate.Internal; import org.hibernate.Internal;
import org.hibernate.MappingException; import org.hibernate.MappingException;
import org.hibernate.boot.model.relational.Database; import org.hibernate.boot.model.relational.Database;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.bytecode.enhance.spi.interceptor.EnhancementHelper; import org.hibernate.bytecode.enhance.spi.interceptor.EnhancementHelper;
import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.AvailableSettings;
import org.hibernate.engine.spi.CascadeStyle; import org.hibernate.engine.spi.CascadeStyle;
@ -31,7 +32,6 @@
import org.hibernate.type.AnyType; import org.hibernate.type.AnyType;
import org.hibernate.type.CollectionType; import org.hibernate.type.CollectionType;
import org.hibernate.type.ComponentType; import org.hibernate.type.ComponentType;
import org.hibernate.type.CompositeType;
import org.hibernate.type.Type; import org.hibernate.type.Type;
import org.hibernate.type.WrapperArrayHandling; import org.hibernate.type.WrapperArrayHandling;
import org.hibernate.type.MappingContext; import org.hibernate.type.MappingContext;
@ -129,8 +129,7 @@ public void resetUpdateable(boolean updateable) {
public void resetOptional(boolean optional) { public void resetOptional(boolean optional) {
setOptional( optional ); setOptional( optional );
for ( Selectable selectable: getValue().getSelectables() ) { for ( Selectable selectable: getValue().getSelectables() ) {
if (selectable instanceof Column) { if ( selectable instanceof Column column ) {
final Column column = (Column) selectable;
column.setNullable( optional ); column.setNullable( optional );
} }
} }
@ -152,15 +151,15 @@ else if ( type instanceof CollectionType ) {
return getCascadeStyle( cascade ); return getCascadeStyle( cascade );
} }
} }
//
private static CascadeStyle getCompositeCascadeStyle(CompositeType compositeType, String cascade) { // private static CascadeStyle getCompositeCascadeStyle(CompositeType compositeType, String cascade) {
if ( compositeType instanceof AnyType ) { // if ( compositeType instanceof AnyType ) {
return getCascadeStyle( cascade ); // return getCascadeStyle( cascade );
} // }
else { // else {
return getCompositeCascadeStyle( (ComponentType) compositeType, cascade ); // return getCompositeCascadeStyle( (ComponentType) compositeType, cascade );
} // }
} // }
private static CascadeStyle getCompositeCascadeStyle(ComponentType compositeType, String cascade) { private static CascadeStyle getCompositeCascadeStyle(ComponentType compositeType, String cascade) {
final int length = compositeType.getSubtypes().length; final int length = compositeType.getSubtypes().length;
@ -543,5 +542,10 @@ public RootClass getRootClass() {
public Property getProperty() { public Property getProperty() {
return Property.this; return Property.this;
} }
@Override
public SqlStringGenerationContext getSqlStringGenerationContext() {
return context.getSqlStringGenerationContext();
}
} }
} }

View File

@ -376,10 +376,19 @@ public GeneratorCreator getCustomIdGeneratorCreator() {
} }
@Override @Override
public Generator createGenerator(Dialect dialect, RootClass rootClass, Property property) { public Generator createGenerator(
Dialect dialect,
RootClass rootClass,
Property property,
GeneratorSettings defaults) {
if ( generator == null ) { if ( generator == null ) {
if ( customIdGeneratorCreator != null ) { if ( customIdGeneratorCreator != null ) {
generator = customIdGeneratorCreator.createGenerator( new IdGeneratorCreationContext( rootClass, property ) ); final IdGeneratorCreationContext context =
new IdGeneratorCreationContext( rootClass, property, defaults );
generator = customIdGeneratorCreator.createGenerator( context );
if ( generator.allowAssignedIdentifiers() && getNullValue() == null ) {
setNullValue( "undefined" );
}
} }
} }
return generator; return generator;
@ -903,8 +912,7 @@ public DynamicParameterizedType.ParameterType makeParameterImpl() {
for ( int i = 0; i < columns.size(); i++ ) { for ( int i = 0; i < columns.size(); i++ ) {
final Selectable selectable = columns.get(i); final Selectable selectable = columns.get(i);
if ( selectable instanceof Column ) { if ( selectable instanceof Column column ) {
final Column column = (Column) selectable;
columnNames[i] = column.getName(); columnNames[i] = column.getName();
columnLengths[i] = column.getLength(); columnLengths[i] = column.getLength();
} }
@ -1029,10 +1037,12 @@ public Long[] getColumnLengths() {
private class IdGeneratorCreationContext implements GeneratorCreationContext { private class IdGeneratorCreationContext implements GeneratorCreationContext {
private final RootClass rootClass; private final RootClass rootClass;
private final Property property; private final Property property;
private final GeneratorSettings defaults;
public IdGeneratorCreationContext(RootClass rootClass, Property property) { public IdGeneratorCreationContext(RootClass rootClass, Property property, GeneratorSettings defaults) {
this.rootClass = rootClass; this.rootClass = rootClass;
this.property = property; this.property = property;
this.defaults = defaults;
} }
@Override @Override
@ -1047,12 +1057,12 @@ public ServiceRegistry getServiceRegistry() {
@Override @Override
public String getDefaultCatalog() { public String getDefaultCatalog() {
return buildingContext.getEffectiveDefaults().getDefaultCatalogName(); return defaults.getDefaultCatalog();
} }
@Override @Override
public String getDefaultSchema() { public String getDefaultSchema() {
return buildingContext.getEffectiveDefaults().getDefaultSchemaName(); return defaults.getDefaultSchema();
} }
@Override @Override
@ -1075,7 +1085,7 @@ public Type getType() {
return SimpleValue.this.getType(); return SimpleValue.this.getType();
} }
// we could add these if it helps integrate old infrastructure // we could add this if it helps integrate old infrastructure
// @Override // @Override
// public Properties getParameters() { // public Properties getParameters() {
// final Value value = getProperty().getValue(); // final Value value = getProperty().getValue();
@ -1086,10 +1096,5 @@ public Type getType() {
// return collectParameters( (SimpleValue) value, dialect, defaultCatalog, defaultSchema, rootClass ); // return collectParameters( (SimpleValue) value, dialect, defaultCatalog, defaultSchema, rootClass );
// } // }
// //
// @Override
// public SqlStringGenerationContext getSqlStringGenerationContext() {
// final Database database = getDatabase();
// return fromExplicit( database.getJdbcEnvironment(), database, defaultCatalog, defaultSchema );
// }
} }
} }

View File

@ -47,7 +47,6 @@
import org.hibernate.engine.spi.SubselectFetch; import org.hibernate.engine.spi.SubselectFetch;
import org.hibernate.generator.BeforeExecutionGenerator; import org.hibernate.generator.BeforeExecutionGenerator;
import org.hibernate.generator.Generator; import org.hibernate.generator.Generator;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentifierGenerator; import org.hibernate.id.IdentifierGenerator;
import org.hibernate.internal.FilterAliasGenerator; import org.hibernate.internal.FilterAliasGenerator;
import org.hibernate.internal.FilterHelper; import org.hibernate.internal.FilterHelper;
@ -65,6 +64,7 @@
import org.hibernate.mapping.Collection; import org.hibernate.mapping.Collection;
import org.hibernate.mapping.Column; import org.hibernate.mapping.Column;
import org.hibernate.mapping.Formula; import org.hibernate.mapping.Formula;
import org.hibernate.mapping.GeneratorSettings;
import org.hibernate.mapping.IdentifierCollection; import org.hibernate.mapping.IdentifierCollection;
import org.hibernate.mapping.IndexedCollection; import org.hibernate.mapping.IndexedCollection;
import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.PersistentClass;
@ -594,13 +594,23 @@ else if ( indexedCollection instanceof org.hibernate.mapping.Map
} }
private BeforeExecutionGenerator createGenerator(RuntimeModelCreationContext context, IdentifierCollection collection) { private BeforeExecutionGenerator createGenerator(RuntimeModelCreationContext context, IdentifierCollection collection) {
final Generator generator = collection.getIdentifier().createGenerator( context.getDialect(), null, null ); final Generator generator =
collection.getIdentifier()
.createGenerator( context.getDialect(), null, null,
new GeneratorSettings() {
@Override
public String getDefaultCatalog() {
return context.getSessionFactoryOptions().getDefaultCatalog();
}
@Override
public String getDefaultSchema() {
return context.getSessionFactoryOptions().getDefaultCatalog();
}
} );
if ( generator.generatedOnExecution() ) { if ( generator.generatedOnExecution() ) {
throw new MappingException("must be an BeforeExecutionGenerator"); //TODO fix message throw new MappingException("must be an BeforeExecutionGenerator"); //TODO fix message
} }
if ( generator instanceof Configurable ) {
( (Configurable) generator ).initialize( context.getSqlStringGenerationContext() );
}
return (BeforeExecutionGenerator) generator; return (BeforeExecutionGenerator) generator;
} }

View File

@ -91,7 +91,8 @@ private void withGenerator(Class<?> entityClass, boolean strictlyGlobal, Consume
final Generator generator = entityBinding.getIdentifier().createGenerator( final Generator generator = entityBinding.getIdentifier().createGenerator(
metadata.getDatabase().getDialect(), metadata.getDatabase().getDialect(),
entityBinding, entityBinding,
entityBinding.getIdentifierProperty() entityBinding.getIdentifierProperty(),
null
); );
checks.accept( generator ); checks.accept( generator );

View File

@ -134,7 +134,7 @@ public void testUuid() {
final Property identifierProperty = entityBinding.getRootClass().getIdentifierProperty(); final Property identifierProperty = entityBinding.getRootClass().getIdentifierProperty();
final KeyValue idMapping = entityBinding.getRootClass().getIdentifier(); final KeyValue idMapping = entityBinding.getRootClass().getIdentifier();
Dialect dialect = new H2Dialect(); Dialect dialect = new H2Dialect();
final Generator generator = idMapping.createGenerator( dialect, entityBinding.getRootClass(), identifierProperty ); final Generator generator = idMapping.createGenerator( dialect, entityBinding.getRootClass(), identifierProperty, null );
MatcherAssert.assertThat( generator, instanceOf( UuidGenerator.class ) ); MatcherAssert.assertThat( generator, instanceOf( UuidGenerator.class ) );
} }
} }