massive cleanup of AnnotationBinder

This commit is contained in:
Gavin King 2022-01-27 11:47:14 +01:00
parent 9a22e615f5
commit 13b00f8907
25 changed files with 693 additions and 776 deletions

View File

@ -11,7 +11,6 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@ -1177,7 +1176,7 @@ public class InFlightMetadataCollectorImpl implements InFlightMetadataCollector
type = AnnotatedClassType.EMBEDDABLE;
}
else if ( clazz.isAnnotationPresent( jakarta.persistence.MappedSuperclass.class ) ) {
type = AnnotatedClassType.EMBEDDABLE_SUPERCLASS;
type = AnnotatedClassType.MAPPED_SUPERCLASS;
}
else {
type = AnnotatedClassType.NONE;

View File

@ -24,7 +24,7 @@ public interface IdGeneratorStrategyInterpreter {
* The Java type of the attribute defining the id whose value is to
* be generated.
*/
Class getIdType();
Class<?> getIdType();
/**
* The {@link GeneratedValue#generator()} name.

View File

@ -19,16 +19,14 @@ public enum TruthValue {
FALSE,
UNKNOWN;
@SuppressWarnings("SimplifiableIfStatement")
public boolean toBoolean(boolean defaultValue) {
if ( this == TRUE ) {
return true;
}
else if ( this == FALSE ) {
return false;
}
else {
return defaultValue;
switch (this) {
case TRUE:
return true;
case FALSE:
return false;
default:
return defaultValue;
}
}

View File

@ -79,8 +79,8 @@ public class AnnotationMetadataSourceProcessorImpl implements MetadataSourceProc
if ( metadataBuildingOptions.isXmlMappingEnabled() ) {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Ewww. This is temporary until we migrate to Jandex + StAX for annotation binding
final JPAXMLOverriddenMetadataProvider jpaMetadataProvider = (JPAXMLOverriddenMetadataProvider) ( (MetadataProviderInjector) reflectionManager )
.getMetadataProvider();
final JPAXMLOverriddenMetadataProvider jpaMetadataProvider = (JPAXMLOverriddenMetadataProvider)
( (MetadataProviderInjector) reflectionManager ).getMetadataProvider();
for ( Binding<?> xmlBinding : managedResources.getXmlMappingBindings() ) {
Object root = xmlBinding.getRoot();
if ( !(root instanceof JaxbEntityMappings) ) {
@ -98,21 +98,21 @@ public class AnnotationMetadataSourceProcessorImpl implements MetadataSourceProc
}
for ( String className : managedResources.getAnnotatedClassNames() ) {
final Class annotatedClass = classLoaderService.classForName( className );
categorizeAnnotatedClass( annotatedClass, attributeConverterManager, classLoaderService );
final Class<?> annotatedClass = classLoaderService.classForName( className );
categorizeAnnotatedClass( annotatedClass, attributeConverterManager );
}
for ( Class annotatedClass : managedResources.getAnnotatedClassReferences() ) {
categorizeAnnotatedClass( annotatedClass, attributeConverterManager, classLoaderService );
for ( Class<?> annotatedClass : managedResources.getAnnotatedClassReferences() ) {
categorizeAnnotatedClass( annotatedClass, attributeConverterManager );
}
}
private void categorizeAnnotatedClass(Class annotatedClass, AttributeConverterManager attributeConverterManager, ClassLoaderService cls) {
private void categorizeAnnotatedClass(Class<?> annotatedClass, AttributeConverterManager attributeConverterManager) {
final XClass xClass = reflectionManager.toXClass( annotatedClass );
// categorize it, based on assumption it does not fall into multiple categories
if ( xClass.isAnnotationPresent( Converter.class ) ) {
//noinspection unchecked
attributeConverterManager.addAttributeConverter( annotatedClass );
//noinspection unchecked, rawtypes
attributeConverterManager.addAttributeConverter( (Class<? extends AttributeConverter>) annotatedClass );
}
else if ( xClass.isAnnotationPresent( Entity.class )
|| xClass.isAnnotationPresent( MappedSuperclass.class ) ) {
@ -126,7 +126,6 @@ public class AnnotationMetadataSourceProcessorImpl implements MetadataSourceProc
}
}
@SuppressWarnings("deprecation")
private XClass toXClass(String className, ReflectionManager reflectionManager, ClassLoaderService cls) {
return reflectionManager.toXClass( cls.classForName( className ) );
}
@ -136,7 +135,7 @@ public class AnnotationMetadataSourceProcessorImpl implements MetadataSourceProc
// use any persistence-unit-defaults defined in orm.xml
( (JpaOrmXmlPersistenceUnitDefaultAware) rootMetadataBuildingContext.getBuildingOptions() ).apply(
new JpaOrmXmlPersistenceUnitDefaults() {
final Map persistenceUnitDefaults = reflectionManager.getDefaults();
final Map<?,?> persistenceUnitDefaults = reflectionManager.getDefaults();
@Override
public String getDefaultSchemaName() {
@ -319,6 +318,7 @@ public class AnnotationMetadataSourceProcessorImpl implements MetadataSourceProc
rootMetadataBuildingContext.getMetadataCollector().addAttributeConverter( descriptor );
}
@SuppressWarnings("rawtypes")
public void addAttributeConverter(Class<? extends AttributeConverter> converterClass) {
rootMetadataBuildingContext.getMetadataCollector().addAttributeConverter( converterClass );
}

View File

@ -150,9 +150,7 @@ public class HbmMetadataSourceProcessorImpl implements MetadataSourceProcessor {
}
@Override
public void postProcessEntityHierarchies() {
modelBinder.finishUp( rootBuildingContext );
}
public void postProcessEntityHierarchies() {}
@Override
public void processResultSetMappings() {

View File

@ -150,7 +150,6 @@ import org.hibernate.tuple.GeneratedValueGeneration;
import org.hibernate.tuple.GenerationTiming;
import org.hibernate.type.AbstractSingleColumnStandardBasicType;
import org.hibernate.type.BasicType;
import org.hibernate.type.ComponentType;
import org.hibernate.type.CustomType;
import org.hibernate.type.ForeignKeyDirection;
import org.hibernate.type.StandardBasicTypes;
@ -192,9 +191,6 @@ public class ModelBinder {
this.relationalObjectBinder = new RelationalObjectBinder( context );
}
public void finishUp(MetadataBuildingContext context) {
}
public void bindEntityHierarchy(EntityHierarchySourceImpl hierarchySource) {
final RootClass rootEntityDescriptor = new RootClass( hierarchySource.getRootEntityMappingDocument() );
bindRootEntity( hierarchySource, rootEntityDescriptor );
@ -308,7 +304,7 @@ public class ModelBinder {
// Configuration applied a similar logic but that capability is no longer
// accessible from Configuration
switch ( mappingDocument.getBuildingOptions().getSharedCacheMode() ) {
case ALL: {
case ALL:
caching = new Caching(
null,
mappingDocument.getBuildingOptions().getImplicitCacheAccessType(),
@ -316,24 +312,11 @@ public class ModelBinder {
TruthValue.UNKNOWN
);
break;
}
case NONE: {
// Ideally we'd disable all caching...
break;
}
case ENABLE_SELECTIVE: {
// this is default behavior for hbm.xml
break;
}
case DISABLE_SELECTIVE: {
// really makes no sense for hbm.xml
break;
}
default: {
// null or UNSPECIFIED, nothing to do. IMO for hbm.xml this is equivalent
// to ENABLE_SELECTIVE
break;
}
case NONE: // Ideally we'd disable all caching...
case ENABLE_SELECTIVE: // this is default behavior for hbm.xml
case DISABLE_SELECTIVE: // really makes no sense for hbm.xml
default: // null or UNSPECIFIED, nothing to do. IMO for hbm.xml this is equivalent to ENABLE_SELECTIVE
// do nothing
}
}
@ -464,7 +447,7 @@ public class ModelBinder {
}
}
bindCustomSql( sourceDocument, entitySource, entityDescriptor );
bindCustomSql( entitySource, entityDescriptor );
final JdbcEnvironment jdbcEnvironment = sourceDocument.getMetadataCollector().getDatabase().getJdbcEnvironment();
@ -846,8 +829,7 @@ public class ModelBinder {
idPropertyName,
idPropertyName == null,
idClassName == null && idPropertyName == null,
identifierSource.getEmbeddableSource().isDynamic(),
identifierSource.getIdentifierAttributeSource().getXmlNodeName()
identifierSource.getEmbeddableSource().isDynamic()
);
finishBindingCompositeIdentifier(
@ -892,8 +874,7 @@ public class ModelBinder {
null,
true,
idClassName == null,
false,
null
false
);
if ( idClassName != null ) {
@ -911,8 +892,7 @@ public class ModelBinder {
null,
true,
true,
false,
null
false
);
rootEntityDescriptor.setIdentifierMapper( mapper );
@ -1758,11 +1738,7 @@ public class ModelBinder {
secondaryTableJoin.setTable( secondaryTable );
entityTableXref.addSecondaryTable( mappingDocument, logicalTableName, secondaryTableJoin );
bindCustomSql(
mappingDocument,
secondaryTableSource,
secondaryTableJoin
);
bindCustomSql( secondaryTableSource, secondaryTableJoin );
secondaryTableJoin.setSequentialSelect( secondaryTableSource.getFetchStyle() == FetchStyle.SELECT );
secondaryTableJoin.setInverse( secondaryTableSource.isInverse() );
@ -1841,7 +1817,6 @@ public class ModelBinder {
componentBinding,
containingClassName,
attributeName,
embeddedSource.getXmlNodeName(),
embeddedSource.isVirtualAttribute()
);
@ -2006,7 +1981,6 @@ public class ModelBinder {
sourceDocument,
oneToOneBinding.getReferencedEntityName(),
propertyRef,
true,
"<one-to-one name=\"" + oneToOneSource.getName() + "\"/>"
);
}
@ -2030,7 +2004,6 @@ public class ModelBinder {
MappingDocument mappingDocument,
String referencedEntityName,
String referencedPropertyName,
boolean isUnique,
String sourceElementSynopsis) {
PersistentClass entityBinding = mappingDocument.getMetadataCollector().getEntityBinding( referencedEntityName );
if ( entityBinding == null ) {
@ -2039,7 +2012,7 @@ public class ModelBinder {
new DelayedPropertyReferenceHandlerImpl(
referencedEntityName,
referencedPropertyName,
isUnique,
true,
sourceElementSynopsis,
mappingDocument.getOrigin()
),
@ -2054,7 +2027,7 @@ public class ModelBinder {
new DelayedPropertyReferenceHandlerImpl(
referencedEntityName,
referencedPropertyName,
isUnique,
true,
sourceElementSynopsis,
mappingDocument.getOrigin()
),
@ -2068,9 +2041,7 @@ public class ModelBinder {
referencedPropertyName,
sourceElementSynopsis
);
if ( isUnique ) {
( (SimpleValue) propertyBinding.getValue() ).setAlternateUniqueKey( true );
}
( (SimpleValue) propertyBinding.getValue() ).setAlternateUniqueKey( true );
}
}
}
@ -2191,7 +2162,6 @@ public class ModelBinder {
sourceDocument,
manyToOneBinding.getReferencedEntityName(),
propertyRef,
true,
"<many-to-one name=\"" + manyToOneSource.getName() + "\"/>"
);
}
@ -2309,7 +2279,7 @@ public class ModelBinder {
String entityName) {
final String attributeName = anyMapping.getName();
bindAny( sourceDocument, anyMapping, anyBinding, anyMapping.getAttributeRole(), anyMapping.getAttributePath() );
bindAny( sourceDocument, anyMapping, anyBinding, anyMapping.getAttributeRole() );
prepareValueTypeViaReflection( sourceDocument, anyBinding, entityName, attributeName, anyMapping.getAttributeRole() );
@ -2330,8 +2300,7 @@ public class ModelBinder {
MappingDocument sourceDocument,
final AnyMappingSource anyMapping,
Any anyBinding,
final AttributeRole attributeRole,
AttributePath attributePath) {
final AttributeRole attributeRole) {
anyBinding.setLazy( anyMapping.isLazy() );
@ -2592,19 +2561,7 @@ public class ModelBinder {
property.setMetaAttributes( propertySource.getToolingHintContext().getMetaAttributeMap() );
if ( log.isDebugEnabled() ) {
final StringBuilder message = new StringBuilder()
.append( "Mapped property: " )
.append( propertySource.getName() )
.append( " -> [" );
final Iterator<Selectable> itr = property.getValue().getColumnIterator();
while ( itr.hasNext() ) {
message.append( itr.next().getText() );
if ( itr.hasNext() ) {
message.append( ", " );
}
}
message.append( "]" );
log.debug( message.toString() );
log.debug( "Mapped property: " + propertySource.getName() + " -> [" + columns( property.getValue() ) + "]" );
}
}
@ -2614,7 +2571,6 @@ public class ModelBinder {
Component component,
String containingClassName,
String propertyName,
String xmlNodeName,
boolean isVirtual) {
final String fullRole = embeddableSource.getAttributeRoleBase().getFullPath();
final String explicitComponentClassName = extractExplicitComponentClassName( embeddableSource );
@ -2629,8 +2585,7 @@ public class ModelBinder {
propertyName,
isVirtual,
isVirtual,
embeddableSource.isDynamic(),
xmlNodeName
embeddableSource.isDynamic()
);
}
@ -2652,8 +2607,7 @@ public class ModelBinder {
String propertyName,
boolean isComponentEmbedded,
boolean isVirtual,
boolean isDynamic,
String xmlNodeName) {
boolean isDynamic) {
componentBinding.setMetaAttributes( embeddableSource.getToolingHintContext().getMetaAttributeMap() );
@ -3014,7 +2968,6 @@ public class ModelBinder {
}
private static void bindCustomSql(
MappingDocument sourceDocument,
EntitySource entitySource,
PersistentClass entityDescriptor) {
if ( entitySource.getCustomSqlInsert() != null ) {
@ -3045,7 +2998,6 @@ public class ModelBinder {
}
private static void bindCustomSql(
MappingDocument sourceDocument,
SecondaryTableSource secondaryTableSource,
Join secondaryTable) {
if ( secondaryTableSource.getCustomSqlInsert() != null ) {
@ -3196,18 +3148,6 @@ public class ModelBinder {
}
}
private String columns(Value value) {
final StringBuilder builder = new StringBuilder();
final Iterator<Selectable> selectableItr = value.getColumnIterator();
while ( selectableItr.hasNext() ) {
builder.append( selectableItr.next().getText() );
if ( selectableItr.hasNext() ) {
builder.append( ", " );
}
}
return builder.toString();
}
private void bindCollectionTable() {
// 2 main branches here:
// 1) one-to-many
@ -3485,7 +3425,6 @@ public class ModelBinder {
elementBinding,
null,
embeddableSource.getAttributePathBase().getProperty(),
getPluralAttributeSource().getXmlNodeName(),
false
);
@ -3668,9 +3607,7 @@ public class ModelBinder {
mappingDocument,
elementSource,
elementBinding,
getPluralAttributeSource().getAttributeRole().append( "element" ),
getPluralAttributeSource().getAttributePath().append( "element" )
getPluralAttributeSource().getAttributeRole().append( "element" )
);
getCollectionBinding().setElement( elementBinding );
// Collection#setWhere is used to set the "where" clause that applies to the collection table
@ -4003,7 +3940,6 @@ public class ModelBinder {
componentBinding,
null,
pluralAttributeSource.getName(),
mapKeySource.getXmlNodeName(),
false
);
collectionBinding.setIndex( componentBinding );
@ -4050,8 +3986,7 @@ public class ModelBinder {
mappingDocument,
mapKeySource,
mapKeyBinding,
pluralAttributeSource.getAttributeRole().append( "key" ),
pluralAttributeSource.getAttributePath().append( "key" )
pluralAttributeSource.getAttributeRole().append( "key" )
);
collectionBinding.setIndex( mapKeyBinding );
}
@ -4287,6 +4222,17 @@ public class ModelBinder {
entityBinding.getTable().addUniqueKey( uk );
}
}
private String columns(Value value) {
final StringBuilder builder = new StringBuilder();
final Iterator<Selectable> selectableItr = value.getColumnIterator();
while ( selectableItr.hasNext() ) {
builder.append( selectableItr.next().getText() );
if ( selectableItr.hasNext() ) {
builder.append( ", " );
}
}
return builder.toString();
}
}

View File

@ -18,15 +18,15 @@ public enum AnnotatedClassType {
*/
NONE,
/**
* has @Entity annotation
* has an {@link jakarta.persistence.Entity} annotation
*/
ENTITY,
/**
* has an @Embeddable annotation
* has an {@link jakarta.persistence.Embeddable} annotation
*/
EMBEDDABLE,
/**
* has @EmbeddedSuperclass annotation
* has {@link jakarta.persistence.MappedSuperclass} annotation
*/
EMBEDDABLE_SUPERCLASS
MAPPED_SUPERCLASS
}

View File

@ -867,7 +867,7 @@ public class AnnotatedColumn {
@Override
public String toString() {
return String.format(
"Ejb3Column{table=%s, mappingColumn=%s, insertable=%s, updatable=%s, unique=%s}",
"Column{table=%s, mappingColumn=%s, insertable=%s, updatable=%s, unique=%s}",
getTable(), mappingColumn.getName(), insertable, updatable, unique
);
}

View File

@ -85,7 +85,7 @@ public class AnnotatedDiscriminatorColumn extends AnnotatedColumn {
@Override
public String toString() {
return String.format("Ejb3DiscriminatorColumn{logicalColumnName'%s', discriminatorTypeName='%s'}",
return String.format("DiscriminatorColumn{logicalColumnName'%s', discriminatorTypeName='%s'}",
getLogicalColumnName(), discriminatorTypeName
);
}

View File

@ -968,7 +968,7 @@ public class AnnotatedJoinColumn extends AnnotatedColumn {
@Override
public String toString() {
return String.format(
"Ejb3JoinColumn{logicalColumnName='%s', referencedColumn='%s', mappedBy='%s'}",
"JoinColumn{logicalColumnName='%s', referencedColumn='%s', mappedBy='%s'}",
getLogicalColumnName(), referencedColumn, mappedBy
);
}

View File

@ -29,6 +29,7 @@ import org.hibernate.annotations.SqlFragmentAlias;
import org.hibernate.annotations.common.reflection.XClass;
import org.hibernate.annotations.common.reflection.XProperty;
import org.hibernate.boot.model.IdGeneratorStrategyInterpreter;
import org.hibernate.boot.model.IdGeneratorStrategyInterpreter.GeneratorNameDeterminationContext;
import org.hibernate.boot.model.IdentifierGeneratorDefinition;
import org.hibernate.boot.spi.MetadataBuildingContext;
import org.hibernate.cfg.annotations.BasicValueBinder;
@ -550,8 +551,7 @@ public class BinderHelper {
id.setIdentifierGeneratorStrategy( identifierGeneratorStrategy );
}
//checkIfMatchingGenerator(gen, generatorType, generatorName);
for ( Object o : gen.getParameters().entrySet() ) {
Map.Entry elt = (Map.Entry) o;
for ( Map.Entry<?,?> elt : gen.getParameters().entrySet() ) {
if ( elt.getKey() == null ) {
continue;
}
@ -594,7 +594,8 @@ public class BinderHelper {
}
}
final IdentifierGeneratorDefinition globalDefinition = buildingContext.getMetadataCollector().getIdentifierGenerator( name );
final IdentifierGeneratorDefinition globalDefinition =
buildingContext.getMetadataCollector().getIdentifierGenerator( name );
if ( globalDefinition != null ) {
return globalDefinition;
}
@ -615,7 +616,8 @@ public class BinderHelper {
return new IdentifierGeneratorDefinition( "assigned", "assigned" );
}
final IdGeneratorStrategyInterpreter generationInterpreter = buildingContext.getBuildingOptions().getIdGenerationTypeInterpreter();
final IdGeneratorStrategyInterpreter generationInterpreter =
buildingContext.getBuildingOptions().getIdGenerationTypeInterpreter();
final GenerationType generationType = interpretGenerationType( generatedValueAnn );
@ -746,9 +748,9 @@ public class BinderHelper {
else {
strategyName = generationInterpreter.determineGeneratorName(
generationType,
new IdGeneratorStrategyInterpreter.GeneratorNameDeterminationContext() {
new GeneratorNameDeterminationContext() {
@Override
public Class getIdType() {
public Class<?> getIdType() {
return buildingContext
.getBootstrapContext()
.getReflectionManager()
@ -812,7 +814,8 @@ public class BinderHelper {
value.setLazy( lazy );
value.setCascadeDeleteEnabled( cascadeOnDelete );
final BasicValueBinder<?> discriminatorValueBinder = new BasicValueBinder<>( BasicValueBinder.Kind.ANY_DISCRIMINATOR, context );
final BasicValueBinder<?> discriminatorValueBinder =
new BasicValueBinder<>( BasicValueBinder.Kind.ANY_DISCRIMINATOR, context );
final AnnotatedColumn[] discriminatorColumns = AnnotatedColumn.buildColumnFromAnnotation(
new jakarta.persistence.Column[] { discriminatorColumn },
@ -864,7 +867,10 @@ public class BinderHelper {
final BasicValue keyDescriptor = keyValueBinder.make();
value.setKey( keyDescriptor );
keyValueBinder.fillSimpleValue();
AnnotatedColumn.checkPropertyConsistency( keyColumns, propertyHolder.getEntityName() + "." + inferredData.getPropertyName() );
AnnotatedColumn.checkPropertyConsistency(
keyColumns,
propertyHolder.getEntityName() + "." + inferredData.getPropertyName()
);
keyColumns[0].linkWithValue( keyDescriptor );
return value;

View File

@ -38,12 +38,13 @@ import static org.hibernate.cfg.AnnotationBinder.getOverridableAnnotation;
* @author Brett Meyer
*/
class ColumnsBuilder {
private PropertyHolder propertyHolder;
private Nullability nullability;
private XProperty property;
private PropertyData inferredData;
private EntityBinder entityBinder;
private MetadataBuildingContext buildingContext;
private final PropertyHolder propertyHolder;
private final Nullability nullability;
private final XProperty property;
private final PropertyData inferredData;
private final EntityBinder entityBinder;
private final MetadataBuildingContext buildingContext;
private AnnotatedColumn[] columns;
private AnnotatedJoinColumn[] joinColumns;

View File

@ -27,7 +27,7 @@ public class CreateKeySecondPass implements SecondPass {
this.joinedSubClass = joinedSubClass;
}
public void doSecondPass(Map<String, PersistentClass> persistentClasses) throws MappingException {
public void doSecondPass(Map<String, PersistentClass> persistentClasses) {
if ( rootClass != null ) {
rootClass.createPrimaryKey();
}

View File

@ -44,9 +44,9 @@ public class InheritanceState {
private boolean hasParents = false;
private InheritanceType type;
private boolean isEmbeddableSuperclass = false;
private Map<XClass, InheritanceState> inheritanceStatePerClass;
private List<XClass> classesToProcessForMappedSuperclass = new ArrayList<>();
private MetadataBuildingContext buildingContext;
private final Map<XClass, InheritanceState> inheritanceStatePerClass;
private final List<XClass> classesToProcessForMappedSuperclass = new ArrayList<>();
private final MetadataBuildingContext buildingContext;
private AccessType accessType;
private ElementsToProcess elementsToProcess;
private Boolean hasIdClassOrEmbeddedId;
@ -195,17 +195,15 @@ public class InheritanceState {
}
/*
* Get the annotated elements and determine access type from hierarchy, guessing from @Id or @EmbeddedId presence if not
* specified.
* Get the annotated elements and determine access type from hierarchy,
* guessing from @Id or @EmbeddedId presence if not specified.
* Change EntityBinder by side effect
*/
public ElementsToProcess getElementsToProcess() {
if ( elementsToProcess == null ) {
InheritanceState inheritanceState = inheritanceStatePerClass.get( clazz );
assert !inheritanceState.isEmbeddableSuperclass();
getMappedSuperclassesTillNextEntityOrdered();
accessType = determineDefaultAccessType();

View File

@ -8,7 +8,6 @@ package org.hibernate.cfg.annotations;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@ -184,7 +183,7 @@ public abstract class CollectionBinder {
private TableBinder tableBinder;
private AnnotatedColumn[] mapKeyColumns;
private AnnotatedJoinColumn[] mapKeyManyToManyColumns;
protected HashMap<String, IdentifierGeneratorDefinition> localGenerators;
protected Map<String, IdentifierGeneratorDefinition> localGenerators;
protected Map<XClass, InheritanceState> inheritanceStatePerClass;
private XClass declaringClass;
private boolean declaringClassSet;
@ -1119,8 +1118,7 @@ public abstract class CollectionBinder {
if ( jpaOrderBy != null ) {
final String orderByFragment = buildOrderByClauseFromHql(
jpaOrderBy.value(),
associatedClass,
collection.getRole()
associatedClass
);
if ( StringHelper.isNotEmpty( orderByFragment ) ) {
collection.setOrderBy( orderByFragment );
@ -1337,7 +1335,7 @@ public abstract class CollectionBinder {
}
}
private static String buildOrderByClauseFromHql(String orderByFragment, PersistentClass associatedClass, String role) {
private static String buildOrderByClauseFromHql(String orderByFragment, PersistentClass associatedClass) {
if ( orderByFragment != null ) {
if ( orderByFragment.length() == 0 ) {
//order by id
@ -1437,7 +1435,7 @@ public abstract class CollectionBinder {
if ( collectionTableAnn != null ) {
if ( collectionTableAnn.foreignKey().value() == ConstraintMode.NO_CONSTRAINT
|| collectionTableAnn.foreignKey().value() == ConstraintMode.PROVIDER_DEFAULT && noConstraintByDefault ) {
key.setForeignKeyName( "none" );
key.disableForeignKey();
}
else {
key.setForeignKeyName( StringHelper.nullIfEmpty( collectionTableAnn.foreignKey().name() ) );
@ -1469,7 +1467,7 @@ public abstract class CollectionBinder {
}
if ( foreignKeyValue == ConstraintMode.NO_CONSTRAINT
|| foreignKeyValue == ConstraintMode.PROVIDER_DEFAULT && noConstraintByDefault ) {
key.setForeignKeyName( "none" );
key.disableForeignKey();
}
else {
key.setForeignKeyName( StringHelper.nullIfEmpty( foreignKeyName ) );
@ -1482,7 +1480,7 @@ public abstract class CollectionBinder {
);
if ( fkOverride != null && ( fkOverride.value() == ConstraintMode.NO_CONSTRAINT ||
fkOverride.value() == ConstraintMode.PROVIDER_DEFAULT && noConstraintByDefault ) ) {
key.setForeignKeyName( "none" );
key.disableForeignKey();
}
else if ( fkOverride != null ) {
key.setForeignKeyName( StringHelper.nullIfEmpty( fkOverride.name() ) );
@ -1495,14 +1493,14 @@ public abstract class CollectionBinder {
&& ( onDeleteAnn == null || onDeleteAnn.action() != OnDeleteAction.CASCADE ) ) {
// foreign key should be up to @ManyToOne side
// @OnDelete generate "on delete cascade" foreign key
key.setForeignKeyName( "none" );
key.disableForeignKey();
}
else {
final JoinColumn joinColumnAnn = property.getAnnotation( JoinColumn.class );
if ( joinColumnAnn != null ) {
if ( joinColumnAnn.foreignKey().value() == ConstraintMode.NO_CONSTRAINT
|| joinColumnAnn.foreignKey().value() == ConstraintMode.PROVIDER_DEFAULT && noConstraintByDefault ) {
key.setForeignKeyName( "none" );
key.disableForeignKey();
}
else {
key.setForeignKeyName( StringHelper.nullIfEmpty( joinColumnAnn.foreignKey().name() ) );
@ -1674,7 +1672,7 @@ public abstract class CollectionBinder {
// as per 11.1.38 of JPA 2.0 spec, default to primary key if no column is specified by @OrderBy.
if ( hqlOrderBy != null ) {
collValue.setManyToManyOrdering(
buildOrderByClauseFromHql( hqlOrderBy, collectionEntity, collValue.getRole() )
buildOrderByClauseFromHql( hqlOrderBy, collectionEntity)
);
}
@ -1687,20 +1685,16 @@ public abstract class CollectionBinder {
if ( joinTableAnn != null ) {
String foreignKeyName = joinTableAnn.inverseForeignKey().name();
String foreignKeyDefinition = joinTableAnn.inverseForeignKey().foreignKeyDefinition();
ConstraintMode foreignKeyValue = joinTableAnn.inverseForeignKey().value();
if ( joinTableAnn.inverseJoinColumns().length != 0 ) {
final JoinColumn joinColumnAnn = joinTableAnn.inverseJoinColumns()[0];
if ( foreignKeyName != null && foreignKeyName.isEmpty() ) {
foreignKeyName = joinColumnAnn.foreignKey().name();
foreignKeyDefinition = joinColumnAnn.foreignKey().foreignKeyDefinition();
}
if ( foreignKeyValue != ConstraintMode.NO_CONSTRAINT ) {
foreignKeyValue = joinColumnAnn.foreignKey().value();
}
}
if ( joinTableAnn.inverseForeignKey().value() == ConstraintMode.NO_CONSTRAINT
|| joinTableAnn.inverseForeignKey().value() == ConstraintMode.PROVIDER_DEFAULT && buildingContext.getBuildingOptions().isNoConstraintByDefault() ) {
element.setForeignKeyName( "none" );
element.disableForeignKey();
}
else {
element.setForeignKeyName( StringHelper.nullIfEmpty( foreignKeyName ) );
@ -2089,7 +2083,7 @@ public abstract class CollectionBinder {
this.mapKeyManyToManyColumns = mapJoinColumns;
}
public void setLocalGenerators(HashMap<String, IdentifierGeneratorDefinition> localGenerators) {
public void setLocalGenerators(Map<String, IdentifierGeneratorDefinition> localGenerators) {
this.localGenerators = localGenerators;
}
}

View File

@ -31,7 +31,6 @@ import org.hibernate.MappingException;
import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Columns;
import org.hibernate.annotations.Comment;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
@ -70,8 +69,6 @@ import org.hibernate.cfg.AccessType;
import org.hibernate.cfg.AnnotationBinder;
import org.hibernate.cfg.BinderHelper;
import org.hibernate.cfg.AnnotatedJoinColumn;
import org.hibernate.cfg.InheritanceState;
import org.hibernate.cfg.ObjectNameSource;
import org.hibernate.cfg.PropertyHolder;
import org.hibernate.cfg.UniqueConstraintHolder;
import org.hibernate.engine.OptimisticLockStyle;
@ -103,7 +100,8 @@ import static org.hibernate.cfg.BinderHelper.toAliasTableMap;
* @author Emmanuel Bernard
*/
public class EntityBinder {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, EntityBinder.class.getName());
private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, EntityBinder.class.getName() );
private static final String NATURAL_ID_CACHE_SUFFIX = "##NaturalId";
private MetadataBuildingContext context;
@ -125,10 +123,9 @@ public class EntityBinder {
private String where;
// todo : we should defer to InFlightMetadataCollector.EntityTableXref for secondary table tracking;
// atm we use both from here; HBM binding solely uses InFlightMetadataCollector.EntityTableXref
private java.util.Map<String, Join> secondaryTables = new HashMap<>();
private java.util.Map<String, Object> secondaryTableJoins = new HashMap<>();
private List<Filter> filters = new ArrayList<>();
private InheritanceState inheritanceState;
private final java.util.Map<String, Join> secondaryTables = new HashMap<>();
private final java.util.Map<String, Object> secondaryTableJoins = new HashMap<>();
private final List<Filter> filters = new ArrayList<>();
private boolean ignoreIdAnnotations;
private AccessType propertyAccessType = AccessType.DEFAULT;
private boolean wrapIdsInEmbeddedComponents;
@ -151,14 +148,13 @@ public class EntityBinder {
}
public EntityBinder(
Entity ejb3Ann,
XClass annotatedClass,
PersistentClass persistentClass,
MetadataBuildingContext context) {
this.context = context;
this.persistentClass = persistentClass;
this.annotatedClass = annotatedClass;
bindEjb3Annotation( ejb3Ann );
bindEntityAnnotation( annotatedClass.getAnnotation( Entity.class ) );
bindHibernateAnnotation();
}
@ -170,14 +166,10 @@ public class EntityBinder {
*
* @return {@code true} if a property by that given name does already exist in the super hierarchy.
*/
@SuppressWarnings("SimplifiableIfStatement")
public boolean isPropertyDefinedInSuperHierarchy(String name) {
// Yes, yes... persistentClass can be null because EntityBinder can be used
// to bind components as well, of course...
if ( persistentClass == null ) {
return false;
}
return persistentClass.isPropertyDefinedInSuperHierarchy( name );
return persistentClass != null && persistentClass.isPropertyDefinedInSuperHierarchy( name );
}
@SuppressWarnings("SimplifiableConditionalExpression")
@ -218,14 +210,13 @@ public class EntityBinder {
}
}
private void bindEjb3Annotation(Entity ejb3Ann) {
if ( ejb3Ann == null ) throw new AssertionFailure( "@Entity should always be not null" );
if ( BinderHelper.isEmptyAnnotationValue( ejb3Ann.name() ) ) {
name = StringHelper.unqualify( annotatedClass.getName() );
}
else {
name = ejb3Ann.name();
private void bindEntityAnnotation(Entity ejb3Ann) {
if ( ejb3Ann == null ) {
throw new AssertionFailure( "@Entity should never be missing" );
}
name = BinderHelper.isEmptyAnnotationValue( ejb3Ann.name() )
? StringHelper.unqualify(annotatedClass.getName())
: ejb3Ann.name();
}
public boolean isRootEntity() {
@ -262,11 +253,7 @@ public class EntityBinder {
if ( persistentClass instanceof RootClass ) {
RootClass rootClass = (RootClass) persistentClass;
boolean mutable = true;
//priority on @Immutable, then @Entity.mutable()
if ( annotatedClass.isAnnotationPresent( Immutable.class ) ) {
mutable = false;
}
boolean mutable = !annotatedClass.isAnnotationPresent( Immutable.class );
rootClass.setMutable( mutable );
rootClass.setExplicitPolymorphism( isExplicitPolymorphism( polymorphismType ) );
@ -307,6 +294,7 @@ public class EntityBinder {
//set persister if needed
Persister persisterAnn = annotatedClass.getAnnotation( Persister.class );
if ( persisterAnn != null ) {
//TODO: throw an error if the class doesn't inherit EntityPersister
Class<? extends EntityPersister> persister = (Class<? extends EntityPersister>) persisterAnn.impl();
persistentClass.setEntityPersisterClass( persister );
}
@ -477,7 +465,6 @@ public class EntityBinder {
}
}
@SuppressWarnings({ "unchecked" })
public void setProxy(Proxy proxy) {
if ( proxy != null ) {
lazy = proxy.lazy();
@ -514,6 +501,7 @@ public class EntityBinder {
XClass clazzToProcess,
SharedCacheMode sharedCacheMode,
MetadataBuildingContext context) {
final Cache explicitCacheAnn = clazzToProcess.getAnnotation( Cache.class );
final Cacheable explicitCacheableAnn = clazzToProcess.getAnnotation( Cacheable.class );
@ -678,26 +666,6 @@ public class EntityBinder {
);
}
private static class EntityTableObjectNameSource implements ObjectNameSource {
private final String explicitName;
private final String logicalName;
private EntityTableObjectNameSource(String explicitName, String entityName) {
this.explicitName = explicitName;
this.logicalName = StringHelper.isNotEmpty( explicitName )
? explicitName
: StringHelper.unqualify( entityName );
}
public String getExplicitName() {
return explicitName;
}
public String getLogicalName() {
return logicalName;
}
}
private static class EntityTableNamingStrategyHelper implements NamingStrategyHelper {
private final String className;
private final String entityName;
@ -761,7 +729,7 @@ public class EntityBinder {
}
public void bindTableForDiscriminatedSubclass(InFlightMetadataCollector.EntityTableXref superTableXref) {
if ( !SingleTableSubclass.class.isInstance( persistentClass ) ) {
if ( !(persistentClass instanceof SingleTableSubclass) ) {
throw new AssertionFailure(
"Was expecting a discriminated subclass [" + SingleTableSubclass.class.getName() +
"] but found [" + persistentClass.getClass().getName() + "] for entity [" +
@ -951,7 +919,7 @@ public class EntityBinder {
final boolean noConstraintByDefault = context.getBuildingOptions().isNoConstraintByDefault();
if ( jpaSecondaryTable.foreignKey().value() == ConstraintMode.NO_CONSTRAINT
|| jpaSecondaryTable.foreignKey().value() == ConstraintMode.PROVIDER_DEFAULT && noConstraintByDefault ) {
( (SimpleValue) join.getKey() ).setForeignKeyName( "none" );
( (SimpleValue) join.getKey() ).disableForeignKey();
}
else {
( (SimpleValue) join.getKey() ).setForeignKeyName( StringHelper.nullIfEmpty( jpaSecondaryTable.foreignKey().name() ) );
@ -1021,33 +989,6 @@ public class EntityBinder {
return addJoin( null, joinTable, holder, noDelayInPkColumnCreation );
}
private static class SecondaryTableNamingStrategyHelper implements NamingStrategyHelper {
@Override
public Identifier determineImplicitName(MetadataBuildingContext buildingContext) {
// should maybe throw an exception here
return null;
}
@Override
public Identifier handleExplicitName(String explicitName, MetadataBuildingContext buildingContext) {
return buildingContext.getMetadataCollector()
.getDatabase()
.getJdbcEnvironment()
.getIdentifierHelper()
.toIdentifier( explicitName );
}
@Override
public Identifier toPhysicalName(Identifier logicalName, MetadataBuildingContext buildingContext) {
return buildingContext.getBuildingOptions().getPhysicalNamingStrategy().toPhysicalTableName(
logicalName,
buildingContext.getMetadataCollector().getDatabase().getJdbcEnvironment()
);
}
}
private static SecondaryTableNamingStrategyHelper SEC_TBL_NS_HELPER = new SecondaryTableNamingStrategyHelper();
private Join addJoin(
SecondaryTable secondaryTable,
JoinTable joinTable,
@ -1185,10 +1126,6 @@ public class EntityBinder {
filters.add(filter);
}
public void setInheritanceState(InheritanceState inheritanceState) {
this.inheritanceState = inheritanceState;
}
public boolean isIgnoreIdAnnotations() {
return ignoreIdAnnotations;
}

View File

@ -348,7 +348,7 @@ public class MapBinder extends CollectionBinder {
if ( foreignKey != null ) {
if ( foreignKey.value() == ConstraintMode.NO_CONSTRAINT
|| foreignKey.value() == ConstraintMode.PROVIDER_DEFAULT && getBuildingContext().getBuildingOptions().isNoConstraintByDefault() ) {
element.setForeignKeyName( "none" );
element.disableForeignKey();
}
else {
element.setForeignKeyName( StringHelper.nullIfEmpty( foreignKey.name() ) );

View File

@ -48,8 +48,8 @@ public class ForeignKey extends Constraint {
@Override
public void setName(String name) {
super.setName( name );
// the FK name "none" is a magic value in the hbm.xml binding that indicated to
// not create a FK.
// the FK name "none" was a magic value in the hbm.xml
// mapping language that indicated to not create a FK
if ( "none".equals( name ) ) {
disableCreation();
}

View File

@ -50,7 +50,7 @@ public class ManyToOne extends ToOne {
// Ensure properties are sorted before we create a foreign key
sortProperties();
// the case of a foreign key to something other than the pk is handled in createPropertyRefConstraints
if ( referencedPropertyName==null && !hasFormula() ) {
if ( isForeignKeyEnabled() && referencedPropertyName==null && !hasFormula() ) {
createForeignKeyOfEntity( ( (EntityType) getType() ).getAssociatedEntityName() );
}
}

View File

@ -82,7 +82,7 @@ public class OneToOne extends ToOne {
public void createForeignKey() throws MappingException {
// Ensure properties are sorted before we create a foreign key
sortProperties();
if ( constrained && referencedPropertyName==null) {
if ( isForeignKeyEnabled() && constrained && referencedPropertyName==null) {
//TODO: handle the case of a foreign key to something other than the pk
createForeignKeyOfEntity( ( (EntityType) getType() ).getAssociatedEntityName() );
}

View File

@ -296,7 +296,7 @@ public class RootClass extends PersistentClass implements TableOwner {
if ( getIdentifier() instanceof Component ) {
Component id = (Component) getIdentifier();
if ( !id.isDynamic() ) {
final Class idClass = id.getComponentClass();
final Class<?> idClass = id.getComponentClass();
if ( idClass != null ) {
final String idComponentClassName = idClass.getName();
if ( !ReflectHelper.overridesEquals( idClass ) ) {

View File

@ -93,6 +93,7 @@ public abstract class SimpleValue implements KeyValue {
private String foreignKeyDefinition;
private boolean alternateUniqueKey;
private boolean cascadeDeleteEnabled;
private boolean foreignKeyEnabled = true;
private ConverterDescriptor attributeConverterDescriptor;
private Type type;
@ -291,7 +292,7 @@ public abstract class SimpleValue implements KeyValue {
@Override
public void createForeignKeyOfEntity(String entityName) {
if ( !hasFormula() && !"none".equals( getForeignKeyName() ) ) {
if ( isConstrained() ) {
table.createForeignKey( getForeignKeyName(), getConstraintColumns(), entityName, getForeignKeyDefinition() )
.setCascadeDeleteEnabled(cascadeDeleteEnabled);
}
@ -545,11 +546,24 @@ public abstract class SimpleValue implements KeyValue {
}
public void setForeignKeyName(String foreignKeyName) {
// the FK name "none" was a magic value in the hbm.xml
// mapping language that indicated to not create a FK
if ( "none".equals( foreignKeyName ) ) {
foreignKeyEnabled = false;
}
this.foreignKeyName = foreignKeyName;
}
public boolean isForeignKeyEnabled() {
return foreignKeyEnabled;
}
public void disableForeignKey() {
this.foreignKeyEnabled = false;
}
public boolean isConstrained() {
return !"none".equals( foreignKeyName ) && !hasFormula();
return isForeignKeyEnabled() && !hasFormula();
}
public String getForeignKeyDefinition() {

View File

@ -32,7 +32,7 @@ public class StandardAnyTypeDefinition implements AnyMappingDefinition {
private static List<DiscriminatorMapping> interpretDiscriminatorMappings(AnyType anyType) {
final Type discriminatorType = anyType.getDiscriminatorType();
if ( ! MetaType.class.isInstance( discriminatorType ) ) {
if ( !(discriminatorType instanceof MetaType) ) {
return Collections.emptyList();
}

View File

@ -22,7 +22,7 @@ import jakarta.persistence.TemporalType;
/**
* Defines the aspects of query execution and parameter binding that apply to all
* forms of querying - HQL, {@linkplain jakarta.persistence.criteria.CriteriaBuilder
* criteria queries} and {@link org.hibernate.procedure.ProcedureCall stored
* criteria queries}, and {@link org.hibernate.procedure.ProcedureCall stored
* procedure calls}.
*
* @author Steve Ebersole