HHH-18139 remove identifierGeneratorStrategy/identifierGeneratorParameters from SimpleValue

Signed-off-by: Gavin King <gavin@hibernate.org>
This commit is contained in:
Gavin King 2024-05-19 22:43:52 +02:00 committed by Steve Ebersole
parent c8c92cfcbf
commit 63ee06685c
18 changed files with 196 additions and 274 deletions

View File

@ -26,6 +26,8 @@
import static java.util.Collections.emptyMap;
import static java.util.Collections.unmodifiableMap;
import static org.hibernate.boot.internal.GenerationStrategyInterpreter.STRATEGY_INTERPRETER;
import static org.hibernate.boot.models.JpaAnnotations.SEQUENCE_GENERATOR;
import static org.hibernate.boot.models.JpaAnnotations.TABLE_GENERATOR;
import static org.hibernate.boot.models.internal.AnnotationUsageHelper.applyStringAttributeIfSpecified;
import static org.hibernate.internal.util.collections.CollectionHelper.isEmpty;
@ -123,7 +125,7 @@ public static IdentifierGeneratorDefinition createImplicit(
);
}
case AUTO: {
final String strategyName = GenerationStrategyInterpreter.STRATEGY_INTERPRETER.determineGeneratorName(
final String strategyName = STRATEGY_INTERPRETER.determineGeneratorName(
generationType,
new GenerationStrategyInterpreter.GeneratorNameDeterminationContext() {
@Override
@ -153,15 +155,15 @@ private static IdentifierGeneratorDefinition buildTableGeneratorDefinition(Strin
final Builder builder = new Builder();
final MutableAnnotationUsage<TableGenerator> tableGeneratorUsage = TABLE_GENERATOR.createUsage( null );
tableGeneratorUsage.setAttributeValue( "name", name );
GenerationStrategyInterpreter.STRATEGY_INTERPRETER.interpretTableGenerator( tableGeneratorUsage, builder );
STRATEGY_INTERPRETER.interpretTableGenerator( tableGeneratorUsage, builder );
return builder.build();
}
private static IdentifierGeneratorDefinition buildSequenceGeneratorDefinition(String name) {
final Builder builder = new Builder();
final MutableAnnotationUsage<SequenceGenerator> sequenceGeneratorUsage = JpaAnnotations.SEQUENCE_GENERATOR.createUsage( null );
final MutableAnnotationUsage<SequenceGenerator> sequenceGeneratorUsage = SEQUENCE_GENERATOR.createUsage( null );
applyStringAttributeIfSpecified( "name", name, sequenceGeneratorUsage );
GenerationStrategyInterpreter.STRATEGY_INTERPRETER.interpretSequenceGenerator( sequenceGeneratorUsage, builder );
STRATEGY_INTERPRETER.interpretSequenceGenerator( sequenceGeneratorUsage, builder );
return builder.build();
}

View File

@ -27,7 +27,6 @@
import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
import org.hibernate.boot.spi.InFlightMetadataCollector;
import org.hibernate.boot.spi.MetadataBuildingContext;
import org.hibernate.boot.spi.PropertyData;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.config.spi.ConfigurationService;
@ -77,11 +76,11 @@
import jakarta.persistence.TableGenerator;
import jakarta.persistence.Version;
import static java.util.Collections.emptyMap;
import static org.hibernate.boot.model.internal.AnnotationHelper.extractParameterMap;
import static org.hibernate.boot.model.internal.BinderHelper.isCompositeId;
import static org.hibernate.boot.model.internal.BinderHelper.isGlobalGeneratorNameGlobal;
import static org.hibernate.internal.util.ReflectHelper.getDefaultConstructor;
import static org.hibernate.internal.util.StringHelper.isNotEmpty;
import static org.hibernate.mapping.SimpleValue.DEFAULT_ID_GEN_STRATEGY;
public class GeneratorBinder {
@ -89,12 +88,12 @@ public class GeneratorBinder {
private static final Logger LOG = CoreLogging.logger( BinderHelper.class );
public static Generator createLegacyIdentifierGenerator(
String strategy,
SimpleValue simpleValue,
Dialect dialect,
String defaultCatalog,
String defaultSchema,
RootClass rootClass) {
final Class<? extends Generator> generatorClass = generatorClass( simpleValue );
RootClass rootClass,
Map<String, Object> configuration) {
final Class<? extends Generator> generatorClass = generatorClass( strategy, simpleValue );
final Constructor<? extends Generator> defaultConstructor = getDefaultConstructor( generatorClass );
if ( defaultConstructor == null ) {
throw new org.hibernate.InstantiationException( "No default constructor for id generator class", generatorClass );
@ -107,15 +106,14 @@ public static Generator createLegacyIdentifierGenerator(
throw new org.hibernate.InstantiationException( "Could not instantiate id generator", generatorClass, e );
}
if ( identifierGenerator instanceof Configurable ) {
final Properties parameters = collectParameters( simpleValue, dialect, defaultCatalog, defaultSchema, rootClass );
final Properties parameters = collectParameters( simpleValue, dialect, rootClass, configuration );
final Configurable configurable = (Configurable) identifierGenerator;
configurable.configure( simpleValue.getType(), parameters, simpleValue.getServiceRegistry() );
}
return identifierGenerator;
}
private static Class<? extends Generator> generatorClass(SimpleValue simpleValue) {
String strategy = simpleValue.getIdentifierGeneratorStrategy();
private static Class<? extends Generator> generatorClass(String strategy, SimpleValue simpleValue) {
if ( "native".equals(strategy) ) {
strategy =
simpleValue.getMetadata().getDatabase().getDialect()
@ -160,26 +158,14 @@ private static Class<? extends Generator> generatorClass(SimpleValue simpleValue
public static Properties collectParameters(
SimpleValue simpleValue,
Dialect dialect,
String defaultCatalog,
String defaultSchema,
RootClass rootClass) {
RootClass rootClass,
Map<String, Object> configuration) {
final ConfigurationService configService =
simpleValue.getMetadata().getMetadataBuildingOptions().getServiceRegistry()
.requireService( ConfigurationService.class );
final Properties params = new Properties();
// This is for backwards compatibility only;
// when this method is called by Hibernate ORM, defaultSchema and defaultCatalog are always
// null, and defaults are handled later.
if ( defaultSchema != null ) {
params.setProperty( PersistentIdentifierGenerator.SCHEMA, defaultSchema);
}
if ( defaultCatalog != null ) {
params.setProperty( PersistentIdentifierGenerator.CATALOG, defaultCatalog);
}
// default initial value and allocation size per-JPA defaults
params.setProperty( OptimizableGenerator.INITIAL_PARAM,
String.valueOf( OptimizableGenerator.DEFAULT_INITIAL_VALUE ) );
@ -216,12 +202,6 @@ public static Properties collectParameters(
params.setProperty( OptimizableGenerator.IMPLICIT_NAME_BASE, tableName );
}
if ( simpleValue.getIdentifierGeneratorParameters() != null ) {
params.putAll( simpleValue.getIdentifierGeneratorParameters() );
}
// TODO : we should pass along all settings once "config lifecycle" is hashed out...
params.put( IdentifierGenerator.CONTRIBUTOR_NAME,
simpleValue.getBuildingContext().getCurrentContributorName() );
@ -231,6 +211,8 @@ public static Properties collectParameters(
settings.get( AvailableSettings.PREFERRED_POOLED_OPTIMIZER ) );
}
params.putAll( configuration );
return params;
}
@ -238,7 +220,7 @@ private static String identityTablesString(Dialect dialect, RootClass rootClass)
final StringBuilder tables = new StringBuilder();
for ( Table table : rootClass.getIdentityTables() ) {
tables.append( table.getQuotedName( dialect ) );
if ( tables.length()>0 ) {
if ( !tables.isEmpty() ) {
tables.append( ", " );
}
}
@ -286,6 +268,7 @@ public static void makeIdGenerator(
parameters.put( PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER, buildingContext.getObjectNameNormalizer() );
parameters.put( IdentifierGenerator.GENERATOR_NAME, generatorName );
final String generatorStrategy;
if ( !generatorName.isEmpty() ) {
//we have a named generator
final IdentifierGeneratorDefinition definition =
@ -296,22 +279,24 @@ public static void makeIdGenerator(
+ " (define a named generator using '@SequenceGenerator', '@TableGenerator', or '@GenericGenerator')" );
}
//This is quite vague in the spec but a generator could override the generator choice
final String identifierGeneratorStrategy = definition.getStrategy();
//yuk! this is a hack not to override 'AUTO' even if generator is set
final boolean avoidOverriding =
identifierGeneratorStrategy.equals( "identity" )
|| identifierGeneratorStrategy.equals( "seqhilo" );
definition.getStrategy().equals( "identity" )
|| definition.getStrategy().equals( "seqhilo" );
if ( generatorType == null || !avoidOverriding ) {
generatorType = identifierGeneratorStrategy;
generatorStrategy = definition.getStrategy();
}
else {
generatorStrategy = generatorType;
}
//checkIfMatchingGenerator(definition, generatorType, generatorName);
parameters.putAll( definition.getParameters() );
}
id.setIdentifierGeneratorStrategy( generatorType );
id.setIdentifierGeneratorParameters( parameters );
if ( DEFAULT_ID_GEN_STRATEGY.equals( generatorType ) ) {
id.setNullValue( "undefined" );
else {
generatorStrategy = generatorType;
}
setGeneratorCreator( id, parameters, generatorStrategy );
}
/**
@ -701,9 +686,8 @@ private static void callConfigure(GeneratorCreationContext creationContext, Gene
Properties parameters = collectParameters(
(SimpleValue) value,
creationContext.getDatabase().getDialect(),
creationContext.getDefaultCatalog(),
creationContext.getDefaultSchema(),
creationContext.getPersistentClass().getRootClass()
creationContext.getPersistentClass().getRootClass(),
emptyMap()
);
( (Configurable) generator ).configure( value.getType(), parameters, creationContext.getServiceRegistry() );
}
@ -749,51 +733,67 @@ static void createIdGenerator(
}
}
static IdentifierGeneratorDefinition createForeignGenerator(PropertyData mapsIdProperty) {
final IdentifierGeneratorDefinition.Builder foreignGeneratorBuilder =
new IdentifierGeneratorDefinition.Builder();
foreignGeneratorBuilder.setName( "Hibernate-local--foreign generator" );
foreignGeneratorBuilder.setStrategy( "foreign" );
foreignGeneratorBuilder.addParam( "property", mapsIdProperty.getPropertyName() );
return foreignGeneratorBuilder.build();
}
public static void makeIdentifier(
/**
* Set up the identifier generator for an id defined in a {@code hbm.xml} mapping.
*
* @see org.hibernate.boot.model.source.internal.hbm.ModelBinder
*/
public static void makeIdGenerator(
final MappingDocument sourceDocument,
IdentifierGeneratorDefinition generator,
String unsavedValue,
IdentifierGeneratorDefinition definition,
SimpleValue identifierValue,
MetadataBuildingContext buildingContext) {
if ( generator != null ) {
if ( definition != null ) {
final Map<String,Object> params = new HashMap<>();
// see if the specified generator name matches a registered <identifier-generator/>
String generatorName = generator.getStrategy();
final IdentifierGeneratorDefinition generatorDef =
sourceDocument.getMetadataCollector().getIdentifierGenerator( generatorName );
sourceDocument.getMetadataCollector().getIdentifierGenerator( definition.getName() );
final String generatorStrategy;
if ( generatorDef != null ) {
generatorName = generatorDef.getStrategy();
generatorStrategy = generatorDef.getStrategy();
params.putAll( generatorDef.getParameters() );
}
else {
generatorStrategy = definition.getStrategy();
}
// YUCK! but cannot think of a clean way to do this given the string-config based scheme
params.put( PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER,
buildingContext.getObjectNameNormalizer() );
params.putAll( generator.getParameters() );
params.putAll( definition.getParameters() );
identifierValue.setIdentifierGeneratorStrategy( generatorName );
identifierValue.setIdentifierGeneratorParameters( params );
}
if ( isNotEmpty( unsavedValue ) ) {
identifierValue.setNullValue( unsavedValue );
}
else if ( DEFAULT_ID_GEN_STRATEGY.equals( identifierValue.getIdentifierGeneratorStrategy() ) ) {
identifierValue.setNullValue( "undefined" );
}
else {
identifierValue.setNullValue( null );
setGeneratorCreator( identifierValue, params, generatorStrategy );
}
}
private static void setGeneratorCreator(
SimpleValue identifierValue,
Map<String, Object> parameters,
String generatorStrategy) {
identifierValue.setCustomIdGeneratorCreator( new IdentifierGeneratorCreator() {
@Override
public Generator createGenerator(CustomIdGeneratorCreationContext context) {
final Generator generator =
createLegacyIdentifierGenerator(
generatorStrategy,
identifierValue,
context.getDatabase().getDialect(),
context.getRootClass(),
parameters
);
if ( generator instanceof IdentityGenerator) {
identifierValue.setColumnToIdentity();
}
return generator;
}
@Override
public boolean isAssigned() {
return DEFAULT_ID_GEN_STRATEGY.equals( generatorStrategy );
}
} );
}
}

View File

@ -131,8 +131,6 @@ else if ( "increment".equals( namedGenerator ) ) {
generatorName = namedGenerator;
}
id.setIdentifierGeneratorStrategy( generatorType );
if ( buildingContext.getBootstrapContext().getJpaCompliance().isGlobalGeneratorScopeEnabled() ) {
SecondPass secondPass = new IdGeneratorResolverSecondPass(
id,

View File

@ -7,7 +7,6 @@
package org.hibernate.boot.model.internal;
import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@ -38,6 +37,7 @@
import org.hibernate.boot.spi.MetadataBuildingContext;
import org.hibernate.boot.spi.PropertyData;
import org.hibernate.engine.OptimisticLockStyle;
import org.hibernate.id.ForeignGenerator;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.mapping.Collection;
import org.hibernate.mapping.Component;
@ -87,18 +87,16 @@
import static org.hibernate.boot.model.internal.BinderHelper.getPropertyOverriddenByMapperOrMapsId;
import static org.hibernate.boot.model.internal.BinderHelper.hasToOneAnnotation;
import static org.hibernate.boot.model.internal.BinderHelper.isCompositeId;
import static org.hibernate.boot.model.internal.BinderHelper.isGlobalGeneratorNameGlobal;
import static org.hibernate.boot.model.internal.ClassPropertyHolder.handleGenericComponentProperty;
import static org.hibernate.boot.model.internal.ClassPropertyHolder.prepareActualProperty;
import static org.hibernate.boot.model.internal.CollectionBinder.bindCollection;
import static org.hibernate.boot.model.internal.EmbeddableBinder.createCompositeBinder;
import static org.hibernate.boot.model.internal.EmbeddableBinder.createEmbeddable;
import static org.hibernate.boot.model.internal.EmbeddableBinder.isEmbedded;
import static org.hibernate.boot.model.internal.GeneratorBinder.createForeignGenerator;
import static org.hibernate.boot.model.internal.GeneratorBinder.createIdGenerator;
import static org.hibernate.boot.model.internal.GeneratorBinder.createLegacyIdentifierGenerator;
import static org.hibernate.boot.model.internal.GeneratorBinder.generatorCreator;
import static org.hibernate.boot.model.internal.GeneratorBinder.identifierGeneratorCreator;
import static org.hibernate.boot.model.internal.GeneratorBinder.makeIdGenerator;
import static org.hibernate.boot.model.internal.TimeZoneStorageHelper.resolveTimeZoneStorageCompositeUserType;
import static org.hibernate.boot.model.internal.ToOneBinder.bindManyToOne;
import static org.hibernate.boot.model.internal.ToOneBinder.bindOneToOne;
@ -1144,7 +1142,7 @@ && isEmbedded( property, property.getElementType() ) ) {
if ( isOverridden ) {
handleGeneratorsForOverriddenId(
propertyHolder,
classGenerators,
// classGenerators,
context,
property,
propertyBinder
@ -1175,7 +1173,7 @@ private static boolean isComposite(
private static void handleGeneratorsForOverriddenId(
PropertyHolder propertyHolder,
Map<String, IdentifierGeneratorDefinition> classGenerators,
// Map<String, IdentifierGeneratorDefinition> classGenerators,
MetadataBuildingContext context,
MemberDetails property,
PropertyBinder propertyBinder) {
@ -1185,30 +1183,17 @@ private static void handleGeneratorsForOverriddenId(
property.resolveAttributeName(),
context
);
final IdentifierGeneratorDefinition foreignGenerator = createForeignGenerator( mapsIdProperty );
if ( isGlobalGeneratorNameGlobal( context ) ) {
context.getMetadataCollector()
.addSecondPass( new IdGeneratorResolverSecondPass(
(SimpleValue) propertyBinder.getValue(),
property,
foreignGenerator.getStrategy(),
foreignGenerator.getName(),
context,
foreignGenerator
) );
}
else {
final Map<String, IdentifierGeneratorDefinition> generators = new HashMap<>( classGenerators );
generators.put( foreignGenerator.getName(), foreignGenerator );
makeIdGenerator(
(SimpleValue) propertyBinder.getValue(),
property,
foreignGenerator.getStrategy(),
foreignGenerator.getName(),
context,
generators
);
}
final SimpleValue idValue = (SimpleValue) propertyBinder.getValue();
final RootClass rootClass = propertyHolder.getPersistentClass().getRootClass();
final String propertyName = mapsIdProperty.getPropertyName();
idValue.setCustomIdGeneratorCreator( creationContext ->
createLegacyIdentifierGenerator( "foreign",
idValue,
creationContext.getDatabase().getDialect(),
rootClass,
Map.of( ForeignGenerator.PROPERTY, propertyName )
)
);
}
private static void createBasicBinder(

View File

@ -160,7 +160,7 @@
import org.hibernate.usertype.ParameterizedType;
import org.hibernate.usertype.UserType;
import static org.hibernate.boot.model.internal.GeneratorBinder.makeIdentifier;
import static org.hibernate.boot.model.internal.GeneratorBinder.makeIdGenerator;
import static org.hibernate.boot.model.naming.Identifier.toIdentifier;
import static org.hibernate.boot.model.source.internal.hbm.Helper.reflectedPropertyClass;
import static org.hibernate.cfg.AvailableSettings.USE_ENTITY_WHERE_CLAUSE_FOR_COLLECTIONS;
@ -739,13 +739,15 @@ public MetadataBuildingContext getBuildingContext() {
rootEntityDescriptor.setDeclaredIdentifierProperty( prop );
}
makeIdentifier(
makeIdGenerator(
sourceDocument,
idSource.getIdentifierGeneratorDescriptor(),
idSource.getUnsavedValue(),
idValue,
metadataBuildingContext
);
if ( isNotEmpty( idSource.getUnsavedValue() ) ) {
idValue.setNullValue( idSource.getUnsavedValue() );
}
}
private void bindAggregatedCompositeEntityIdentifier(
@ -900,10 +902,9 @@ private void finishBindingCompositeIdentifier(
rootEntityDescriptor.setDeclaredIdentifierProperty( prop );
}
makeIdentifier(
makeIdGenerator(
sourceDocument,
identifierSource.getIdentifierGeneratorDescriptor(),
null,
cid,
metadataBuildingContext
);
@ -3300,10 +3301,9 @@ protected void bindCollectionIdentifier() {
idBagBinding.setIdentifier( idBinding );
makeIdentifier(
makeIdGenerator(
mappingDocument,
new IdentifierGeneratorDefinition( idSource.getGeneratorName(), idSource.getParameters() ),
null,
idBinding,
metadataBuildingContext
);

View File

@ -55,20 +55,19 @@ else if ( idJtd instanceof PrimitiveJavaType ) {
return IdentifierValue.NULL;
}
}
else if ( "null".equals( unsavedValue ) ) {
return IdentifierValue.NULL;
}
else if ( "undefined".equals( unsavedValue ) ) {
return IdentifierValue.UNDEFINED;
}
else if ( "none".equals( unsavedValue ) ) {
return IdentifierValue.NONE;
}
else if ( "any".equals( unsavedValue ) ) {
return IdentifierValue.ANY;
}
else {
return new IdentifierValue( idJtd.fromString( unsavedValue ) );
switch (unsavedValue) {
case "null":
return IdentifierValue.NULL;
case "undefined":
return IdentifierValue.UNDEFINED;
case "none":
return IdentifierValue.NONE;
case "any":
return IdentifierValue.ANY;
default:
return new IdentifierValue( idJtd.fromString( unsavedValue ) );
}
}
}

View File

@ -26,6 +26,11 @@
public class Assigned implements IdentifierGenerator, StandardGenerator {
private String entityName;
@Override
public boolean allowAssignedIdentifiers() {
return true;
}
public Object generate(SharedSessionContractImplementor session, Object obj) throws HibernateException {
//TODO: cache the persister, this shows up in yourkit
final Object id = session.getEntityPersister( entityName, obj ).getIdentifier( obj, session );

View File

@ -24,6 +24,7 @@
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.engine.jdbc.env.spi.IdentifierHelper;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.BulkInsertionCapableIdentifierGenerator;
@ -325,19 +326,12 @@ protected QualifiedName determineSequenceName(
Dialect dialect,
JdbcEnvironment jdbcEnv,
ServiceRegistry serviceRegistry) {
final Identifier catalog = jdbcEnv.getIdentifierHelper().toIdentifier(
getString( CATALOG, params )
);
final Identifier schema = jdbcEnv.getIdentifierHelper().toIdentifier(
getString( SCHEMA, params )
);
final IdentifierHelper identifierHelper = jdbcEnv.getIdentifierHelper();
final String sequenceName = getString(
SEQUENCE_PARAM,
params,
() -> getString( ALT_SEQUENCE_PARAM, params )
);
final Identifier catalog = identifierHelper.toIdentifier( getString( CATALOG, params ) );
final Identifier schema = identifierHelper.toIdentifier( getString( SCHEMA, params ) );
final String sequenceName = getString( SEQUENCE_PARAM, params, () -> getString( ALT_SEQUENCE_PARAM, params ) );
if ( StringHelper.isNotEmpty( sequenceName ) ) {
// we have an explicit name, use it
if ( sequenceName.contains( "." ) ) {
@ -347,7 +341,7 @@ protected QualifiedName determineSequenceName(
return new QualifiedNameParser.NameParts(
catalog,
schema,
jdbcEnv.getIdentifierHelper().toIdentifier( sequenceName )
identifierHelper.toIdentifier( sequenceName )
);
}
}

View File

@ -29,6 +29,7 @@
import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.engine.config.spi.StandardConverters;
import org.hibernate.engine.jdbc.Size;
import org.hibernate.engine.jdbc.env.spi.IdentifierHelper;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.hibernate.engine.jdbc.internal.FormatStyle;
import org.hibernate.engine.jdbc.spi.SqlStatementLogger;
@ -380,22 +381,21 @@ private static OptimizerDescriptor determineOptimizationStrategy(Properties para
* @return The table name to use.
*/
protected QualifiedName determineGeneratorTableName(Properties params, JdbcEnvironment jdbcEnvironment, ServiceRegistry serviceRegistry) {
final IdentifierHelper identifierHelper = jdbcEnvironment.getIdentifierHelper();
final Identifier catalog = identifierHelper.toIdentifier( getString( CATALOG, params ) );
final Identifier schema = identifierHelper.toIdentifier( getString( SCHEMA, params ) );
final String explicitTableName = getString( TABLE_PARAM, params );
if ( StringHelper.isNotEmpty( explicitTableName ) ) {
if ( explicitTableName.contains( "." ) ) {
return QualifiedNameParser.INSTANCE.parse( explicitTableName );
}
else {
final Identifier catalog = jdbcEnvironment.getIdentifierHelper().toIdentifier(
getString( CATALOG, params )
);
final Identifier schema = jdbcEnvironment.getIdentifierHelper().toIdentifier(
getString( SCHEMA, params )
);
return new QualifiedNameParser.NameParts(
catalog,
schema,
jdbcEnvironment.getIdentifierHelper().toIdentifier( explicitTableName )
identifierHelper.toIdentifier( explicitTableName )
);
}
}
@ -426,14 +426,7 @@ protected QualifiedName determineGeneratorTableName(Properties params, JdbcEnvir
namingStrategySetting
);
final Identifier catalog = jdbcEnvironment.getIdentifierHelper().toIdentifier(
getString( CATALOG, params )
);
final Identifier schema = jdbcEnvironment.getIdentifierHelper().toIdentifier(
getString( SCHEMA, params )
);
return namingStrategy.determineTableName( catalog, schema, params, serviceRegistry );
return namingStrategy.determineTableName( catalog, schema, params, serviceRegistry );
}
/**

View File

@ -79,6 +79,7 @@
import org.hibernate.jpa.internal.ExceptionMapperLegacyJpaImpl;
import org.hibernate.jpa.internal.PersistenceUnitUtilImpl;
import org.hibernate.mapping.Collection;
import org.hibernate.mapping.KeyValue;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.RootClass;
import org.hibernate.mapping.SimpleValue;
@ -467,13 +468,18 @@ private static Map<String, Generator> createGenerators(
final Map<String, Generator> generators = new HashMap<>();
for ( PersistentClass model : bootMetamodel.getEntityBindings() ) {
if ( !model.isInherited() ) {
final Generator generator = model.getIdentifier().createGenerator( dialect, (RootClass) model );
if (generator instanceof Configurable) {
KeyValue id = model.getIdentifier();
final Generator generator = id.createGenerator( dialect, (RootClass) model );
if ( generator instanceof Configurable ) {
final Configurable identifierGenerator = (Configurable) generator;
identifierGenerator.initialize( sqlStringGenerationContext );
}
if ( generator.allowAssignedIdentifiers() ) {
( (SimpleValue) model.getIdentifier() ).setNullValue( "undefined" );
//TODO: this isn't a great place to do this
if ( generator.allowAssignedIdentifiers() && id instanceof SimpleValue ) {
SimpleValue simpleValue = (SimpleValue) id;
if ( simpleValue.getNullValue() == null ) {
simpleValue.setNullValue( "undefined" );
}
}
generators.put( model.getEntityName(), generator );
}

View File

@ -676,12 +676,38 @@ public Generator createGenerator(Dialect dialect, RootClass rootClass) throws Ma
}
private Generator buildIdentifierGenerator( Dialect dialect, RootClass rootClass) throws MappingException {
final boolean hasCustomGenerator = ! DEFAULT_ID_GEN_STRATEGY.equals( getIdentifierGeneratorStrategy() );
if ( hasCustomGenerator ) {
if ( !getCustomIdGeneratorCreator().isAssigned() ) {
return super.createGenerator( dialect, rootClass );
}
final Class<?> entityClass = rootClass.getMappedClass();
final Class<?> attributeDeclarer = getAttributeDeclarer( rootClass, entityClass );
final CompositeNestedGeneratedValueGenerator.GenerationContextLocator locator =
new StandardGenerationContextLocator( rootClass.getEntityName() );
final CompositeNestedGeneratedValueGenerator generator =
new CompositeNestedGeneratedValueGenerator( locator, getType() );
final List<Property> properties = getProperties();
for ( int i = 0; i < properties.size(); i++ ) {
final Property property = properties.get( i );
if ( property.getValue().isSimpleValue() ) {
final SimpleValue value = (SimpleValue) property.getValue();
if ( !value.getCustomIdGeneratorCreator().isAssigned() ) {
// skip any 'assigned' generators, they would have been handled by
// the StandardGenerationContextLocator
generator.addGeneratedValuePlan( new ValueGenerationPlan(
value.createGenerator( dialect, rootClass ),
getType().isMutable() ? injector( property, attributeDeclarer ) : null,
i
) );
}
}
}
return generator;
}
private Class<?> getAttributeDeclarer(RootClass rootClass, Class<?> entityClass) {
final Class<?> attributeDeclarer; // what class is the declarer of the composite pk attributes
// IMPL NOTE : See the javadoc discussion on CompositeNestedGeneratedValueGenerator wrt the
// various scenarios for which we need to account here
@ -697,30 +723,7 @@ else if ( rootClass.getIdentifierProperty() != null ) {
// we have the "straight up" embedded (again the Hibernate term) component identifier
attributeDeclarer = entityClass;
}
final CompositeNestedGeneratedValueGenerator.GenerationContextLocator locator =
new StandardGenerationContextLocator( rootClass.getEntityName() );
final CompositeNestedGeneratedValueGenerator generator =
new CompositeNestedGeneratedValueGenerator( locator, getType() );
final List<Property> properties = getProperties();
for ( int i = 0; i < properties.size(); i++ ) {
final Property property = properties.get( i );
if ( property.getValue().isSimpleValue() ) {
final SimpleValue value = (SimpleValue) property.getValue();
if ( !DEFAULT_ID_GEN_STRATEGY.equals( value.getIdentifierGeneratorStrategy() ) ) {
// skip any 'assigned' generators, they would have been handled by
// the StandardGenerationContextLocator
generator.addGeneratedValuePlan( new ValueGenerationPlan(
value.createGenerator( dialect, rootClass ),
getType().isMutable() ? injector( property, attributeDeclarer ) : null,
i
) );
}
}
}
return generator;
return attributeDeclarer;
}
private Setter injector(Property property, Class<?> attributeDeclarer) {

View File

@ -14,4 +14,7 @@
@FunctionalInterface
public interface IdentifierGeneratorCreator {
Generator createGenerator(CustomIdGeneratorCreationContext context);
default boolean isAssigned() {
return false;
}
}

View File

@ -11,7 +11,6 @@
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
@ -23,7 +22,6 @@
import org.hibernate.FetchMode;
import org.hibernate.Internal;
import org.hibernate.MappingException;
import org.hibernate.Remove;
import org.hibernate.TimeZoneStorageStrategy;
import org.hibernate.annotations.OnDeleteAction;
import org.hibernate.boot.model.convert.internal.ClassBasedConverterDescriptor;
@ -39,7 +37,7 @@
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.spi.Mapping;
import org.hibernate.generator.Generator;
import org.hibernate.id.IdentityGenerator;
import org.hibernate.id.Assigned;
import org.hibernate.id.factory.spi.CustomIdGeneratorCreationContext;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
@ -66,7 +64,6 @@
import static java.lang.Boolean.parseBoolean;
import static org.hibernate.boot.model.convert.spi.ConverterDescriptor.TYPE_NAME_PREFIX;
import static org.hibernate.boot.model.internal.GeneratorBinder.createLegacyIdentifierGenerator;
import static org.hibernate.internal.util.collections.ArrayHelper.toBooleanArray;
/**
@ -94,8 +91,6 @@ public abstract class SimpleValue implements KeyValue {
private boolean isNationalized;
private boolean isLob;
private Map<String,Object> identifierGeneratorParameters;
private String identifierGeneratorStrategy = DEFAULT_ID_GEN_STRATEGY;
private String nullValue;
private Table table;
@ -108,7 +103,17 @@ public abstract class SimpleValue implements KeyValue {
private ConverterDescriptor attributeConverterDescriptor;
private Type type;
private IdentifierGeneratorCreator customIdGeneratorCreator;
private IdentifierGeneratorCreator customIdGeneratorCreator = new IdentifierGeneratorCreator() {
@Override
public Generator createGenerator(CustomIdGeneratorCreationContext context) {
return new Assigned();
}
@Override
public boolean isAssigned() {
return true;
}
};
private Generator generator;
public SimpleValue(MetadataBuildingContext buildingContext) {
@ -133,8 +138,6 @@ protected SimpleValue(SimpleValue original) {
this.isVersion = original.isVersion;
this.isNationalized = original.isNationalized;
this.isLob = original.isLob;
this.identifierGeneratorParameters = original.identifierGeneratorParameters;
this.identifierGeneratorStrategy = original.identifierGeneratorStrategy;
this.nullValue = original.nullValue;
this.table = original.table;
this.foreignKeyName = original.foreignKeyName;
@ -390,24 +393,17 @@ public IdentifierGeneratorCreator getCustomIdGeneratorCreator() {
}
@Override
public Generator createGenerator(Dialect dialect, RootClass rootClass) throws MappingException {
public Generator createGenerator(Dialect dialect, RootClass rootClass) {
if ( generator == null ) {
if ( customIdGeneratorCreator != null ) {
generator = customIdGeneratorCreator.createGenerator(
new IdGeneratorCreationContext( null, null, rootClass )
);
}
else {
generator = createLegacyIdentifierGenerator( this, dialect, null, null, rootClass );
if ( generator instanceof IdentityGenerator ) {
setColumnToIdentity();
}
generator = customIdGeneratorCreator.createGenerator( new IdGeneratorCreationContext( rootClass ) );
}
}
return generator;
}
private void setColumnToIdentity() {
@Internal
public void setColumnToIdentity() {
if ( getColumnSpan() != 1 ) {
throw new MappingException( "Identity generation requires exactly one column" );
}
@ -433,61 +429,6 @@ public Table getTable() {
return table;
}
/**
* Returns the identifierGeneratorStrategy.
* @return String
*/
public String getIdentifierGeneratorStrategy() {
return identifierGeneratorStrategy;
}
/**
* Sets the identifierGeneratorStrategy.
* @param identifierGeneratorStrategy The identifierGeneratorStrategy to set
*/
public void setIdentifierGeneratorStrategy(String identifierGeneratorStrategy) {
this.identifierGeneratorStrategy = identifierGeneratorStrategy;
}
public Map<String, Object> getIdentifierGeneratorParameters() {
return identifierGeneratorParameters;
}
public void setIdentifierGeneratorParameters(Map<String, Object> identifierGeneratorParameters) {
this.identifierGeneratorParameters = identifierGeneratorParameters;
}
/**
* @deprecated use {@link #getIdentifierGeneratorParameters()}
*/
@Deprecated @Remove
public Properties getIdentifierGeneratorProperties() {
Properties properties = new Properties();
properties.putAll( identifierGeneratorParameters );
return properties;
}
/**
* @deprecated use {@link #setIdentifierGeneratorParameters(Map)}
*/
@Deprecated @Remove
public void setIdentifierGeneratorProperties(Properties identifierGeneratorProperties) {
this.identifierGeneratorParameters = new HashMap<>();
identifierGeneratorProperties.forEach((key, value) -> {
if (key instanceof String) {
identifierGeneratorParameters.put((String) key, value);
}
});
}
/**
* @deprecated use {@link #setIdentifierGeneratorParameters(Map)}
*/
@Deprecated @Remove
public void setIdentifierGeneratorProperties(Map<String,Object> identifierGeneratorProperties) {
this.identifierGeneratorParameters = identifierGeneratorProperties;
}
public String getNullValue() {
return nullValue;
}
@ -1100,13 +1041,9 @@ public Long[] getColumnLengths() {
}
private class IdGeneratorCreationContext implements CustomIdGeneratorCreationContext {
private final String defaultCatalog;
private final String defaultSchema;
private final RootClass rootClass;
public IdGeneratorCreationContext(String defaultCatalog, String defaultSchema, RootClass rootClass) {
this.defaultCatalog = defaultCatalog;
this.defaultSchema = defaultSchema;
public IdGeneratorCreationContext(RootClass rootClass) {
this.rootClass = rootClass;
}
@ -1122,12 +1059,12 @@ public ServiceRegistry getServiceRegistry() {
@Override
public String getDefaultCatalog() {
return defaultCatalog;
return buildingContext.getEffectiveDefaults().getDefaultCatalogName();
}
@Override
public String getDefaultSchema() {
return defaultSchema;
return buildingContext.getEffectiveDefaults().getDefaultSchemaName();
}
@Override

View File

@ -25,7 +25,7 @@ public class Dvd {
@EmbeddedId
@GeneratedValue(generator = "custom-id")
@GenericGenerator(name = "custom-id", strategy = "org.hibernate.orm.test.annotations.type.MyOidGenerator")
@GenericGenerator(name = "custom-id", type = MyOidGenerator.class)
@AttributeOverride(name = "aHigh", column = @Column(name = "high"))
@AttributeOverride(name = "aMiddle", column = @Column(name = "middle"))
@AttributeOverride(name = "aLow", column = @Column(name = "low"))

View File

@ -19,7 +19,7 @@
*/
public class TypeTest extends BaseCoreFunctionalTestCase {
@Test
public void testIdWithMulticolumns() throws Exception {
public void testIdWithMulticolumns() {
Session s;
Transaction tx;
s = openSession();
@ -35,8 +35,6 @@ public void testIdWithMulticolumns() throws Exception {
@Override
protected Class[] getAnnotatedClasses() {
return new Class[]{
Dvd.class
};
return new Class[]{ Dvd.class };
}
}

View File

@ -693,7 +693,6 @@ private ExpectedQualifier expectedQualifier(String catalog, String schema) {
);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private String generateScriptFromSessionFactory(String action) {
ServiceRegistryImplementor serviceRegistry = sessionFactory.getServiceRegistry();
Map<String, Object> settings = new HashMap<>(

View File

@ -46,7 +46,7 @@ public void testBagIdResolution(DomainModelScope scope) {
final BasicType<?> legacyResolvedBasicType = identifierResolution.getLegacyResolvedBasicType();
assertThat( legacyResolvedBasicType.getJdbcType().getJdbcTypeCode(), equalTo( Types.SMALLINT ) );
assertThat( identifier.getIdentifierGeneratorStrategy(), equalTo( "increment" ) );
// assertThat( identifier.getIdentifierGeneratorStrategy(), equalTo( "increment" ) );
}
@Entity( name = "EntityWithBag" )

View File

@ -31,8 +31,8 @@ public void verifyModel(DomainModelScope scope) {
assertThat( value.getCustomIdGeneratorCreator() ).isNotNull();
final String strategy = value.getIdentifierGeneratorStrategy();
assertThat( strategy ).isEqualTo( "assigned" );
// final String strategy = value.getIdentifierGeneratorStrategy();
// assertThat( strategy ).isEqualTo( "assigned" );
} );
}