clean up some bodgy handling of "null" annotation values (empty strings)

This commit is contained in:
Gavin 2022-12-09 14:57:53 +01:00 committed by Gavin King
parent a9be2e1584
commit 7208bcea41
24 changed files with 307 additions and 314 deletions

View File

@ -11,7 +11,6 @@ import java.util.UUID;
import org.hibernate.boot.model.IdGeneratorStrategyInterpreter; import org.hibernate.boot.model.IdGeneratorStrategyInterpreter;
import org.hibernate.boot.model.IdentifierGeneratorDefinition; import org.hibernate.boot.model.IdentifierGeneratorDefinition;
import org.hibernate.cfg.BinderHelper;
import org.hibernate.id.IncrementGenerator; import org.hibernate.id.IncrementGenerator;
import org.hibernate.id.PersistentIdentifierGenerator; import org.hibernate.id.PersistentIdentifierGenerator;
import org.hibernate.id.UUIDGenerator; import org.hibernate.id.UUIDGenerator;
@ -23,8 +22,6 @@ import jakarta.persistence.GenerationType;
import jakarta.persistence.SequenceGenerator; import jakarta.persistence.SequenceGenerator;
import jakarta.persistence.TableGenerator; import jakarta.persistence.TableGenerator;
import static org.hibernate.cfg.BinderHelper.isEmptyAnnotationValue;
/** /**
* The root (composition) IdGenerationTypeInterpreter. * The root (composition) IdGenerationTypeInterpreter.
* *
@ -130,31 +127,31 @@ public class IdGeneratorInterpreterImpl implements IdGeneratorStrategyInterprete
definitionBuilder.setStrategy( org.hibernate.id.enhanced.TableGenerator.class.getName() ); definitionBuilder.setStrategy( org.hibernate.id.enhanced.TableGenerator.class.getName() );
definitionBuilder.addParam( org.hibernate.id.enhanced.TableGenerator.CONFIG_PREFER_SEGMENT_PER_ENTITY, "true" ); definitionBuilder.addParam( org.hibernate.id.enhanced.TableGenerator.CONFIG_PREFER_SEGMENT_PER_ENTITY, "true" );
if ( !isEmptyAnnotationValue( tableGeneratorAnnotation.catalog() ) ) { if ( !tableGeneratorAnnotation.catalog().isEmpty()) {
definitionBuilder.addParam( PersistentIdentifierGenerator.CATALOG, tableGeneratorAnnotation.catalog() ); definitionBuilder.addParam( PersistentIdentifierGenerator.CATALOG, tableGeneratorAnnotation.catalog() );
} }
if ( !isEmptyAnnotationValue( tableGeneratorAnnotation.schema() ) ) { if ( !tableGeneratorAnnotation.schema().isEmpty()) {
definitionBuilder.addParam( PersistentIdentifierGenerator.SCHEMA, tableGeneratorAnnotation.schema() ); definitionBuilder.addParam( PersistentIdentifierGenerator.SCHEMA, tableGeneratorAnnotation.schema() );
} }
if ( !isEmptyAnnotationValue( tableGeneratorAnnotation.table() ) ) { if ( !tableGeneratorAnnotation.table().isEmpty()) {
definitionBuilder.addParam( definitionBuilder.addParam(
org.hibernate.id.enhanced.TableGenerator.TABLE_PARAM, org.hibernate.id.enhanced.TableGenerator.TABLE_PARAM,
tableGeneratorAnnotation.table() tableGeneratorAnnotation.table()
); );
} }
if ( !isEmptyAnnotationValue( tableGeneratorAnnotation.pkColumnName() ) ) { if ( !tableGeneratorAnnotation.pkColumnName().isEmpty()) {
definitionBuilder.addParam( definitionBuilder.addParam(
org.hibernate.id.enhanced.TableGenerator.SEGMENT_COLUMN_PARAM, org.hibernate.id.enhanced.TableGenerator.SEGMENT_COLUMN_PARAM,
tableGeneratorAnnotation.pkColumnName() tableGeneratorAnnotation.pkColumnName()
); );
} }
if ( !isEmptyAnnotationValue( tableGeneratorAnnotation.pkColumnValue() ) ) { if ( !tableGeneratorAnnotation.pkColumnValue().isEmpty()) {
definitionBuilder.addParam( definitionBuilder.addParam(
org.hibernate.id.enhanced.TableGenerator.SEGMENT_VALUE_PARAM, org.hibernate.id.enhanced.TableGenerator.SEGMENT_VALUE_PARAM,
tableGeneratorAnnotation.pkColumnValue() tableGeneratorAnnotation.pkColumnValue()
); );
} }
if ( !isEmptyAnnotationValue( tableGeneratorAnnotation.valueColumnName() ) ) { if ( !tableGeneratorAnnotation.valueColumnName().isEmpty()) {
definitionBuilder.addParam( definitionBuilder.addParam(
org.hibernate.id.enhanced.TableGenerator.VALUE_COLUMN_PARAM, org.hibernate.id.enhanced.TableGenerator.VALUE_COLUMN_PARAM,
tableGeneratorAnnotation.valueColumnName() tableGeneratorAnnotation.valueColumnName()
@ -184,19 +181,19 @@ public class IdGeneratorInterpreterImpl implements IdGeneratorStrategyInterprete
definitionBuilder.setName( sequenceGeneratorAnnotation.name() ); definitionBuilder.setName( sequenceGeneratorAnnotation.name() );
definitionBuilder.setStrategy( SequenceStyleGenerator.class.getName() ); definitionBuilder.setStrategy( SequenceStyleGenerator.class.getName() );
if ( !isEmptyAnnotationValue( sequenceGeneratorAnnotation.catalog() ) ) { if ( !sequenceGeneratorAnnotation.catalog().isEmpty()) {
definitionBuilder.addParam( definitionBuilder.addParam(
PersistentIdentifierGenerator.CATALOG, PersistentIdentifierGenerator.CATALOG,
sequenceGeneratorAnnotation.catalog() sequenceGeneratorAnnotation.catalog()
); );
} }
if ( !isEmptyAnnotationValue( sequenceGeneratorAnnotation.schema() ) ) { if ( !sequenceGeneratorAnnotation.schema().isEmpty()) {
definitionBuilder.addParam( definitionBuilder.addParam(
PersistentIdentifierGenerator.SCHEMA, PersistentIdentifierGenerator.SCHEMA,
sequenceGeneratorAnnotation.schema() sequenceGeneratorAnnotation.schema()
); );
} }
if ( !isEmptyAnnotationValue( sequenceGeneratorAnnotation.sequenceName() ) ) { if ( !sequenceGeneratorAnnotation.sequenceName().isEmpty()) {
definitionBuilder.addParam( definitionBuilder.addParam(
SequenceStyleGenerator.SEQUENCE_PARAM, SequenceStyleGenerator.SEQUENCE_PARAM,
sequenceGeneratorAnnotation.sequenceName() sequenceGeneratorAnnotation.sequenceName()

View File

@ -39,7 +39,6 @@ import org.jboss.logging.Logger;
import static org.hibernate.cfg.BinderHelper.getOverridableAnnotation; import static org.hibernate.cfg.BinderHelper.getOverridableAnnotation;
import static org.hibernate.cfg.BinderHelper.getPath; import static org.hibernate.cfg.BinderHelper.getPath;
import static org.hibernate.cfg.BinderHelper.getRelativePath; import static org.hibernate.cfg.BinderHelper.getRelativePath;
import static org.hibernate.cfg.BinderHelper.isEmptyAnnotationValue;
import static org.hibernate.internal.util.StringHelper.isEmpty; import static org.hibernate.internal.util.StringHelper.isEmpty;
import static org.hibernate.internal.util.StringHelper.isNotEmpty; import static org.hibernate.internal.util.StringHelper.isNotEmpty;
import static org.hibernate.internal.util.StringHelper.nullIfEmpty; import static org.hibernate.internal.util.StringHelper.nullIfEmpty;
@ -701,12 +700,12 @@ public class AnnotatedColumn {
} }
private static String getTableName(jakarta.persistence.Column column, Database database) { private static String getTableName(jakarta.persistence.Column column, Database database) {
return isEmptyAnnotationValue( column.table() ) ? "" return column.table().isEmpty() ? ""
: database.getJdbcEnvironment().getIdentifierHelper().toIdentifier( column.table() ).render(); : database.getJdbcEnvironment().getIdentifierHelper().toIdentifier( column.table() ).render();
} }
private static String getSqlType(MetadataBuildingContext context, jakarta.persistence.Column column) { private static String getSqlType(MetadataBuildingContext context, jakarta.persistence.Column column) {
return isEmptyAnnotationValue( column.columnDefinition() ) ? null return column.columnDefinition().isEmpty() ? null
: context.getObjectNameNormalizer().applyGlobalQuoting( column.columnDefinition() ); : context.getObjectNameNormalizer().applyGlobalQuoting( column.columnDefinition() );
} }
@ -763,7 +762,7 @@ public class AnnotatedColumn {
} }
private static String getColumnName(Database database, jakarta.persistence.Column column) { private static String getColumnName(Database database, jakarta.persistence.Column column) {
return isEmptyAnnotationValue( column.name() ) ? null return column.name().isEmpty() ? null
: database.getJdbcEnvironment().getIdentifierHelper().toIdentifier( column.name() ).render(); : database.getJdbcEnvironment().getIdentifierHelper().toIdentifier( column.name() ).render();
} }

View File

@ -13,8 +13,6 @@ import org.hibernate.AssertionFailure;
import org.hibernate.annotations.DiscriminatorFormula; import org.hibernate.annotations.DiscriminatorFormula;
import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.MetadataBuildingContext;
import static org.hibernate.cfg.BinderHelper.isEmptyAnnotationValue;
/** /**
* A {@link jakarta.persistence.DiscriminatorColumn} annotation * A {@link jakarta.persistence.DiscriminatorColumn} annotation
* *
@ -59,10 +57,10 @@ public class AnnotatedDiscriminatorColumn extends AnnotatedColumn {
} }
else if ( discriminatorColumn != null ) { else if ( discriminatorColumn != null ) {
column.setImplicit( false ); column.setImplicit( false );
if ( !isEmptyAnnotationValue( discriminatorColumn.columnDefinition() ) ) { if ( !discriminatorColumn.columnDefinition().isEmpty() ) {
column.setSqlType( discriminatorColumn.columnDefinition() ); column.setSqlType( discriminatorColumn.columnDefinition() );
} }
if ( !isEmptyAnnotationValue( discriminatorColumn.name() ) ) { if ( !discriminatorColumn.name().isEmpty() ) {
column.setLogicalColumnName( discriminatorColumn.name() ); column.setLogicalColumnName( discriminatorColumn.name() );
} }
column.setNullable( false ); column.setNullable( false );

View File

@ -24,11 +24,10 @@ import org.hibernate.mapping.SimpleValue;
import org.hibernate.mapping.Value; import org.hibernate.mapping.Value;
import static org.hibernate.cfg.BinderHelper.getRelativePath; import static org.hibernate.cfg.BinderHelper.getRelativePath;
import static org.hibernate.cfg.BinderHelper.isEmptyAnnotationValue;
import static org.hibernate.cfg.BinderHelper.isEmptyOrNullAnnotationValue;
import static org.hibernate.internal.util.StringHelper.isEmpty; import static org.hibernate.internal.util.StringHelper.isEmpty;
import static org.hibernate.internal.util.StringHelper.isNotEmpty; import static org.hibernate.internal.util.StringHelper.isNotEmpty;
import static org.hibernate.internal.util.StringHelper.isQuoted; import static org.hibernate.internal.util.StringHelper.isQuoted;
import static org.hibernate.internal.util.StringHelper.nullIfEmpty;
import static org.hibernate.internal.util.StringHelper.qualify; import static org.hibernate.internal.util.StringHelper.qualify;
import static org.hibernate.internal.util.StringHelper.unquote; import static org.hibernate.internal.util.StringHelper.unquote;
@ -53,7 +52,7 @@ public class AnnotatedJoinColumn extends AnnotatedColumn {
private AnnotatedJoinColumn() {} private AnnotatedJoinColumn() {}
public void setReferencedColumn(String referencedColumn) { public void setReferencedColumn(String referencedColumn) {
this.referencedColumn = referencedColumn; this.referencedColumn = nullIfEmpty( referencedColumn );
} }
/** /**
@ -68,7 +67,7 @@ public class AnnotatedJoinColumn extends AnnotatedColumn {
* {@link JoinColumn#referencedColumnName() referencedColumnName}. * {@link JoinColumn#referencedColumnName() referencedColumnName}.
*/ */
public boolean isReferenceImplicit() { public boolean isReferenceImplicit() {
return isEmptyOrNullAnnotationValue( referencedColumn ); return isEmpty( referencedColumn );
} }
static AnnotatedJoinColumn buildJoinColumn( static AnnotatedJoinColumn buildJoinColumn(
@ -111,7 +110,7 @@ public class AnnotatedJoinColumn extends AnnotatedColumn {
PropertyData inferredData, PropertyData inferredData,
String defaultColumnSuffix) { String defaultColumnSuffix) {
if ( joinColumn != null ) { if ( joinColumn != null ) {
if ( !isEmptyOrNullAnnotationValue( mappedBy ) ) { if ( mappedBy != null ) {
throw new AnnotationException( "Association '" throw new AnnotationException( "Association '"
+ getRelativePath( propertyHolder, inferredData.getPropertyName() ) + getRelativePath( propertyHolder, inferredData.getPropertyName() )
+ "' is 'mappedBy' a different entity and may not explicitly specify the '@JoinColumn'" ); + "' is 'mappedBy' a different entity and may not explicitly specify the '@JoinColumn'" );
@ -177,11 +176,11 @@ public class AnnotatedJoinColumn extends AnnotatedColumn {
} }
else { else {
setImplicit( false ); setImplicit( false );
if ( !isEmptyAnnotationValue( joinColumn.columnDefinition() ) ) { if ( !joinColumn.columnDefinition().isEmpty() ) {
setSqlType( getBuildingContext().getObjectNameNormalizer() setSqlType( getBuildingContext().getObjectNameNormalizer()
.applyGlobalQuoting( joinColumn.columnDefinition() ) ); .applyGlobalQuoting( joinColumn.columnDefinition() ) );
} }
if ( !isEmptyAnnotationValue( joinColumn.name() ) ) { if ( !joinColumn.name().isEmpty() ) {
setLogicalColumnName( joinColumn.name() ); setLogicalColumnName( joinColumn.name() );
} }
setNullable( joinColumn.nullable() ); setNullable( joinColumn.nullable() );
@ -190,7 +189,7 @@ public class AnnotatedJoinColumn extends AnnotatedColumn {
setUpdatable( joinColumn.updatable() ); setUpdatable( joinColumn.updatable() );
setReferencedColumn( joinColumn.referencedColumnName() ); setReferencedColumn( joinColumn.referencedColumnName() );
if ( isEmptyAnnotationValue( joinColumn.table() ) ) { if ( joinColumn.table().isEmpty() ) {
setExplicitTableName( "" ); setExplicitTableName( "" );
} }
else { else {
@ -242,7 +241,7 @@ public class AnnotatedJoinColumn extends AnnotatedColumn {
final ObjectNameNormalizer normalizer = context.getObjectNameNormalizer(); final ObjectNameNormalizer normalizer = context.getObjectNameNormalizer();
final String columnDef = columnDefinition.isEmpty() ? null final String columnDef = columnDefinition.isEmpty() ? null
: normalizer.toDatabaseIdentifierText( columnDefinition ); : normalizer.toDatabaseIdentifierText( columnDefinition );
final String logicalColumnName = columnName != null && columnName.isEmpty() final String logicalColumnName = columnName.isEmpty()
? normalizer.normalizeIdentifierQuotingAsString( defaultColumnName ) ? normalizer.normalizeIdentifierQuotingAsString( defaultColumnName )
: normalizer.normalizeIdentifierQuotingAsString( columnName ); : normalizer.normalizeIdentifierQuotingAsString( columnName );
final AnnotatedJoinColumn column = new AnnotatedJoinColumn(); final AnnotatedJoinColumn column = new AnnotatedJoinColumn();
@ -350,7 +349,7 @@ public class AnnotatedJoinColumn extends AnnotatedColumn {
@Override @Override
protected void addColumnBinding(SimpleValue value) { protected void addColumnBinding(SimpleValue value) {
if ( isEmpty( getParent().getMappedBy() ) ) { if ( !getParent().hasMappedBy() ) {
// was the column explicitly quoted in the mapping/annotation // was the column explicitly quoted in the mapping/annotation
// TODO: in metamodel, we need to better split global quoting and explicit quoting w/ respect to logical names // TODO: in metamodel, we need to better split global quoting and explicit quoting w/ respect to logical names
boolean isLogicalColumnQuoted = isQuoted( getLogicalColumnName() ); boolean isLogicalColumnQuoted = isQuoted( getLogicalColumnName() );

View File

@ -34,8 +34,9 @@ import java.util.Map;
import static org.hibernate.cfg.BinderHelper.findReferencedColumnOwner; import static org.hibernate.cfg.BinderHelper.findReferencedColumnOwner;
import static org.hibernate.cfg.BinderHelper.getRelativePath; import static org.hibernate.cfg.BinderHelper.getRelativePath;
import static org.hibernate.cfg.BinderHelper.isEmptyOrNullAnnotationValue; import static org.hibernate.internal.util.StringHelper.isNotEmpty;
import static org.hibernate.internal.util.StringHelper.isQuoted; import static org.hibernate.internal.util.StringHelper.isQuoted;
import static org.hibernate.internal.util.StringHelper.nullIfEmpty;
import static org.hibernate.internal.util.StringHelper.qualify; import static org.hibernate.internal.util.StringHelper.qualify;
/** /**
@ -78,7 +79,8 @@ public class AnnotatedJoinColumns extends AnnotatedColumns {
for ( JoinColumnOrFormula columnOrFormula : joinColumnOrFormulas ) { for ( JoinColumnOrFormula columnOrFormula : joinColumnOrFormulas ) {
final JoinFormula formula = columnOrFormula.formula(); final JoinFormula formula = columnOrFormula.formula();
final JoinColumn column = columnOrFormula.column(); final JoinColumn column = columnOrFormula.column();
if ( !isEmptyOrNullAnnotationValue( formula.value() ) ) { final String annotationString = formula.value();
if ( isNotEmpty( annotationString ) ) {
AnnotatedJoinColumn.buildJoinFormula( formula, parent ); AnnotatedJoinColumn.buildJoinFormula( formula, parent );
} }
else { else {
@ -132,6 +134,7 @@ public class AnnotatedJoinColumns extends AnnotatedColumns {
PropertyData inferredData, PropertyData inferredData,
String defaultColumnSuffix, String defaultColumnSuffix,
MetadataBuildingContext context) { MetadataBuildingContext context) {
assert mappedBy == null || !mappedBy.isEmpty();
final String propertyName = inferredData.getPropertyName(); final String propertyName = inferredData.getPropertyName();
final String path = qualify( propertyHolder.getPath(), propertyName ); final String path = qualify( propertyHolder.getPath(), propertyName );
final JoinColumn[] overriddes = propertyHolder.getOverriddenJoinColumn( path ); final JoinColumn[] overriddes = propertyHolder.getOverriddenJoinColumn( path );
@ -218,7 +221,7 @@ public class AnnotatedJoinColumns extends AnnotatedColumns {
} }
public void setMappedBy(String mappedBy) { public void setMappedBy(String mappedBy) {
this.mappedBy = mappedBy; this.mappedBy = nullIfEmpty( mappedBy );
} }
/** /**
@ -228,7 +231,7 @@ public class AnnotatedJoinColumns extends AnnotatedColumns {
* unowned many-valued association. * unowned many-valued association.
*/ */
public boolean hasMappedBy() { public boolean hasMappedBy() {
return !isEmptyOrNullAnnotationValue( getMappedBy() ); return mappedBy != null;
} }
public String getMappedByEntityName() { public String getMappedByEntityName() {

View File

@ -155,7 +155,6 @@ import static org.hibernate.cfg.BinderHelper.getPath;
import static org.hibernate.cfg.BinderHelper.getPropertyOverriddenByMapperOrMapsId; import static org.hibernate.cfg.BinderHelper.getPropertyOverriddenByMapperOrMapsId;
import static org.hibernate.cfg.BinderHelper.getRelativePath; import static org.hibernate.cfg.BinderHelper.getRelativePath;
import static org.hibernate.cfg.BinderHelper.hasToOneAnnotation; import static org.hibernate.cfg.BinderHelper.hasToOneAnnotation;
import static org.hibernate.cfg.BinderHelper.isEmptyAnnotationValue;
import static org.hibernate.cfg.BinderHelper.makeIdGenerator; import static org.hibernate.cfg.BinderHelper.makeIdGenerator;
import static org.hibernate.cfg.InheritanceState.getInheritanceStateOfSuperEntity; import static org.hibernate.cfg.InheritanceState.getInheritanceStateOfSuperEntity;
import static org.hibernate.cfg.InheritanceState.getSuperclassInheritanceState; import static org.hibernate.cfg.InheritanceState.getSuperclassInheritanceState;
@ -550,11 +549,11 @@ public final class AnnotationBinder {
} }
private static void handleImport(XClass annotatedClass, MetadataBuildingContext context) { private static void handleImport(XClass annotatedClass, MetadataBuildingContext context) {
if ( annotatedClass.isAnnotationPresent(Imported.class) ) { if ( annotatedClass.isAnnotationPresent( Imported.class ) ) {
String qualifiedName = annotatedClass.getName(); String qualifiedName = annotatedClass.getName();
String name = StringHelper.unqualify( qualifiedName ); String name = StringHelper.unqualify( qualifiedName );
String rename = annotatedClass.getAnnotation(Imported.class).rename(); String rename = annotatedClass.getAnnotation( Imported.class ).rename();
context.getMetadataCollector().addImport( isEmptyAnnotationValue( rename ) ? name : rename, qualifiedName ); context.getMetadataCollector().addImport( rename.isEmpty() ? name : rename, qualifiedName );
} }
} }

View File

@ -73,6 +73,7 @@ import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType; import jakarta.persistence.GenerationType;
import static org.hibernate.cfg.AnnotatedColumn.buildColumnOrFormulaFromAnnotation; import static org.hibernate.cfg.AnnotatedColumn.buildColumnOrFormulaFromAnnotation;
import static org.hibernate.internal.util.StringHelper.isEmpty;
import static org.hibernate.internal.util.StringHelper.isNotEmpty; import static org.hibernate.internal.util.StringHelper.isNotEmpty;
import static org.hibernate.internal.util.StringHelper.qualify; import static org.hibernate.internal.util.StringHelper.qualify;
@ -482,7 +483,7 @@ public class BinderHelper {
int lastPropertyColumnIndex = 0; int lastPropertyColumnIndex = 0;
Property currentProperty = null; Property currentProperty = null;
for ( Column column : orderedColumns ) { for ( Column column : orderedColumns ) {
Set<Property> properties = columnsToProperty.get( column ); final Set<Property> properties = columnsToProperty.get( column );
if ( properties.isEmpty() ) { if ( properties.isEmpty() ) {
// no property found which maps to this column // no property found which maps to this column
throw new AnnotationException( "Referenced column '" + column.getName() throw new AnnotationException( "Referenced column '" + column.getName()
@ -576,11 +577,9 @@ public class BinderHelper {
public static Property findPropertyByName(PersistentClass associatedClass, String propertyName) { public static Property findPropertyByName(PersistentClass associatedClass, String propertyName) {
Property property = null; Property property = null;
Property idProperty = associatedClass.getIdentifierProperty(); Property idProperty = associatedClass.getIdentifierProperty();
String idName = idProperty != null ? idProperty.getName() : null; String idName = idProperty == null ? null : idProperty.getName();
try { try {
if ( propertyName == null if ( isEmpty( propertyName ) || propertyName.equals( idName ) ) {
|| propertyName.length() == 0
|| propertyName.equals( idName ) ) {
//default to id //default to id
property = idProperty; property = idProperty;
} }
@ -768,7 +767,7 @@ public class BinderHelper {
parameters.put( PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER, buildingContext.getObjectNameNormalizer() ); parameters.put( PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER, buildingContext.getObjectNameNormalizer() );
parameters.put( IdentifierGenerator.GENERATOR_NAME, generatorName ); parameters.put( IdentifierGenerator.GENERATOR_NAME, generatorName );
if ( !isEmptyAnnotationValue( generatorName ) ) { if ( !generatorName.isEmpty() ) {
//we have a named generator //we have a named generator
final IdentifierGeneratorDefinition definition = makeIdentifierGeneratorDefinition( final IdentifierGeneratorDefinition definition = makeIdentifierGeneratorDefinition(
generatorName, generatorName,
@ -858,19 +857,6 @@ public class BinderHelper {
return generatedValueAnn.strategy() == null ? GenerationType.AUTO : generatedValueAnn.strategy(); return generatedValueAnn.strategy() == null ? GenerationType.AUTO : generatedValueAnn.strategy();
} }
public static boolean isEmptyAnnotationValue(String annotationString) {
return annotationString != null && annotationString.isEmpty();
//equivalent to (but faster) ANNOTATION_STRING_DEFAULT.equals( annotationString );
}
public static boolean isEmptyOrNullAnnotationValue(String annotationString) {
return annotationString == null || annotationString.isEmpty();
}
public static String getAnnotationValueStringOrNull(String value) {
return isEmptyOrNullAnnotationValue( value ) ? null : value;
}
public static Any buildAnyValue( public static Any buildAnyValue(
jakarta.persistence.Column discriminatorColumn, jakarta.persistence.Column discriminatorColumn,
Formula discriminatorFormula, Formula discriminatorFormula,

View File

@ -33,6 +33,8 @@ import org.hibernate.mapping.Table;
import org.hibernate.mapping.ToOne; import org.hibernate.mapping.ToOne;
import org.hibernate.mapping.Value; import org.hibernate.mapping.Value;
import static org.hibernate.internal.util.StringHelper.isEmpty;
/** /**
* @author Emmanuel Bernard * @author Emmanuel Bernard
@ -106,7 +108,7 @@ public class ClassPropertyHolder extends AbstractPropertyHolder {
final Convert convertAnnotation = xClass.getAnnotation( Convert.class ); final Convert convertAnnotation = xClass.getAnnotation( Convert.class );
if ( convertAnnotation != null ) { if ( convertAnnotation != null ) {
final AttributeConversionInfo info = new AttributeConversionInfo( convertAnnotation, xClass ); final AttributeConversionInfo info = new AttributeConversionInfo( convertAnnotation, xClass );
if ( StringHelper.isEmpty( info.getAttributeName() ) ) { if ( isEmpty( info.getAttributeName() ) ) {
throw new IllegalStateException( "@Convert placed on @Entity/@MappedSuperclass must define attributeName" ); throw new IllegalStateException( "@Convert placed on @Entity/@MappedSuperclass must define attributeName" );
} }
infoMap.put( info.getAttributeName(), info ); infoMap.put( info.getAttributeName(), info );
@ -117,7 +119,7 @@ public class ClassPropertyHolder extends AbstractPropertyHolder {
if ( convertsAnnotation != null ) { if ( convertsAnnotation != null ) {
for ( Convert convertAnnotation : convertsAnnotation.value() ) { for ( Convert convertAnnotation : convertsAnnotation.value() ) {
final AttributeConversionInfo info = new AttributeConversionInfo( convertAnnotation, xClass ); final AttributeConversionInfo info = new AttributeConversionInfo( convertAnnotation, xClass );
if ( StringHelper.isEmpty( info.getAttributeName() ) ) { if ( isEmpty( info.getAttributeName() ) ) {
throw new IllegalStateException( "@Converts placed on @Entity/@MappedSuperclass must define attributeName" ); throw new IllegalStateException( "@Converts placed on @Entity/@MappedSuperclass must define attributeName" );
} }
infoMap.put( info.getAttributeName(), info ); infoMap.put( info.getAttributeName(), info );
@ -142,7 +144,7 @@ public class ClassPropertyHolder extends AbstractPropertyHolder {
final Convert convertAnnotation = property.getAnnotation( Convert.class ); final Convert convertAnnotation = property.getAnnotation( Convert.class );
if ( convertAnnotation != null ) { if ( convertAnnotation != null ) {
final AttributeConversionInfo info = new AttributeConversionInfo( convertAnnotation, property ); final AttributeConversionInfo info = new AttributeConversionInfo( convertAnnotation, property );
if ( StringHelper.isEmpty( info.getAttributeName() ) ) { if ( isEmpty( info.getAttributeName() ) ) {
attributeConversionInfoMap.put( propertyName, info ); attributeConversionInfoMap.put( propertyName, info );
} }
else { else {
@ -156,7 +158,7 @@ public class ClassPropertyHolder extends AbstractPropertyHolder {
if ( convertsAnnotation != null ) { if ( convertsAnnotation != null ) {
for ( Convert convertAnnotation : convertsAnnotation.value() ) { for ( Convert convertAnnotation : convertsAnnotation.value() ) {
final AttributeConversionInfo info = new AttributeConversionInfo( convertAnnotation, property ); final AttributeConversionInfo info = new AttributeConversionInfo( convertAnnotation, property );
if ( StringHelper.isEmpty( info.getAttributeName() ) ) { if ( isEmpty( info.getAttributeName() ) ) {
attributeConversionInfoMap.put( propertyName, info ); attributeConversionInfoMap.put( propertyName, info );
} }
else { else {

View File

@ -39,6 +39,9 @@ import jakarta.persistence.MapKeyTemporal;
import jakarta.persistence.OneToMany; import jakarta.persistence.OneToMany;
import jakarta.persistence.Temporal; import jakarta.persistence.Temporal;
import static org.hibernate.internal.util.StringHelper.isEmpty;
import static org.hibernate.internal.util.StringHelper.isNotEmpty;
/** /**
* @author Emmanuel Bernard * @author Emmanuel Bernard
* @author Steve Ebersole * @author Steve Ebersole
@ -119,7 +122,7 @@ public class CollectionPropertyHolder extends AbstractPropertyHolder {
final AttributeConversionInfo info = new AttributeConversionInfo( convertAnnotation, collectionProperty ); final AttributeConversionInfo info = new AttributeConversionInfo( convertAnnotation, collectionProperty );
if ( collection.isMap() ) { if ( collection.isMap() ) {
boolean specCompliant = StringHelper.isNotEmpty( info.getAttributeName() ) boolean specCompliant = isNotEmpty( info.getAttributeName() )
&& ( info.getAttributeName().startsWith( "key" ) && ( info.getAttributeName().startsWith( "key" )
|| info.getAttributeName().startsWith( "value" ) ); || info.getAttributeName().startsWith( "value" ) );
if ( !specCompliant ) { if ( !specCompliant ) {
@ -127,7 +130,7 @@ public class CollectionPropertyHolder extends AbstractPropertyHolder {
} }
} }
if ( StringHelper.isEmpty( info.getAttributeName() ) ) { if ( isEmpty( info.getAttributeName() ) ) {
// the @Convert did not name an attribute... // the @Convert did not name an attribute...
if ( canElementBeConverted && canKeyBeConverted ) { if ( canElementBeConverted && canKeyBeConverted ) {
throw new IllegalStateException( throw new IllegalStateException(

View File

@ -36,6 +36,7 @@ import static org.hibernate.cfg.BinderHelper.getOverridableAnnotation;
import static org.hibernate.cfg.BinderHelper.getPath; import static org.hibernate.cfg.BinderHelper.getPath;
import static org.hibernate.cfg.BinderHelper.getPropertyOverriddenByMapperOrMapsId; import static org.hibernate.cfg.BinderHelper.getPropertyOverriddenByMapperOrMapsId;
import static org.hibernate.internal.util.StringHelper.isEmpty; import static org.hibernate.internal.util.StringHelper.isEmpty;
import static org.hibernate.internal.util.StringHelper.nullIfEmpty;
/** /**
* Do the initial discovery of columns metadata and apply defaults. * Do the initial discovery of columns metadata and apply defaults.
@ -119,28 +120,27 @@ class ColumnsBuilder {
} }
//set default values if needed //set default values if needed
if ( joinColumns == null && if ( joinColumns == null
( property.isAnnotationPresent( ManyToOne.class ) && ( property.isAnnotationPresent( ManyToOne.class )
|| property.isAnnotationPresent( OneToOne.class ) ) || property.isAnnotationPresent( OneToOne.class ) ) ) {
) {
joinColumns = buildDefaultJoinColumnsForToOne( property, inferredData ); joinColumns = buildDefaultJoinColumnsForToOne( property, inferredData );
} }
else if ( joinColumns == null && else if ( joinColumns == null
( property.isAnnotationPresent( OneToMany.class ) && ( property.isAnnotationPresent( OneToMany.class )
|| property.isAnnotationPresent( ElementCollection.class ) || property.isAnnotationPresent( ElementCollection.class ) ) ) {
) ) {
OneToMany oneToMany = property.getAnnotation( OneToMany.class ); OneToMany oneToMany = property.getAnnotation( OneToMany.class );
joinColumns = AnnotatedJoinColumns.buildJoinColumns( joinColumns = AnnotatedJoinColumns.buildJoinColumns(
null, null,
comment, comment,
oneToMany != null ? oneToMany.mappedBy() : "", oneToMany == null ? null : nullIfEmpty( oneToMany.mappedBy() ),
entityBinder.getSecondaryTables(), entityBinder.getSecondaryTables(),
propertyHolder, propertyHolder,
inferredData, inferredData,
buildingContext buildingContext
); );
} }
else if ( joinColumns == null && property.isAnnotationPresent( org.hibernate.annotations.Any.class ) ) { else if ( joinColumns == null
&& property.isAnnotationPresent( org.hibernate.annotations.Any.class ) ) {
throw new AnnotationException( "Property '" + getPath( propertyHolder, inferredData ) throw new AnnotationException( "Property '" + getPath( propertyHolder, inferredData )
+ "' is annotated '@Any' and must declare at least one '@JoinColumn'" ); + "' is annotated '@Any' and must declare at least one '@JoinColumn'" );
} }
@ -191,7 +191,7 @@ class ColumnsBuilder {
return AnnotatedJoinColumns.buildJoinColumns( return AnnotatedJoinColumns.buildJoinColumns(
null, null,
comment, comment,
oneToOneAnn != null ? oneToOneAnn.mappedBy() : null, oneToOneAnn == null ? null : nullIfEmpty( oneToOneAnn.mappedBy() ),
entityBinder.getSecondaryTables(), entityBinder.getSecondaryTables(),
propertyHolder, propertyHolder,
inferredData, inferredData,

View File

@ -29,6 +29,8 @@ import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property; import org.hibernate.mapping.Property;
import org.hibernate.mapping.Table; import org.hibernate.mapping.Table;
import static org.hibernate.internal.util.StringHelper.isEmpty;
/** /**
* PropertyHolder for composites (Embeddable/Embedded). * PropertyHolder for composites (Embeddable/Embedded).
* <p> * <p>
@ -135,7 +137,7 @@ public class ComponentPropertyHolder extends AbstractPropertyHolder {
final Convert convertAnnotation = embeddedXProperty.getAnnotation( Convert.class ); final Convert convertAnnotation = embeddedXProperty.getAnnotation( Convert.class );
if ( convertAnnotation != null ) { if ( convertAnnotation != null ) {
final AttributeConversionInfo info = new AttributeConversionInfo( convertAnnotation, embeddableXClass ); final AttributeConversionInfo info = new AttributeConversionInfo( convertAnnotation, embeddableXClass );
if ( StringHelper.isEmpty( info.getAttributeName() ) ) { if ( isEmpty( info.getAttributeName() ) ) {
throw new IllegalStateException( "Convert placed on Embedded attribute must define (sub)attributeName" ); throw new IllegalStateException( "Convert placed on Embedded attribute must define (sub)attributeName" );
} }
infoMap.put( info.getAttributeName(), info ); infoMap.put( info.getAttributeName(), info );
@ -147,7 +149,7 @@ public class ComponentPropertyHolder extends AbstractPropertyHolder {
if ( convertsAnnotation != null ) { if ( convertsAnnotation != null ) {
for ( Convert convertAnnotation : convertsAnnotation.value() ) { for ( Convert convertAnnotation : convertsAnnotation.value() ) {
final AttributeConversionInfo info = new AttributeConversionInfo( convertAnnotation, embeddableXClass ); final AttributeConversionInfo info = new AttributeConversionInfo( convertAnnotation, embeddableXClass );
if ( StringHelper.isEmpty( info.getAttributeName() ) ) { if ( isEmpty( info.getAttributeName() ) ) {
throw new IllegalStateException( "Convert placed on Embedded attribute must define (sub)attributeName" ); throw new IllegalStateException( "Convert placed on Embedded attribute must define (sub)attributeName" );
} }
infoMap.put( info.getAttributeName(), info ); infoMap.put( info.getAttributeName(), info );
@ -164,7 +166,7 @@ public class ComponentPropertyHolder extends AbstractPropertyHolder {
final Convert convertAnnotation = embeddableXClass.getAnnotation( Convert.class ); final Convert convertAnnotation = embeddableXClass.getAnnotation( Convert.class );
if ( convertAnnotation != null ) { if ( convertAnnotation != null ) {
final AttributeConversionInfo info = new AttributeConversionInfo( convertAnnotation, embeddableXClass ); final AttributeConversionInfo info = new AttributeConversionInfo( convertAnnotation, embeddableXClass );
if ( StringHelper.isEmpty( info.getAttributeName() ) ) { if ( isEmpty( info.getAttributeName() ) ) {
throw new IllegalStateException( "@Convert placed on @Embeddable must define attributeName" ); throw new IllegalStateException( "@Convert placed on @Embeddable must define attributeName" );
} }
infoMap.put( info.getAttributeName(), info ); infoMap.put( info.getAttributeName(), info );
@ -176,7 +178,7 @@ public class ComponentPropertyHolder extends AbstractPropertyHolder {
if ( convertsAnnotation != null ) { if ( convertsAnnotation != null ) {
for ( Convert convertAnnotation : convertsAnnotation.value() ) { for ( Convert convertAnnotation : convertsAnnotation.value() ) {
final AttributeConversionInfo info = new AttributeConversionInfo( convertAnnotation, embeddableXClass ); final AttributeConversionInfo info = new AttributeConversionInfo( convertAnnotation, embeddableXClass );
if ( StringHelper.isEmpty( info.getAttributeName() ) ) { if ( isEmpty( info.getAttributeName() ) ) {
throw new IllegalStateException( "@Converts placed on @Embeddable must define attributeName" ); throw new IllegalStateException( "@Converts placed on @Embeddable must define attributeName" );
} }
infoMap.put( info.getAttributeName(), info ); infoMap.put( info.getAttributeName(), info );

View File

@ -12,7 +12,7 @@ import org.hibernate.annotations.ListIndexBase;
import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.MetadataBuildingContext;
import org.hibernate.mapping.Join; import org.hibernate.mapping.Join;
import static org.hibernate.cfg.BinderHelper.isEmptyAnnotationValue; import static org.hibernate.internal.util.StringHelper.nullIfEmpty;
/** /**
* An {@link jakarta.persistence.OrderColumn} annotation * An {@link jakarta.persistence.OrderColumn} annotation
@ -98,8 +98,10 @@ public class IndexColumn extends AnnotatedColumn {
Map<String, Join> secondaryTables, Map<String, Join> secondaryTables,
MetadataBuildingContext context) { MetadataBuildingContext context) {
if ( orderColumn != null ) { if ( orderColumn != null ) {
final String sqlType = isEmptyAnnotationValue( orderColumn.columnDefinition() ) ? null : orderColumn.columnDefinition(); final String sqlType = nullIfEmpty( orderColumn.columnDefinition() );
final String name = isEmptyAnnotationValue( orderColumn.name() ) ? inferredData.getPropertyName() + "_ORDER" : orderColumn.name(); final String name = orderColumn.name().isEmpty()
? inferredData.getPropertyName() + "_ORDER"
: orderColumn.name();
final IndexColumn column = new IndexColumn(); final IndexColumn column = new IndexColumn();
column.setLogicalColumnName( name ); column.setLogicalColumnName( name );
column.setSqlType( sqlType ); column.setSqlType( sqlType );
@ -139,8 +141,10 @@ public class IndexColumn extends AnnotatedColumn {
PropertyData inferredData, PropertyData inferredData,
MetadataBuildingContext context) { MetadataBuildingContext context) {
if ( indexColumn != null ) { if ( indexColumn != null ) {
final String sqlType = isEmptyAnnotationValue( indexColumn.columnDefinition() ) ? null : indexColumn.columnDefinition(); final String sqlType = nullIfEmpty( indexColumn.columnDefinition() );
final String name = isEmptyAnnotationValue( indexColumn.name() ) ? inferredData.getPropertyName() : indexColumn.name(); final String name = indexColumn.name().isEmpty()
? inferredData.getPropertyName()
: indexColumn.name();
//TODO move it to a getter based system and remove the constructor //TODO move it to a getter based system and remove the constructor
final IndexColumn column = new IndexColumn(); final IndexColumn column = new IndexColumn();
column.setLogicalColumnName( name ); column.setLogicalColumnName( name );

View File

@ -33,10 +33,11 @@ import org.hibernate.type.ForeignKeyDirection;
import static org.hibernate.cfg.BinderHelper.findPropertyByName; import static org.hibernate.cfg.BinderHelper.findPropertyByName;
import static org.hibernate.cfg.BinderHelper.getPath; import static org.hibernate.cfg.BinderHelper.getPath;
import static org.hibernate.cfg.BinderHelper.isEmptyAnnotationValue;
import static org.hibernate.cfg.ToOneBinder.bindForeignKeyNameAndDefinition; import static org.hibernate.cfg.ToOneBinder.bindForeignKeyNameAndDefinition;
import static org.hibernate.cfg.ToOneBinder.getReferenceEntityName; import static org.hibernate.cfg.ToOneBinder.getReferenceEntityName;
import static org.hibernate.internal.util.StringHelper.qualify; import static org.hibernate.internal.util.StringHelper.qualify;
import static org.hibernate.type.ForeignKeyDirection.FROM_PARENT;
import static org.hibernate.type.ForeignKeyDirection.TO_PARENT;
/** /**
* We have to handle {@link jakarta.persistence.OneToOne} associations * We have to handle {@link jakarta.persistence.OneToOne} associations
@ -98,7 +99,7 @@ public class OneToOneSecondPass implements SecondPass {
XProperty property = inferredData.getProperty(); XProperty property = inferredData.getProperty();
ToOneBinder.defineFetchingStrategy( value, property, inferredData, propertyHolder ); ToOneBinder.defineFetchingStrategy( value, property, inferredData, propertyHolder );
//value.setFetchMode( fetchMode ); //value.setFetchMode( fetchMode );
value.setOnDeleteAction(onDeleteAction); value.setOnDeleteAction( onDeleteAction );
//value.setLazy( fetchMode != FetchMode.JOIN ); //value.setLazy( fetchMode != FetchMode.JOIN );
value.setConstrained( !optional ); value.setConstrained( !optional );
@ -119,20 +120,20 @@ public class OneToOneSecondPass implements SecondPass {
final Property result = binder.makeProperty(); final Property result = binder.makeProperty();
result.setOptional( optional ); result.setOptional( optional );
if ( isEmptyAnnotationValue( mappedBy ) ) { if ( mappedBy == null ) {
bindUnowned( persistentClasses, value, propertyName, result ); bindOwned( persistentClasses, value, propertyName, result );
} }
else { else {
bindOwned( persistentClasses, value, result ); bindUnowned( persistentClasses, value, result );
} }
value.sortProperties(); value.sortProperties();
} }
private ForeignKeyDirection getForeignKeyDirection() { private ForeignKeyDirection getForeignKeyDirection() {
return !isEmptyAnnotationValue( mappedBy ) ? ForeignKeyDirection.TO_PARENT : ForeignKeyDirection.FROM_PARENT; return mappedBy == null ? FROM_PARENT : TO_PARENT;
} }
private void bindOwned(Map<String, PersistentClass> persistentClasses, OneToOne oneToOne, Property property) { private void bindUnowned(Map<String, PersistentClass> persistentClasses, OneToOne oneToOne, Property property) {
oneToOne.setMappedByProperty( mappedBy ); oneToOne.setMappedByProperty( mappedBy );
final PersistentClass targetEntity = persistentClasses.get( oneToOne.getReferencedEntityName() ); final PersistentClass targetEntity = persistentClasses.get( oneToOne.getReferencedEntityName() );
if ( targetEntity == null ) { if ( targetEntity == null ) {
@ -237,7 +238,7 @@ public class OneToOneSecondPass implements SecondPass {
+ "' which does not exist in the target entity type '" + oneToOne.getReferencedEntityName() + "'" ); + "' which does not exist in the target entity type '" + oneToOne.getReferencedEntityName() + "'" );
} }
private void bindUnowned(Map<String, PersistentClass> persistentClasses, OneToOne oneToOne, String propertyName, Property property) { private void bindOwned(Map<String, PersistentClass> persistentClasses, OneToOne oneToOne, String propertyName, Property property) {
// we need to check if the columns are in the right order // we need to check if the columns are in the right order
// if not, then we need to create a many to one and formula // if not, then we need to create a many to one and formula
// but actually, since entities linked by a one to one need // but actually, since entities linked by a one to one need

View File

@ -49,7 +49,6 @@ import static org.hibernate.cfg.AnnotationBinder.matchIgnoreNotFoundWithFetchTyp
import static org.hibernate.cfg.BinderHelper.getCascadeStrategy; import static org.hibernate.cfg.BinderHelper.getCascadeStrategy;
import static org.hibernate.cfg.BinderHelper.getFetchMode; import static org.hibernate.cfg.BinderHelper.getFetchMode;
import static org.hibernate.cfg.BinderHelper.getPath; import static org.hibernate.cfg.BinderHelper.getPath;
import static org.hibernate.cfg.BinderHelper.isEmptyAnnotationValue;
import static org.hibernate.internal.CoreLogging.messageLogger; import static org.hibernate.internal.CoreLogging.messageLogger;
import static org.hibernate.internal.util.StringHelper.isNotEmpty; import static org.hibernate.internal.util.StringHelper.isNotEmpty;
import static org.hibernate.internal.util.StringHelper.nullIfEmpty; import static org.hibernate.internal.util.StringHelper.nullIfEmpty;
@ -221,14 +220,15 @@ public class ToOneBinder {
columnName = prop.getAnnotation( Column.class ).name(); columnName = prop.getAnnotation( Column.class ).name();
} }
if ( property.isAnnotationPresent( ManyToOne.class ) && joinColumn != null if ( property.isAnnotationPresent( ManyToOne.class ) && joinColumn != null ) {
&& ! isEmptyAnnotationValue( joinColumn.name() ) if ( !joinColumn.name().isEmpty()
&& joinColumn.name().equals( columnName ) && joinColumn.name().equals( columnName )
&& !property.isAnnotationPresent( MapsId.class ) ) { && !property.isAnnotationPresent( MapsId.class ) ) {
hasSpecjManyToOne = true; hasSpecjManyToOne = true;
for ( AnnotatedJoinColumn column : columns.getJoinColumns() ) { for ( AnnotatedJoinColumn column : columns.getJoinColumns() ) {
column.setInsertable( false ); column.setInsertable( false );
column.setUpdatable( false ); column.setUpdatable( false );
}
} }
} }
} }
@ -424,7 +424,7 @@ public class ToOneBinder {
getTargetEntity( inferredData, context ), getTargetEntity( inferredData, context ),
propertyHolder, propertyHolder,
inferredData, inferredData,
oneToOne.mappedBy(), nullIfEmpty( oneToOne.mappedBy() ),
trueOneToOne, trueOneToOne,
isIdentifierMapper, isIdentifierMapper,
inSecondPass, inSecondPass,
@ -453,7 +453,7 @@ public class ToOneBinder {
final String propertyName = inferredData.getPropertyName(); final String propertyName = inferredData.getPropertyName();
LOG.tracev( "Fetching {0} with {1}", propertyName, fetchMode ); LOG.tracev( "Fetching {0} with {1}", propertyName, fetchMode );
if ( isMapToPK( joinColumns, propertyHolder, trueOneToOne ) if ( isMapToPK( joinColumns, propertyHolder, trueOneToOne )
|| !isEmptyAnnotationValue( mappedBy ) ) { || mappedBy != null ) {
//is a true one-to-one //is a true one-to-one
//FIXME referencedColumnName ignored => ordering may fail. //FIXME referencedColumnName ignored => ordering may fail.
final OneToOneSecondPass secondPass = new OneToOneSecondPass( final OneToOneSecondPass secondPass = new OneToOneSecondPass(
@ -474,7 +474,7 @@ public class ToOneBinder {
secondPass.doSecondPass( context.getMetadataCollector().getEntityBindingMap() ); secondPass.doSecondPass( context.getMetadataCollector().getEntityBindingMap() );
} }
else { else {
context.getMetadataCollector().addSecondPass( secondPass, isEmptyAnnotationValue( mappedBy ) ); context.getMetadataCollector().addSecondPass( secondPass, mappedBy == null );
} }
} }
else { else {

View File

@ -9,6 +9,7 @@ package org.hibernate.cfg.annotations;
import java.util.function.Supplier; import java.util.function.Supplier;
import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.MetadataBuildingContext;
import org.hibernate.mapping.Bag;
import org.hibernate.mapping.Collection; import org.hibernate.mapping.Collection;
import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.PersistentClass;
import org.hibernate.resource.beans.spi.ManagedBean; import org.hibernate.resource.beans.spi.ManagedBean;
@ -16,7 +17,7 @@ import org.hibernate.usertype.UserCollectionType;
/** /**
* A {@link CollectionBinder} for {@link org.hibernate.collection.spi.PersistentBag bags}, * A {@link CollectionBinder} for {@link org.hibernate.collection.spi.PersistentBag bags},
* whose mapping model type is {@link org.hibernate.mapping.Bag}. * whose mapping model type is {@link Bag}.
* *
* @author Matthew Inger * @author Matthew Inger
*/ */
@ -29,6 +30,6 @@ public class BagBinder extends CollectionBinder {
} }
protected Collection createCollection(PersistentClass owner) { protected Collection createCollection(PersistentClass owner) {
return new org.hibernate.mapping.Bag( getCustomTypeBeanResolver(), owner, getBuildingContext() ); return new Bag( getCustomTypeBeanResolver(), owner, getBuildingContext() );
} }
} }

View File

@ -165,7 +165,6 @@ import static org.hibernate.cfg.BinderHelper.getCascadeStrategy;
import static org.hibernate.cfg.BinderHelper.getFetchMode; import static org.hibernate.cfg.BinderHelper.getFetchMode;
import static org.hibernate.cfg.BinderHelper.getOverridableAnnotation; import static org.hibernate.cfg.BinderHelper.getOverridableAnnotation;
import static org.hibernate.cfg.BinderHelper.getPath; import static org.hibernate.cfg.BinderHelper.getPath;
import static org.hibernate.cfg.BinderHelper.isEmptyAnnotationValue;
import static org.hibernate.cfg.BinderHelper.isPrimitive; import static org.hibernate.cfg.BinderHelper.isPrimitive;
import static org.hibernate.cfg.BinderHelper.toAliasEntityMap; import static org.hibernate.cfg.BinderHelper.toAliasEntityMap;
import static org.hibernate.cfg.BinderHelper.toAliasTableMap; import static org.hibernate.cfg.BinderHelper.toAliasTableMap;
@ -213,6 +212,7 @@ public abstract class CollectionBinder {
private boolean oneToMany; private boolean oneToMany;
protected IndexColumn indexColumn; protected IndexColumn indexColumn;
protected OnDeleteAction onDeleteAction; protected OnDeleteAction onDeleteAction;
protected boolean hasMapKeyProperty;
protected String mapKeyPropertyName; protected String mapKeyPropertyName;
private boolean insertable = true; private boolean insertable = true;
private boolean updatable = true; private boolean updatable = true;
@ -320,8 +320,8 @@ public abstract class CollectionBinder {
entityBinder, entityBinder,
context, context,
property, property,
comment) comment
); ) );
bindJoinedTableAssociation( bindJoinedTableAssociation(
property, property,
@ -415,7 +415,7 @@ public abstract class CollectionBinder {
ElementCollection elementCollectionAnn) { ElementCollection elementCollectionAnn) {
if ( ( oneToManyAnn != null || manyToManyAnn != null || elementCollectionAnn != null ) if ( ( oneToManyAnn != null || manyToManyAnn != null || elementCollectionAnn != null )
&& isToManyAssociationWithinEmbeddableCollection(propertyHolder) ) { && isToManyAssociationWithinEmbeddableCollection(propertyHolder) ) {
String ann = oneToManyAnn !=null ? "'@OneToMany'" : manyToManyAnn !=null ? "'@ManyToMany'" : "'@ElementCollection'"; String ann = oneToManyAnn != null ? "'@OneToMany'" : manyToManyAnn !=null ? "'@ManyToMany'" : "'@ElementCollection'";
throw new AnnotationException( "Property '" + getPath(propertyHolder, inferredData) + throw new AnnotationException( "Property '" + getPath(propertyHolder, inferredData) +
"' belongs to an '@Embeddable' class that is contained in an '@ElementCollection' and may not be a " + ann ); "' belongs to an '@Embeddable' class that is contained in an '@ElementCollection' and may not be a " + ann );
} }
@ -469,7 +469,7 @@ public abstract class CollectionBinder {
throw new NotYetImplementedException( "Collections having FK in secondary table" ); throw new NotYetImplementedException( "Collections having FK in secondary table" );
} }
collectionBinder.setFkJoinColumns( joinColumns ); collectionBinder.setFkJoinColumns( joinColumns );
mappedBy = oneToManyAnn.mappedBy(); mappedBy = nullIfEmpty( oneToManyAnn.mappedBy() );
//noinspection unchecked //noinspection unchecked
collectionBinder.setTargetEntity( reflectionManager.toXClass( oneToManyAnn.targetEntity() ) ); collectionBinder.setTargetEntity( reflectionManager.toXClass( oneToManyAnn.targetEntity() ) );
collectionBinder.setCascadeStrategy( collectionBinder.setCascadeStrategy(
@ -483,14 +483,14 @@ public abstract class CollectionBinder {
throw new NotYetImplementedException( "Collections having FK in secondary table" ); throw new NotYetImplementedException( "Collections having FK in secondary table" );
} }
collectionBinder.setFkJoinColumns( joinColumns ); collectionBinder.setFkJoinColumns( joinColumns );
mappedBy = ""; mappedBy = null;
final Class<?> targetElement = elementCollectionAnn.targetClass(); final Class<?> targetElement = elementCollectionAnn.targetClass();
collectionBinder.setTargetEntity( reflectionManager.toXClass( targetElement ) ); collectionBinder.setTargetEntity( reflectionManager.toXClass( targetElement ) );
//collectionBinder.setCascadeStrategy( getCascadeStrategy( embeddedCollectionAnn.cascade(), hibernateCascade ) ); //collectionBinder.setCascadeStrategy( getCascadeStrategy( embeddedCollectionAnn.cascade(), hibernateCascade ) );
collectionBinder.setOneToMany( true ); collectionBinder.setOneToMany( true );
} }
else if ( manyToManyAnn != null ) { else if ( manyToManyAnn != null ) {
mappedBy = manyToManyAnn.mappedBy(); mappedBy = nullIfEmpty( manyToManyAnn.mappedBy() );
//noinspection unchecked //noinspection unchecked
collectionBinder.setTargetEntity( reflectionManager.toXClass( manyToManyAnn.targetEntity() ) ); collectionBinder.setTargetEntity( reflectionManager.toXClass( manyToManyAnn.targetEntity() ) );
collectionBinder.setCascadeStrategy( collectionBinder.setCascadeStrategy(
@ -499,7 +499,7 @@ public abstract class CollectionBinder {
collectionBinder.setOneToMany( false ); collectionBinder.setOneToMany( false );
} }
else if ( property.isAnnotationPresent( ManyToAny.class ) ) { else if ( property.isAnnotationPresent( ManyToAny.class ) ) {
mappedBy = ""; mappedBy = null;
collectionBinder.setTargetEntity( reflectionManager.toXClass( void.class ) ); collectionBinder.setTargetEntity( reflectionManager.toXClass( void.class ) );
collectionBinder.setCascadeStrategy( collectionBinder.setCascadeStrategy(
getCascadeStrategy( null, hibernateCascade, false, false ) getCascadeStrategy( null, hibernateCascade, false, false )
@ -681,13 +681,13 @@ public abstract class CollectionBinder {
if ( jpaIndexes != null && jpaIndexes.length > 0 ) { if ( jpaIndexes != null && jpaIndexes.length > 0 ) {
associationTableBinder.setJpaIndex( jpaIndexes ); associationTableBinder.setJpaIndex( jpaIndexes );
} }
if ( !isEmptyAnnotationValue( schema ) ) { if ( !schema.isEmpty() ) {
associationTableBinder.setSchema( schema ); associationTableBinder.setSchema( schema );
} }
if ( !isEmptyAnnotationValue( catalog ) ) { if ( !catalog.isEmpty() ) {
associationTableBinder.setCatalog( catalog ); associationTableBinder.setCatalog( catalog );
} }
if ( !isEmptyAnnotationValue( tableName ) ) { if ( !tableName.isEmpty() ) {
associationTableBinder.setName( tableName ); associationTableBinder.setName( tableName );
} }
associationTableBinder.setUniqueConstraints( uniqueConstraints ); associationTableBinder.setUniqueConstraints( uniqueConstraints );
@ -1047,12 +1047,12 @@ public abstract class CollectionBinder {
return CollectionClassification.BAG; return CollectionClassification.BAG;
} }
ManyToMany manyToMany = property.getAnnotation( ManyToMany.class ); ManyToMany manyToMany = property.getAnnotation( ManyToMany.class );
if ( manyToMany != null && ! isEmpty( manyToMany.mappedBy() ) ) { if ( manyToMany != null && !manyToMany.mappedBy().isEmpty() ) {
// We don't support @OrderColumn on the non-owning side of a many-to-many association. // We don't support @OrderColumn on the non-owning side of a many-to-many association.
return CollectionClassification.BAG; return CollectionClassification.BAG;
} }
OneToMany oneToMany = property.getAnnotation( OneToMany.class ); OneToMany oneToMany = property.getAnnotation( OneToMany.class );
if ( oneToMany != null && ! isEmpty( oneToMany.mappedBy() ) ) { if ( oneToMany != null && !oneToMany.mappedBy().isEmpty() ) {
// Unowned to-many mappings are always considered BAG by default // Unowned to-many mappings are always considered BAG by default
return CollectionClassification.BAG; return CollectionClassification.BAG;
} }
@ -1113,7 +1113,7 @@ public abstract class CollectionBinder {
} }
public void setMappedBy(String mappedBy) { public void setMappedBy(String mappedBy) {
this.mappedBy = mappedBy; this.mappedBy = nullIfEmpty( mappedBy );
} }
public void setTableBinder(TableBinder tableBinder) { public void setTableBinder(TableBinder tableBinder) {
@ -1160,7 +1160,7 @@ public abstract class CollectionBinder {
boolean isUnowned = isUnownedCollection(); boolean isUnowned = isUnownedCollection();
bindOptimisticLock( isUnowned ); bindOptimisticLock( isUnowned );
bindCustomPersister(); bindCustomPersister();
applySortingAndOrdering( collection ); applySortingAndOrdering();
bindCache(); bindCache();
bindLoader(); bindLoader();
detectMappedByProblem( isUnowned ); detectMappedByProblem( isUnowned );
@ -1173,15 +1173,15 @@ public abstract class CollectionBinder {
} }
private boolean isUnownedCollection() { private boolean isUnownedCollection() {
return !isEmptyAnnotationValue( mappedBy ); return mappedBy != null;
} }
private boolean isMutable() { private boolean isMutable() {
return !property.isAnnotationPresent(Immutable.class); return !property.isAnnotationPresent( Immutable.class );
} }
private void checkMapKeyColumn() { private void checkMapKeyColumn() {
if ( property.isAnnotationPresent( MapKeyColumn.class ) && mapKeyPropertyName != null ) { if ( property.isAnnotationPresent( MapKeyColumn.class ) && hasMapKeyProperty ) {
throw new AnnotationException( "Collection '" + qualify( propertyHolder.getPath(), propertyName ) throw new AnnotationException( "Collection '" + qualify( propertyHolder.getPath(), propertyName )
+ "' is annotated both '@MapKey' and '@MapKeyColumn'" ); + "' is annotated both '@MapKey' and '@MapKeyColumn'" );
} }
@ -1342,7 +1342,7 @@ public abstract class CollectionBinder {
} }
} }
private void applySortingAndOrdering(Collection collection) { private void applySortingAndOrdering() {
if ( naturalSort != null && comparatorSort != null ) { if ( naturalSort != null && comparatorSort != null ) {
throw buildIllegalSortCombination(); throw buildIllegalSortCombination();
@ -1551,7 +1551,7 @@ public abstract class CollectionBinder {
} }
private boolean isReversePropertyInJoin(XClass elementType, PersistentClass persistentClass) { private boolean isReversePropertyInJoin(XClass elementType, PersistentClass persistentClass) {
if ( persistentClass != null && hasMappedBy() ) { if ( persistentClass != null && isUnownedCollection()) {
try { try {
return persistentClass.getJoinNumber( persistentClass.getRecursiveProperty( mappedBy ) ) != 0; return persistentClass.getJoinNumber( persistentClass.getRecursiveProperty( mappedBy ) ) != 0;
} }
@ -1576,17 +1576,13 @@ public abstract class CollectionBinder {
private boolean implicitJoinColumn() { private boolean implicitJoinColumn() {
return joinColumns.getJoinColumns().get(0).isImplicit() return joinColumns.getJoinColumns().get(0).isImplicit()
&& hasMappedBy(); //implicit @JoinColumn && isUnownedCollection(); //implicit @JoinColumn
} }
private boolean explicitForeignJoinColumn() { private boolean explicitForeignJoinColumn() {
return !foreignJoinColumns.getJoinColumns().get(0).isImplicit(); //this is an explicit @JoinColumn return !foreignJoinColumns.getJoinColumns().get(0).isImplicit(); //this is an explicit @JoinColumn
} }
private boolean hasMappedBy() {
return isNotEmpty( mappedBy );
}
/** /**
* Bind a {@link OneToMany} association. * Bind a {@link OneToMany} association.
*/ */
@ -1804,12 +1800,12 @@ public abstract class CollectionBinder {
private String getFilterConditionForJoinTable(FilterJoinTable filter) { private String getFilterConditionForJoinTable(FilterJoinTable filter) {
final String condition = filter.condition(); final String condition = filter.condition();
return isEmptyAnnotationValue( condition ) ? getDefaultFilterCondition( filter.name(), filter ) : condition; return condition.isEmpty() ? getDefaultFilterCondition( filter.name(), filter ) : condition;
} }
private String getFilterCondition(Filter filter) { private String getFilterCondition(Filter filter) {
final String condition = filter.condition(); final String condition = filter.condition();
return isEmptyAnnotationValue( condition ) ? getDefaultFilterCondition( filter.name(), filter ) : condition; return condition.isEmpty() ? getDefaultFilterCondition( filter.name(), filter ) : condition;
} }
private String getDefaultFilterCondition(String name, Annotation annotation) { private String getDefaultFilterCondition(String name, Annotation annotation) {
@ -1829,10 +1825,10 @@ public abstract class CollectionBinder {
return defaultCondition; return defaultCondition;
} }
public void setCache(Cache cacheAnn) { public void setCache(Cache cache) {
if ( cacheAnn != null ) { if ( cache != null ) {
cacheRegionName = isEmptyAnnotationValue( cacheAnn.region() ) ? null : cacheAnn.region(); cacheRegionName = nullIfEmpty(cache.region());
cacheConcurrencyStrategy = EntityBinder.getCacheConcurrencyStrategy( cacheAnn.usage() ); cacheConcurrencyStrategy = EntityBinder.getCacheConcurrencyStrategy( cache.usage() );
} }
else { else {
cacheConcurrencyStrategy = null; cacheConcurrencyStrategy = null;
@ -1849,22 +1845,26 @@ public abstract class CollectionBinder {
} }
public void setMapKey(MapKey key) { public void setMapKey(MapKey key) {
if ( key != null ) { hasMapKeyProperty = key != null;
mapKeyPropertyName = key.name(); if ( hasMapKeyProperty ) {
mapKeyPropertyName = nullIfEmpty( key.name() );
} }
} }
private static String buildOrderByClauseFromHql(String orderByFragment, PersistentClass associatedClass) { private static String buildOrderByClauseFromHql(String orderByFragment, PersistentClass associatedClass) {
if ( orderByFragment != null ) { if ( orderByFragment == null ) {
if ( orderByFragment.length() == 0 ) { return null;
//order by id }
return buildOrderById( associatedClass, " asc" ); else if ( orderByFragment.isEmpty() ) {
} //order by id
else if ( "desc".equals( orderByFragment ) ) { return buildOrderById( associatedClass, " asc" );
return buildOrderById( associatedClass, " desc" ); }
} else if ( "desc".equalsIgnoreCase( orderByFragment ) ) {
return buildOrderById( associatedClass, " desc" );
}
else {
return orderByFragment;
} }
return orderByFragment;
} }
private static String buildOrderById(PersistentClass associatedClass, String order) { private static String buildOrderById(PersistentClass associatedClass, String order) {
@ -1933,7 +1933,7 @@ public abstract class CollectionBinder {
if ( property != null ) { if ( property != null ) {
final org.hibernate.annotations.ForeignKey fk = property.getAnnotation( org.hibernate.annotations.ForeignKey.class ); final org.hibernate.annotations.ForeignKey fk = property.getAnnotation( org.hibernate.annotations.ForeignKey.class );
if ( fk != null && !isEmptyAnnotationValue( fk.name() ) ) { if ( fk != null && !fk.name().isEmpty() ) {
key.setForeignKeyName( fk.name() ); key.setForeignKeyName( fk.name() );
} }
else { else {
@ -1963,9 +1963,9 @@ public abstract class CollectionBinder {
String foreignKeyName = foreignKey.name(); String foreignKeyName = foreignKey.name();
String foreignKeyDefinition = foreignKey.foreignKeyDefinition(); String foreignKeyDefinition = foreignKey.foreignKeyDefinition();
ConstraintMode foreignKeyValue = foreignKey.value(); ConstraintMode foreignKeyValue = foreignKey.value();
if ( joinTableAnn.joinColumns().length != 0 ) { if ( joinTableAnn.joinColumns().length > 0 ) {
final JoinColumn joinColumnAnn = joinTableAnn.joinColumns()[0]; final JoinColumn joinColumnAnn = joinTableAnn.joinColumns()[0];
if ( foreignKeyName != null && foreignKeyName.isEmpty() ) { if ( foreignKeyName.isEmpty() ) {
foreignKeyName = joinColumnAnn.foreignKey().name(); foreignKeyName = joinColumnAnn.foreignKey().name();
foreignKeyDefinition = joinColumnAnn.foreignKey().foreignKeyDefinition(); foreignKeyDefinition = joinColumnAnn.foreignKey().foreignKeyDefinition();
} }
@ -2026,7 +2026,7 @@ public abstract class CollectionBinder {
} }
private void overrideReferencedPropertyName(Collection collection, AnnotatedJoinColumns joinColumns) { private void overrideReferencedPropertyName(Collection collection, AnnotatedJoinColumns joinColumns) {
if ( hasMappedBy() && !joinColumns.getColumns().isEmpty() ) { if ( isUnownedCollection() && !joinColumns.getColumns().isEmpty() ) {
final String entityName = joinColumns.getManyToManyOwnerSideEntityName() != null final String entityName = joinColumns.getManyToManyOwnerSideEntityName() != null
? "inverse__" + joinColumns.getManyToManyOwnerSideEntityName() ? "inverse__" + joinColumns.getManyToManyOwnerSideEntityName()
: joinColumns.getPropertyHolder().getEntityName(); : joinColumns.getPropertyHolder().getEntityName();
@ -2065,7 +2065,7 @@ public abstract class CollectionBinder {
isManyToAny isManyToAny
); );
if ( hasMappedBy() ) { if (isUnownedCollection()) {
handleUnownedManyToMany( handleUnownedManyToMany(
collection, collection,
joinColumns, joinColumns,
@ -2324,7 +2324,7 @@ public abstract class CollectionBinder {
} }
final org.hibernate.annotations.ForeignKey fk = property.getAnnotation( org.hibernate.annotations.ForeignKey.class ); final org.hibernate.annotations.ForeignKey fk = property.getAnnotation( org.hibernate.annotations.ForeignKey.class );
if ( fk != null && !isEmptyAnnotationValue( fk.name() ) ) { if ( fk != null && !fk.name().isEmpty() ) {
element.setForeignKeyName( fk.name() ); element.setForeignKeyName( fk.name() );
} }
else { else {
@ -2334,7 +2334,7 @@ public abstract class CollectionBinder {
String foreignKeyDefinition = joinTableAnn.inverseForeignKey().foreignKeyDefinition(); String foreignKeyDefinition = joinTableAnn.inverseForeignKey().foreignKeyDefinition();
if ( joinTableAnn.inverseJoinColumns().length != 0 ) { if ( joinTableAnn.inverseJoinColumns().length != 0 ) {
final JoinColumn joinColumnAnn = joinTableAnn.inverseJoinColumns()[0]; final JoinColumn joinColumnAnn = joinTableAnn.inverseJoinColumns()[0];
if ( foreignKeyName != null && foreignKeyName.isEmpty() ) { if ( foreignKeyName.isEmpty() ) {
foreignKeyName = joinColumnAnn.foreignKey().name(); foreignKeyName = joinColumnAnn.foreignKey().name();
foreignKeyDefinition = joinColumnAnn.foreignKey().foreignKeyDefinition(); foreignKeyDefinition = joinColumnAnn.foreignKey().foreignKeyDefinition();
} }
@ -2581,7 +2581,7 @@ public abstract class CollectionBinder {
AnnotatedJoinColumns joinColumns, AnnotatedJoinColumns joinColumns,
OnDeleteAction onDeleteAction) { OnDeleteAction onDeleteAction) {
if ( !hasMappedBy() ) { if ( !isUnownedCollection()) {
createSyntheticPropertyReference( createSyntheticPropertyReference(
joinColumns, joinColumns,
collection.getOwner(), collection.getOwner(),
@ -2637,7 +2637,7 @@ public abstract class CollectionBinder {
AnnotatedJoinColumns joinColumns, AnnotatedJoinColumns joinColumns,
SimpleValue value, SimpleValue value,
boolean unique) { boolean unique) {
if ( hasMappedBy() ) { if (isUnownedCollection()) {
bindUnownedManyToManyInverseForeignKey( targetEntity, joinColumns, value ); bindUnownedManyToManyInverseForeignKey( targetEntity, joinColumns, value );
} }
else { else {

View File

@ -142,8 +142,6 @@ import static org.hibernate.cfg.AnnotatedJoinColumn.buildInheritanceJoinColumn;
import static org.hibernate.cfg.BinderHelper.getMappedSuperclassOrNull; import static org.hibernate.cfg.BinderHelper.getMappedSuperclassOrNull;
import static org.hibernate.cfg.BinderHelper.getOverridableAnnotation; import static org.hibernate.cfg.BinderHelper.getOverridableAnnotation;
import static org.hibernate.cfg.BinderHelper.hasToOneAnnotation; import static org.hibernate.cfg.BinderHelper.hasToOneAnnotation;
import static org.hibernate.cfg.BinderHelper.isEmptyAnnotationValue;
import static org.hibernate.cfg.BinderHelper.isEmptyOrNullAnnotationValue;
import static org.hibernate.cfg.BinderHelper.makeIdGenerator; import static org.hibernate.cfg.BinderHelper.makeIdGenerator;
import static org.hibernate.cfg.BinderHelper.toAliasEntityMap; import static org.hibernate.cfg.BinderHelper.toAliasEntityMap;
import static org.hibernate.cfg.BinderHelper.toAliasTableMap; import static org.hibernate.cfg.BinderHelper.toAliasTableMap;
@ -703,7 +701,7 @@ public class EntityBinder {
private static void handleForeignKeys(XClass clazzToProcess, MetadataBuildingContext context, DependantValue key) { private static void handleForeignKeys(XClass clazzToProcess, MetadataBuildingContext context, DependantValue key) {
final ForeignKey foreignKey = clazzToProcess.getAnnotation( ForeignKey.class ); final ForeignKey foreignKey = clazzToProcess.getAnnotation( ForeignKey.class );
if ( foreignKey != null && !isEmptyAnnotationValue( foreignKey.name() ) ) { if ( foreignKey != null && !foreignKey.name().isEmpty() ) {
key.setForeignKeyName( foreignKey.name() ); key.setForeignKeyName( foreignKey.name() );
} }
else { else {
@ -715,9 +713,9 @@ public class EntityBinder {
// don't apply a constraint based on ConstraintMode // don't apply a constraint based on ConstraintMode
key.disableForeignKey(); key.disableForeignKey();
} }
else if ( pkJoinColumns != null && !StringHelper.isEmpty( pkJoinColumns.foreignKey().name() ) ) { else if ( pkJoinColumns != null && isNotEmpty( pkJoinColumns.foreignKey().name() ) ) {
key.setForeignKeyName( pkJoinColumns.foreignKey().name() ); key.setForeignKeyName( pkJoinColumns.foreignKey().name() );
if ( !isEmptyAnnotationValue( pkJoinColumns.foreignKey().foreignKeyDefinition() ) ) { if ( !pkJoinColumns.foreignKey().foreignKeyDefinition().isEmpty() ) {
key.setForeignKeyDefinition( pkJoinColumns.foreignKey().foreignKeyDefinition() ); key.setForeignKeyDefinition( pkJoinColumns.foreignKey().foreignKeyDefinition() );
} }
} }
@ -726,9 +724,9 @@ public class EntityBinder {
// don't apply a constraint based on ConstraintMode // don't apply a constraint based on ConstraintMode
key.disableForeignKey(); key.disableForeignKey();
} }
else if ( pkJoinColumn != null && !StringHelper.isEmpty( pkJoinColumn.foreignKey().name() ) ) { else if ( pkJoinColumn != null && isNotEmpty( pkJoinColumn.foreignKey().name() ) ) {
key.setForeignKeyName( pkJoinColumn.foreignKey().name() ); key.setForeignKeyName( pkJoinColumn.foreignKey().name() );
if ( !isEmptyAnnotationValue( pkJoinColumn.foreignKey().foreignKeyDefinition() ) ) { if ( !pkJoinColumn.foreignKey().foreignKeyDefinition().isEmpty() ) {
key.setForeignKeyDefinition( pkJoinColumn.foreignKey().foreignKeyDefinition() ); key.setForeignKeyDefinition( pkJoinColumn.foreignKey().foreignKeyDefinition() );
} }
} }
@ -1063,7 +1061,8 @@ public class EntityBinder {
if ( entity == null ) { if ( entity == null ) {
throw new AssertionFailure( "@Entity should never be missing" ); throw new AssertionFailure( "@Entity should never be missing" );
} }
name = isEmptyAnnotationValue( entity.name() ) ? unqualify( annotatedClass.getName() ) : entity.name(); final String entityName = entity.name();
name = entityName.isEmpty() ? unqualify( annotatedClass.getName() ) : entityName;
} }
public boolean isRootEntity() { public boolean isRootEntity() {
@ -1201,7 +1200,7 @@ public class EntityBinder {
private void bindFilters() { private void bindFilters() {
for ( Filter filter : filters ) { for ( Filter filter : filters ) {
String condition = filter.condition(); String condition = filter.condition();
if ( isEmptyAnnotationValue( condition ) ) { if ( condition.isEmpty() ) {
condition = getDefaultFilterCondition( filter.name() ); condition = getDefaultFilterCondition( filter.name() );
} }
persistentClass.addFilter( persistentClass.addFilter(
@ -1284,7 +1283,7 @@ public class EntityBinder {
final String discriminatorValue = annotatedClass.isAnnotationPresent( DiscriminatorValue.class ) final String discriminatorValue = annotatedClass.isAnnotationPresent( DiscriminatorValue.class )
? annotatedClass.getAnnotation( DiscriminatorValue.class ).value() ? annotatedClass.getAnnotation( DiscriminatorValue.class ).value()
: null; : null;
if ( isEmptyOrNullAnnotationValue( discriminatorValue ) ) { if ( isEmpty( discriminatorValue ) ) {
final Value discriminator = persistentClass.getDiscriminator(); final Value discriminator = persistentClass.getDiscriminator();
if ( discriminator == null ) { if ( discriminator == null ) {
persistentClass.setDiscriminatorValue( name ); persistentClass.setDiscriminatorValue( name );
@ -1371,7 +1370,7 @@ public class EntityBinder {
naturalIdCacheRegion = null; naturalIdCacheRegion = null;
final NaturalIdCache naturalIdCacheAnn = annotatedClass.getAnnotation( NaturalIdCache.class ); final NaturalIdCache naturalIdCacheAnn = annotatedClass.getAnnotation( NaturalIdCache.class );
if ( naturalIdCacheAnn != null ) { if ( naturalIdCacheAnn != null ) {
if ( isEmptyAnnotationValue( naturalIdCacheAnn.region() ) ) { if ( naturalIdCacheAnn.region().isEmpty() ) {
final Cache explicitCacheAnn = annotatedClass.getAnnotation( Cache.class ); final Cache explicitCacheAnn = annotatedClass.getAnnotation( Cache.class );
naturalIdCacheRegion = explicitCacheAnn != null && isNotEmpty( explicitCacheAnn.region() ) naturalIdCacheRegion = explicitCacheAnn != null && isNotEmpty( explicitCacheAnn.region() )
? explicitCacheAnn.region() + NATURAL_ID_CACHE_SUFFIX ? explicitCacheAnn.region() + NATURAL_ID_CACHE_SUFFIX
@ -1744,7 +1743,7 @@ public class EntityBinder {
final String tableName = join.getTable().getQuotedName(); final String tableName = join.getTable().getQuotedName();
final org.hibernate.annotations.Table matchingTable = findMatchingComplementaryTableAnnotation( tableName ); final org.hibernate.annotations.Table matchingTable = findMatchingComplementaryTableAnnotation( tableName );
final SimpleValue key = (SimpleValue) join.getKey(); final SimpleValue key = (SimpleValue) join.getKey();
if ( matchingTable != null && !isEmptyAnnotationValue( matchingTable.foreignKey().name() ) ) { if ( matchingTable != null && !matchingTable.foreignKey().name().isEmpty() ) {
key.setForeignKeyName( matchingTable.foreignKey().name() ); key.setForeignKeyName( matchingTable.foreignKey().name() );
} }
else { else {
@ -2017,7 +2016,7 @@ public class EntityBinder {
} }
else if ( matchingTable != null ) { else if ( matchingTable != null ) {
final String insertSql = matchingTable.sqlInsert().sql(); final String insertSql = matchingTable.sqlInsert().sql();
if ( !isEmptyAnnotationValue(insertSql) ) { if ( !insertSql.isEmpty() ) {
join.setCustomSQLInsert( join.setCustomSQLInsert(
insertSql.trim(), insertSql.trim(),
matchingTable.sqlInsert().callable(), matchingTable.sqlInsert().callable(),
@ -2036,7 +2035,7 @@ public class EntityBinder {
} }
else if ( matchingTable != null ) { else if ( matchingTable != null ) {
final String updateSql = matchingTable.sqlUpdate().sql(); final String updateSql = matchingTable.sqlUpdate().sql();
if ( !isEmptyAnnotationValue(updateSql) ) { if ( !updateSql.isEmpty() ) {
join.setCustomSQLUpdate( join.setCustomSQLUpdate(
updateSql.trim(), updateSql.trim(),
matchingTable.sqlUpdate().callable(), matchingTable.sqlUpdate().callable(),
@ -2055,7 +2054,7 @@ public class EntityBinder {
} }
else if ( matchingTable != null ) { else if ( matchingTable != null ) {
final String deleteSql = matchingTable.sqlDelete().sql(); final String deleteSql = matchingTable.sqlDelete().sql();
if ( !isEmptyAnnotationValue(deleteSql) ) { if ( !deleteSql.isEmpty() ) {
join.setCustomSQLDelete( join.setCustomSQLDelete(
deleteSql.trim(), deleteSql.trim(),
matchingTable.sqlDelete().callable(), matchingTable.sqlDelete().callable(),
@ -2095,10 +2094,10 @@ public class EntityBinder {
public void processComplementaryTableDefinitions(org.hibernate.annotations.Table table) { public void processComplementaryTableDefinitions(org.hibernate.annotations.Table table) {
if ( table != null ) { if ( table != null ) {
Table appliedTable = findTable( table.appliesTo() ); Table appliedTable = findTable( table.appliesTo() );
if ( !isEmptyAnnotationValue( table.comment() ) ) { if ( !table.comment().isEmpty() ) {
appliedTable.setComment( table.comment() ); appliedTable.setComment( table.comment() );
} }
if ( !isEmptyAnnotationValue( table.checkConstraint() ) ) { if ( !table.checkConstraint().isEmpty() ) {
appliedTable.addCheckConstraint( table.checkConstraint() ); appliedTable.addCheckConstraint( table.checkConstraint() );
} }
TableBinder.addIndexes( appliedTable, table.indexes(), context ); TableBinder.addIndexes( appliedTable, table.indexes(), context );

View File

@ -17,7 +17,6 @@ import org.hibernate.cfg.CollectionSecondPass;
import org.hibernate.cfg.PropertyHolder; import org.hibernate.cfg.PropertyHolder;
import org.hibernate.cfg.PropertyHolderBuilder; import org.hibernate.cfg.PropertyHolderBuilder;
import org.hibernate.cfg.SecondPass; import org.hibernate.cfg.SecondPass;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.mapping.Collection; import org.hibernate.mapping.Collection;
import org.hibernate.mapping.IndexBackref; import org.hibernate.mapping.IndexBackref;
import org.hibernate.mapping.List; import org.hibernate.mapping.List;
@ -27,8 +26,6 @@ import org.hibernate.mapping.SimpleValue;
import org.hibernate.resource.beans.spi.ManagedBean; import org.hibernate.resource.beans.spi.ManagedBean;
import org.hibernate.usertype.UserCollectionType; import org.hibernate.usertype.UserCollectionType;
import org.jboss.logging.Logger;
import static org.hibernate.internal.util.StringHelper.qualify; import static org.hibernate.internal.util.StringHelper.qualify;
/** /**
@ -45,6 +42,10 @@ public class ListBinder extends CollectionBinder {
super( customTypeBeanResolver, false, buildingContext ); super( customTypeBeanResolver, false, buildingContext );
} }
private List getList() {
return (List) collection;
}
@Override @Override
protected Collection createCollection(PersistentClass owner) { protected Collection createCollection(PersistentClass owner) {
return new List( getCustomTypeBeanResolver(), owner, getBuildingContext() ); return new List( getCustomTypeBeanResolver(), owner, getBuildingContext() );
@ -79,9 +80,7 @@ public class ListBinder extends CollectionBinder {
getBuildingContext() getBuildingContext()
); );
final List listValueMapping = (List) collection; if ( !collection.isOneToMany() ) {
if ( !listValueMapping.isOneToMany() ) {
indexColumn.forceNotNull(); indexColumn.forceNotNull();
} }
indexColumn.getParent().setPropertyHolder( valueHolder ); indexColumn.getParent().setPropertyHolder( valueHolder );
@ -93,24 +92,28 @@ public class ListBinder extends CollectionBinder {
// valueBinder.setExplicitType( "integer" ); // valueBinder.setExplicitType( "integer" );
final SimpleValue indexValue = valueBinder.make(); final SimpleValue indexValue = valueBinder.make();
indexColumn.linkWithValue( indexValue ); indexColumn.linkWithValue( indexValue );
listValueMapping.setIndex( indexValue );
listValueMapping.setBaseIndex( indexColumn.getBase() ); final List list = getList();
createBackref( listValueMapping ); list.setIndex( indexValue );
list.setBaseIndex( indexColumn.getBase() );
createBackref();
} }
private void createBackref(List listValueMapping) { private void createBackref() {
if ( listValueMapping.isOneToMany() if ( collection.isOneToMany()
&& !listValueMapping.getKey().isNullable() && !collection.getKey().isNullable()
&& !listValueMapping.isInverse() ) { && !collection.isInverse() ) {
final String entityName = ( (OneToMany) listValueMapping.getElement() ).getReferencedEntityName(); final String entityName = ( (OneToMany) collection.getElement() ).getReferencedEntityName();
final PersistentClass referenced = buildingContext.getMetadataCollector().getEntityBinding( entityName ); final PersistentClass referenced = buildingContext.getMetadataCollector().getEntityBinding( entityName );
final IndexBackref backref = new IndexBackref(); final IndexBackref backref = new IndexBackref();
backref.setName( '_' + propertyName + "IndexBackref" ); backref.setName( '_' + propertyName + "IndexBackref" );
backref.setUpdateable( false ); backref.setUpdateable( false );
backref.setSelectable( false ); backref.setSelectable( false );
backref.setCollectionRole( listValueMapping.getRole() ); backref.setCollectionRole( collection.getRole() );
backref.setEntityName( listValueMapping.getOwner().getEntityName() ); backref.setEntityName( collection.getOwner().getEntityName() );
backref.setValue( listValueMapping.getIndex() ); List list = getList();
backref.setValue( list.getIndex() );
referenced.addProperty( backref ); referenced.addProperty( backref );
} }
} }

View File

@ -7,7 +7,6 @@
package org.hibernate.cfg.annotations; package org.hibernate.cfg.annotations;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.function.Supplier; import java.util.function.Supplier;
import org.hibernate.AnnotationException; import org.hibernate.AnnotationException;
@ -38,6 +37,7 @@ import org.hibernate.mapping.Component;
import org.hibernate.mapping.DependantBasicValue; import org.hibernate.mapping.DependantBasicValue;
import org.hibernate.mapping.Formula; import org.hibernate.mapping.Formula;
import org.hibernate.mapping.ManyToOne; import org.hibernate.mapping.ManyToOne;
import org.hibernate.mapping.Map;
import org.hibernate.mapping.OneToMany; import org.hibernate.mapping.OneToMany;
import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property; import org.hibernate.mapping.Property;
@ -58,6 +58,7 @@ import jakarta.persistence.MapKeyColumn;
import jakarta.persistence.MapKeyJoinColumn; import jakarta.persistence.MapKeyJoinColumn;
import jakarta.persistence.MapKeyJoinColumns; import jakarta.persistence.MapKeyJoinColumns;
import static org.hibernate.cfg.AnnotatedClassType.EMBEDDABLE;
import static org.hibernate.cfg.BinderHelper.findPropertyByName; import static org.hibernate.cfg.BinderHelper.findPropertyByName;
import static org.hibernate.cfg.BinderHelper.isPrimitive; import static org.hibernate.cfg.BinderHelper.isPrimitive;
import static org.hibernate.cfg.PropertyHolderBuilder.buildPropertyHolder; import static org.hibernate.cfg.PropertyHolderBuilder.buildPropertyHolder;
@ -66,7 +67,7 @@ import static org.hibernate.internal.util.StringHelper.qualify;
/** /**
* A {@link CollectionBinder} for {@link org.hibernate.collection.spi.PersistentMap maps}, * A {@link CollectionBinder} for {@link org.hibernate.collection.spi.PersistentMap maps},
* whose mapping model type is {@link org.hibernate.mapping.Map}. * whose mapping model type is {@link Map}.
* *
* @author Emmanuel Bernard * @author Emmanuel Bernard
*/ */
@ -83,19 +84,24 @@ public class MapBinder extends CollectionBinder {
return true; return true;
} }
private Map getMap() {
return (Map) collection;
}
protected Collection createCollection(PersistentClass owner) { protected Collection createCollection(PersistentClass owner) {
return new org.hibernate.mapping.Map( getCustomTypeBeanResolver(), owner, getBuildingContext() ); return new Map( getCustomTypeBeanResolver(), owner, getBuildingContext() );
} }
@Override @Override
SecondPass getSecondPass() { SecondPass getSecondPass() {
return new CollectionSecondPass( MapBinder.this.collection ) { return new CollectionSecondPass( MapBinder.this.collection ) {
public void secondPass(Map<String, PersistentClass> persistentClasses) public void secondPass(java.util.Map<String, PersistentClass> persistentClasses)
throws MappingException { throws MappingException {
bindStarToManySecondPass( persistentClasses ); bindStarToManySecondPass( persistentClasses );
bindKeyFromAssociationTable( bindKeyFromAssociationTable(
getElementType(), getElementType(),
persistentClasses, persistentClasses,
hasMapKeyProperty,
mapKeyPropertyName, mapKeyPropertyName,
property, property,
isEmbedded, isEmbedded,
@ -109,7 +115,7 @@ public class MapBinder extends CollectionBinder {
private void makeOneToManyMapKeyColumnNullableIfNotInProperty( private void makeOneToManyMapKeyColumnNullableIfNotInProperty(
final XProperty property) { final XProperty property) {
final org.hibernate.mapping.Map map = (org.hibernate.mapping.Map) this.collection; final Map map = (Map) this.collection;
if ( map.isOneToMany() && if ( map.isOneToMany() &&
property.isAnnotationPresent( MapKeyColumn.class ) ) { property.isAnnotationPresent( MapKeyColumn.class ) ) {
final Value indexValue = map.getIndex(); final Value indexValue = map.getIndex();
@ -122,7 +128,7 @@ public class MapBinder extends CollectionBinder {
} }
final Column column = (Column) selectable; final Column column = (Column) selectable;
if ( !column.isNullable() ) { if ( !column.isNullable() ) {
final PersistentClass persistentClass = ( ( OneToMany ) map.getElement() ).getAssociatedClass(); final PersistentClass persistentClass = ( (OneToMany) map.getElement() ).getAssociatedClass();
// check if the index column has been mapped by the associated entity to a property; // check if the index column has been mapped by the associated entity to a property;
// @MapKeyColumn only maps a column to the primary table for the one-to-many, so we only // @MapKeyColumn only maps a column to the primary table for the one-to-many, so we only
// need to check "un-joined" properties. // need to check "un-joined" properties.
@ -151,35 +157,34 @@ public class MapBinder extends CollectionBinder {
private void bindKeyFromAssociationTable( private void bindKeyFromAssociationTable(
XClass elementType, XClass elementType,
Map<String, PersistentClass> persistentClasses, java.util.Map<String, PersistentClass> persistentClasses,
boolean hasMapKeyProperty,
String mapKeyPropertyName, String mapKeyPropertyName,
XProperty property, XProperty property,
boolean isEmbedded, boolean isEmbedded,
AnnotatedColumns mapKeyColumns, AnnotatedColumns mapKeyColumns,
AnnotatedJoinColumns mapKeyManyToManyColumns) { AnnotatedJoinColumns mapKeyManyToManyColumns) {
org.hibernate.mapping.Map map = (org.hibernate.mapping.Map) this.collection; if ( hasMapKeyProperty ) {
if ( mapKeyPropertyName != null ) {
//this is an EJB3 @MapKey //this is an EJB3 @MapKey
handleMapKeyProperty( elementType, persistentClasses, mapKeyPropertyName, map ); handleMapKeyProperty( elementType, persistentClasses, mapKeyPropertyName );
} }
else { else {
//this is a true Map mapping //this is a true Map mapping
handleMapKey( persistentClasses, property, isEmbedded, mapKeyColumns, mapKeyManyToManyColumns, map ); handleMapKey( persistentClasses, property, isEmbedded, mapKeyColumns, mapKeyManyToManyColumns );
} }
} }
private void handleMapKey( private void handleMapKey(
Map<String, PersistentClass> persistentClasses, java.util.Map<String, PersistentClass> persistentClasses,
XProperty property, XProperty property,
boolean isEmbedded, boolean isEmbedded,
AnnotatedColumns mapKeyColumns, AnnotatedColumns mapKeyColumns,
AnnotatedJoinColumns mapKeyManyToManyColumns, AnnotatedJoinColumns mapKeyManyToManyColumns) {
org.hibernate.mapping.Map map) {
final String mapKeyType = getKeyType( property ); final String mapKeyType = getKeyType( property );
final PersistentClass collectionEntity = persistentClasses.get( mapKeyType ); final PersistentClass collectionEntity = persistentClasses.get( mapKeyType );
final boolean isKeyedByEntities = collectionEntity != null; final boolean isKeyedByEntities = collectionEntity != null;
if ( isKeyedByEntities ) { if ( isKeyedByEntities ) {
final ManyToOne element = handleCollectionKeyedByEntities( buildingContext, mapKeyType, map ); final ManyToOne element = handleCollectionKeyedByEntities( mapKeyType );
handleForeignKey( property, element ); handleForeignKey( property, element );
// a map key column has no unique constraint, so pass 'unique=false' here // a map key column has no unique constraint, so pass 'unique=false' here
bindManyToManyInverseForeignKey( collectionEntity, mapKeyManyToManyColumns, element, false ); bindManyToManyInverseForeignKey( collectionEntity, mapKeyManyToManyColumns, element, false );
@ -190,11 +195,10 @@ public class MapBinder extends CollectionBinder {
property, property,
mapKeyColumns, mapKeyColumns,
mapKeyType, mapKeyType,
map,
keyClass, keyClass,
annotatedMapKeyType( property, isEmbedded, mapKeyType, keyClass ), annotatedMapKeyType( property, isEmbedded, mapKeyType, keyClass ),
buildCollectionPropertyHolder( property, map, keyClass ), buildCollectionPropertyHolder( property, keyClass ),
accessType( property, map.getOwner() ) accessType( property, collection.getOwner() )
); );
} }
//FIXME pass the Index Entity JoinColumns //FIXME pass the Index Entity JoinColumns
@ -217,7 +221,7 @@ public class MapBinder extends CollectionBinder {
else { else {
// force in case of attribute override naming the key // force in case of attribute override naming the key
return isEmbedded || mappingDefinedAttributeOverrideOnMapKey( property ) return isEmbedded || mappingDefinedAttributeOverrideOnMapKey( property )
? AnnotatedClassType.EMBEDDABLE ? EMBEDDABLE
: buildingContext.getMetadataCollector().getClassType( keyClass ); : buildingContext.getMetadataCollector().getClassType( keyClass );
} }
} }
@ -244,9 +248,8 @@ public class MapBinder extends CollectionBinder {
private void handleMapKeyProperty( private void handleMapKeyProperty(
XClass elementType, XClass elementType,
Map<String, PersistentClass> persistentClasses, java.util.Map<String, PersistentClass> persistentClasses,
String mapKeyPropertyName, String mapKeyPropertyName) {
org.hibernate.mapping.Map map) {
final PersistentClass associatedClass = persistentClasses.get( elementType.getName() ); final PersistentClass associatedClass = persistentClasses.get( elementType.getName() );
if ( associatedClass == null ) { if ( associatedClass == null ) {
throw new AnnotationException( "Association '" + safeCollectionRole() throw new AnnotationException( "Association '" + safeCollectionRole()
@ -262,18 +265,17 @@ public class MapBinder extends CollectionBinder {
final PersistentClass targetEntity = InheritanceType.JOINED == inheritanceState.getType() final PersistentClass targetEntity = InheritanceType.JOINED == inheritanceState.getType()
? mapProperty.getPersistentClass() ? mapProperty.getPersistentClass()
: associatedClass; : associatedClass;
final Value indexValue = createFormulatedValue( mapProperty.getValue(), map, associatedClass, targetEntity ); final Value indexValue = createFormulatedValue( mapProperty.getValue(), collection, associatedClass, targetEntity );
map.setIndex( indexValue ); getMap().setIndex( indexValue );
map.setMapKeyPropertyName( mapKeyPropertyName ); getMap().setMapKeyPropertyName( mapProperty.getName() );
} }
private CollectionPropertyHolder buildCollectionPropertyHolder( private CollectionPropertyHolder buildCollectionPropertyHolder(
XProperty property, XProperty property,
org.hibernate.mapping.Map map,
XClass keyClass) { XClass keyClass) {
final CollectionPropertyHolder holder = buildPropertyHolder( final CollectionPropertyHolder holder = buildPropertyHolder(
map, collection,
qualify( map.getRole(), "mapkey" ), qualify( collection.getRole(), "mapkey" ),
keyClass, keyClass,
property, property,
propertyHolder, propertyHolder,
@ -304,16 +306,14 @@ public class MapBinder extends CollectionBinder {
} }
//similar to CollectionBinder.handleCollectionOfEntities() //similar to CollectionBinder.handleCollectionOfEntities()
private static ManyToOne handleCollectionKeyedByEntities( private ManyToOne handleCollectionKeyedByEntities(
MetadataBuildingContext context, String mapKeyType) {
String mapKeyType, final ManyToOne element = new ManyToOne( buildingContext, collection.getCollectionTable() );
org.hibernate.mapping.Map map) { getMap().setIndex( element );
final ManyToOne element = new ManyToOne( context, map.getCollectionTable() );
map.setIndex( element );
element.setReferencedEntityName( mapKeyType ); element.setReferencedEntityName( mapKeyType );
//element.setFetchMode( fetchMode ); //element.setFetchMode( fetchMode );
//element.setLazy( fetchMode != FetchMode.JOIN ); //element.setLazy( fetchMode != FetchMode.JOIN );
//make the second join non lazy //make the second join non-lazy
element.setFetchMode( FetchMode.JOIN ); element.setFetchMode( FetchMode.JOIN );
element.setLazy( false ); element.setLazy( false );
//does not make sense for a map key element.setIgnoreNotFound( ignoreNotFound ); //does not make sense for a map key element.setIgnoreNotFound( ignoreNotFound );
@ -324,18 +324,17 @@ public class MapBinder extends CollectionBinder {
XProperty property, XProperty property,
AnnotatedColumns mapKeyColumns, AnnotatedColumns mapKeyColumns,
String mapKeyType, String mapKeyType,
org.hibernate.mapping.Map map,
XClass keyClass, XClass keyClass,
AnnotatedClassType classType, AnnotatedClassType classType,
CollectionPropertyHolder holder, CollectionPropertyHolder holder,
AccessType accessType) { AccessType accessType) {
final Class<? extends CompositeUserType<?>> compositeUserType = final Class<? extends CompositeUserType<?>> compositeUserType =
resolveCompositeUserType( property, keyClass, buildingContext ); resolveCompositeUserType( property, keyClass, buildingContext );
if ( AnnotatedClassType.EMBEDDABLE == classType || compositeUserType != null ) { if ( classType == EMBEDDABLE || compositeUserType != null ) {
handleCompositeMapKey( map, keyClass, holder, accessType, compositeUserType ); handleCompositeMapKey( keyClass, holder, accessType, compositeUserType );
} }
else { else {
handleMapKey( property, mapKeyColumns, mapKeyType, map, keyClass, holder, accessType ); handleMapKey( property, mapKeyColumns, mapKeyType, keyClass, holder, accessType );
} }
} }
@ -343,7 +342,7 @@ public class MapBinder extends CollectionBinder {
XProperty property, XProperty property,
AnnotatedColumns mapKeyColumns, AnnotatedColumns mapKeyColumns,
String mapKeyType, String mapKeyType,
org.hibernate.mapping.Map map, XClass keyClass, XClass keyClass,
CollectionPropertyHolder holder, CollectionPropertyHolder holder,
AccessType accessType) { AccessType accessType) {
final BasicValueBinder elementBinder = new BasicValueBinder( BasicValueBinder.Kind.MAP_KEY, buildingContext ); final BasicValueBinder elementBinder = new BasicValueBinder( BasicValueBinder.Kind.MAP_KEY, buildingContext );
@ -366,16 +365,15 @@ public class MapBinder extends CollectionBinder {
); );
elementBinder.setPersistentClassName( propertyHolder.getEntityName() ); elementBinder.setPersistentClassName( propertyHolder.getEntityName() );
elementBinder.setAccessType( accessType ); elementBinder.setAccessType( accessType );
map.setIndex( elementBinder.make() ); getMap().setIndex( elementBinder.make() );
} }
private void handleCompositeMapKey( private void handleCompositeMapKey(
org.hibernate.mapping.Map map,
XClass keyClass, XClass keyClass,
CollectionPropertyHolder holder, CollectionPropertyHolder holder,
AccessType accessType, AccessType accessType,
Class<? extends CompositeUserType<?>> compositeUserType) { Class<? extends CompositeUserType<?>> compositeUserType) {
map.setIndex( AnnotationBinder.fillComponent( getMap().setIndex( AnnotationBinder.fillComponent(
holder, holder,
propertyPreloadedData( keyClass ), propertyPreloadedData( keyClass ),
accessType, accessType,
@ -394,9 +392,9 @@ public class MapBinder extends CollectionBinder {
private PropertyPreloadedData propertyPreloadedData(XClass keyClass) { private PropertyPreloadedData propertyPreloadedData(XClass keyClass) {
return isHibernateExtensionMapping() return isHibernateExtensionMapping()
? new PropertyPreloadedData(AccessType.PROPERTY, "index", keyClass) ? new PropertyPreloadedData( AccessType.PROPERTY, "index", keyClass )
// "key" is the JPA 2 prefix for map keys // "key" is the JPA 2 prefix for map keys
: new PropertyPreloadedData(AccessType.PROPERTY, "key", keyClass); : new PropertyPreloadedData( AccessType.PROPERTY, "key", keyClass );
} }
private static Class<? extends CompositeUserType<?>> resolveCompositeUserType( private static Class<? extends CompositeUserType<?>> resolveCompositeUserType(

View File

@ -45,8 +45,7 @@ import jakarta.persistence.SqlResultSetMapping;
import jakarta.persistence.SqlResultSetMappings; import jakarta.persistence.SqlResultSetMappings;
import jakarta.persistence.StoredProcedureParameter; import jakarta.persistence.StoredProcedureParameter;
import static org.hibernate.cfg.BinderHelper.getAnnotationValueStringOrNull; import static org.hibernate.internal.util.StringHelper.nullIfEmpty;
import static org.hibernate.cfg.BinderHelper.isEmptyAnnotationValue;
import static org.hibernate.internal.util.collections.CollectionHelper.setOf; import static org.hibernate.internal.util.collections.CollectionHelper.setOf;
/** /**
@ -65,13 +64,13 @@ public abstract class QueryBinder {
return; return;
} }
if ( isEmptyAnnotationValue( namedQuery.name() ) ) {
throw new AnnotationException( "Class or package level '@NamedQuery' annotation must specify a 'name'" );
}
final String queryName = namedQuery.name(); final String queryName = namedQuery.name();
final String queryString = namedQuery.query(); final String queryString = namedQuery.query();
if ( queryName.isEmpty() ) {
throw new AnnotationException( "Class or package level '@NamedQuery' annotation must specify a 'name'" );
}
if ( LOG.isDebugEnabled() ) { if ( LOG.isDebugEnabled() ) {
LOG.debugf( "Binding named query: %s => %s", queryName, queryString ); LOG.debugf( "Binding named query: %s => %s", queryName, queryString );
} }
@ -108,13 +107,13 @@ public abstract class QueryBinder {
return; return;
} }
if ( isEmptyAnnotationValue( namedNativeQuery.name() ) ) {
throw new AnnotationException( "Class or package level '@NamedNativeQuery' annotation must specify a 'name'" );
}
final String registrationName = namedNativeQuery.name(); final String registrationName = namedNativeQuery.name();
final String queryString = namedNativeQuery.query(); final String queryString = namedNativeQuery.query();
if ( registrationName.isEmpty() ) {
throw new AnnotationException( "Class or package level '@NamedNativeQuery' annotation must specify a 'name'" );
}
final QueryHintDefinition hints = new QueryHintDefinition( registrationName, namedNativeQuery.hints() ); final QueryHintDefinition hints = new QueryHintDefinition( registrationName, namedNativeQuery.hints() );
final String resultSetMappingName = namedNativeQuery.resultSetMapping(); final String resultSetMappingName = namedNativeQuery.resultSetMapping();
@ -162,7 +161,7 @@ public abstract class QueryBinder {
final String registrationName = namedNativeQuery.name(); final String registrationName = namedNativeQuery.name();
//ResultSetMappingDefinition mappingDefinition = mappings.getJdbcValuesMappingProducer( queryAnn.resultSetMapping() ); //ResultSetMappingDefinition mappingDefinition = mappings.getJdbcValuesMappingProducer( queryAnn.resultSetMapping() );
if ( isEmptyAnnotationValue( registrationName ) ) { if ( registrationName.isEmpty() ) {
throw new AnnotationException( "Class or package level '@NamedNativeQuery' annotation must specify a 'name'" ); throw new AnnotationException( "Class or package level '@NamedNativeQuery' annotation must specify a 'name'" );
} }
@ -177,14 +176,14 @@ public abstract class QueryBinder {
.setResultSetMappingClassName( resultSetMappingClassName ) .setResultSetMappingClassName( resultSetMappingClassName )
.setQuerySpaces( null ) .setQuerySpaces( null )
.setCacheable( namedNativeQuery.cacheable() ) .setCacheable( namedNativeQuery.cacheable() )
.setCacheRegion( getAnnotationValueStringOrNull( namedNativeQuery.cacheRegion() ) ) .setCacheRegion(nullIfEmpty(namedNativeQuery.cacheRegion()))
.setCacheMode( getCacheMode( namedNativeQuery ) ) .setCacheMode( getCacheMode( namedNativeQuery ) )
.setTimeout( namedNativeQuery.timeout() < 0 ? null : namedNativeQuery.timeout() ) .setTimeout( namedNativeQuery.timeout() < 0 ? null : namedNativeQuery.timeout() )
.setFetchSize( namedNativeQuery.fetchSize() < 0 ? null : namedNativeQuery.fetchSize() ) .setFetchSize( namedNativeQuery.fetchSize() < 0 ? null : namedNativeQuery.fetchSize() )
.setFlushMode( getFlushMode( namedNativeQuery.flushMode() ) ) .setFlushMode( getFlushMode( namedNativeQuery.flushMode() ) )
.setReadOnly( namedNativeQuery.readOnly() ) .setReadOnly( namedNativeQuery.readOnly() )
.setQuerySpaces( setOf( namedNativeQuery.querySpaces() ) ) .setQuerySpaces( setOf( namedNativeQuery.querySpaces() ) )
.setComment( getAnnotationValueStringOrNull( namedNativeQuery.comment() ) ); .setComment(nullIfEmpty(namedNativeQuery.comment()));
if ( namedNativeQuery.callable() ) { if ( namedNativeQuery.callable() ) {
final NamedProcedureCallDefinition definition = final NamedProcedureCallDefinition definition =
@ -329,21 +328,20 @@ public abstract class QueryBinder {
final String registrationName = namedQuery.name(); final String registrationName = namedQuery.name();
//ResultSetMappingDefinition mappingDefinition = mappings.getJdbcValuesMappingProducer( namedQuery.resultSetMapping() ); //ResultSetMappingDefinition mappingDefinition = mappings.getJdbcValuesMappingProducer( namedQuery.resultSetMapping() );
if ( isEmptyAnnotationValue( registrationName ) ) { if ( registrationName.isEmpty() ) {
throw new AnnotationException( "Class or package level '@NamedQuery' annotation must specify a 'name'" ); throw new AnnotationException( "Class or package level '@NamedQuery' annotation must specify a 'name'" );
} }
final NamedHqlQueryDefinition.Builder builder = new NamedHqlQueryDefinition.Builder( registrationName ) final NamedHqlQueryDefinition.Builder builder = new NamedHqlQueryDefinition.Builder( registrationName )
.setHqlString( namedQuery.query() ) .setHqlString( namedQuery.query() )
.setCacheable( namedQuery.cacheable() ) .setCacheable( namedQuery.cacheable() )
.setCacheRegion( getAnnotationValueStringOrNull( namedQuery.cacheRegion() ) ) .setCacheRegion(nullIfEmpty(namedQuery.cacheRegion()))
.setCacheMode( getCacheMode( namedQuery ) ) .setCacheMode( getCacheMode( namedQuery ) )
.setTimeout( namedQuery.timeout() < 0 ? null : namedQuery.timeout() ) .setTimeout( namedQuery.timeout() < 0 ? null : namedQuery.timeout() )
.setFetchSize( namedQuery.fetchSize() < 0 ? null : namedQuery.fetchSize() ) .setFetchSize( namedQuery.fetchSize() < 0 ? null : namedQuery.fetchSize() )
.setFlushMode( getFlushMode( namedQuery.flushMode() ) ) .setFlushMode( getFlushMode( namedQuery.flushMode() ) )
.setReadOnly( namedQuery.readOnly() ) .setReadOnly( namedQuery.readOnly() )
.setComment( isEmptyAnnotationValue( namedQuery.comment() ) ? null : namedQuery.comment() ); .setComment( nullIfEmpty( namedQuery.comment() ) );
final NamedHqlQueryDefinitionImpl hqlQueryDefinition = builder.build(); final NamedHqlQueryDefinitionImpl hqlQueryDefinition = builder.build();
@ -426,9 +424,7 @@ public abstract class QueryBinder {
return; return;
} }
final String registrationName = annotation.name(); if ( annotation.name().isEmpty() ) {
if ( isEmptyAnnotationValue( registrationName ) ) {
throw new AnnotationException( "Class or package level '@NamedStoredProcedureQuery' annotation must specify a 'name'" ); throw new AnnotationException( "Class or package level '@NamedStoredProcedureQuery' annotation must specify a 'name'" );
} }

View File

@ -12,12 +12,13 @@ import org.hibernate.annotations.OrderBy;
import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.MetadataBuildingContext;
import org.hibernate.mapping.Collection; import org.hibernate.mapping.Collection;
import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Set;
import org.hibernate.resource.beans.spi.ManagedBean; import org.hibernate.resource.beans.spi.ManagedBean;
import org.hibernate.usertype.UserCollectionType; import org.hibernate.usertype.UserCollectionType;
/** /**
* A {@link CollectionBinder} for {@link org.hibernate.collection.spi.PersistentSet sets}, * A {@link CollectionBinder} for {@link org.hibernate.collection.spi.PersistentSet sets},
* whose mapping model type is {@link org.hibernate.mapping.Set}. * whose mapping model type is {@link Set}.
* *
* @author Matthew Inger * @author Matthew Inger
*/ */
@ -32,7 +33,7 @@ public class SetBinder extends CollectionBinder {
@Override @Override
protected Collection createCollection(PersistentClass persistentClass) { protected Collection createCollection(PersistentClass persistentClass) {
return new org.hibernate.mapping.Set( getCustomTypeBeanResolver(), persistentClass, getBuildingContext() ); return new Set( getCustomTypeBeanResolver(), persistentClass, getBuildingContext() );
} }
@Override @Override

View File

@ -49,9 +49,9 @@ import org.hibernate.mapping.Value;
import org.jboss.logging.Logger; import org.jboss.logging.Logger;
import static org.hibernate.cfg.BinderHelper.isEmptyOrNullAnnotationValue;
import static org.hibernate.internal.util.StringHelper.isNotEmpty; import static org.hibernate.internal.util.StringHelper.isNotEmpty;
import static org.hibernate.internal.util.StringHelper.isQuoted; import static org.hibernate.internal.util.StringHelper.isQuoted;
import static org.hibernate.internal.util.StringHelper.nullIfEmpty;
import static org.hibernate.internal.util.StringHelper.unquote; import static org.hibernate.internal.util.StringHelper.unquote;
import static org.hibernate.internal.util.collections.CollectionHelper.arrayList; import static org.hibernate.internal.util.collections.CollectionHelper.arrayList;
@ -485,8 +485,8 @@ public class TableBinder {
MetadataBuildingContext buildingContext, MetadataBuildingContext buildingContext,
String subselect, String subselect,
InFlightMetadataCollector.EntityTableXref denormalizedSuperTableXref) { InFlightMetadataCollector.EntityTableXref denormalizedSuperTableXref) {
schema = isEmptyOrNullAnnotationValue( schema ) ? null : schema; schema = nullIfEmpty( schema );
catalog = isEmptyOrNullAnnotationValue( catalog ) ? null : catalog; catalog = nullIfEmpty( catalog );
final Table table; final Table table;
if ( denormalizedSuperTableXref != null ) { if ( denormalizedSuperTableXref != null ) {

View File

@ -200,6 +200,8 @@ import jakarta.persistence.Version;
import static org.hibernate.cfg.annotations.reflection.internal.PropertyMappingElementCollector.JAXB_TRANSIENT_NAME; import static org.hibernate.cfg.annotations.reflection.internal.PropertyMappingElementCollector.JAXB_TRANSIENT_NAME;
import static org.hibernate.cfg.annotations.reflection.internal.PropertyMappingElementCollector.PERSISTENT_ATTRIBUTE_NAME; import static org.hibernate.cfg.annotations.reflection.internal.PropertyMappingElementCollector.PERSISTENT_ATTRIBUTE_NAME;
import static org.hibernate.internal.util.StringHelper.isEmpty;
import static org.hibernate.internal.util.StringHelper.isNotEmpty;
/** /**
* Encapsulates the overriding of Java annotations from an EJB 3.0 descriptor (orm.xml, ...). * Encapsulates the overriding of Java annotations from an EJB 3.0 descriptor (orm.xml, ...).
@ -621,8 +623,8 @@ public class JPAXMLOverriddenAnnotationReader implements AnnotationReader {
private String qualifyConverterAttributeName(String attributeNamePrefix, String specifiedAttributeName) { private String qualifyConverterAttributeName(String attributeNamePrefix, String specifiedAttributeName) {
String qualifiedAttributeName; String qualifiedAttributeName;
if ( StringHelper.isNotEmpty( specifiedAttributeName ) ) { if ( isNotEmpty( specifiedAttributeName ) ) {
if ( StringHelper.isNotEmpty( attributeNamePrefix ) ) { if ( isNotEmpty( attributeNamePrefix ) ) {
qualifiedAttributeName = attributeNamePrefix + '.' + specifiedAttributeName; qualifiedAttributeName = attributeNamePrefix + '.' + specifiedAttributeName;
} }
else { else {
@ -857,14 +859,14 @@ public class JPAXMLOverriddenAnnotationReader implements AnnotationReader {
|| isPhysicalAnnotationPresent( JoinColumns.class ) ); || isPhysicalAnnotationPresent( JoinColumns.class ) );
final Class<? extends Annotation> annotationClass = annotation.annotationType(); final Class<? extends Annotation> annotationClass = annotation.annotationType();
defaultToJoinTable = defaultToJoinTable && defaultToJoinTable = defaultToJoinTable &&
( ( annotationClass == ManyToMany.class && StringHelper.isEmpty( ( (ManyToMany) annotation ).mappedBy() ) ) ( ( annotationClass == ManyToMany.class && isEmpty( ( (ManyToMany) annotation ).mappedBy() ) )
|| ( annotationClass == OneToMany.class && StringHelper.isEmpty( ( (OneToMany) annotation ).mappedBy() ) ) || ( annotationClass == OneToMany.class && isEmpty( ( (OneToMany) annotation ).mappedBy() ) )
|| ( annotationClass == ElementCollection.class ) || ( annotationClass == ElementCollection.class )
); );
final Class<JoinTable> annotationType = JoinTable.class; final Class<JoinTable> annotationType = JoinTable.class;
if ( defaultToJoinTable if ( defaultToJoinTable
&& ( StringHelper.isNotEmpty( defaults.getCatalog() ) && ( isNotEmpty( defaults.getCatalog() )
|| StringHelper.isNotEmpty( defaults.getSchema() ) ) ) { || isNotEmpty( defaults.getSchema() ) ) ) {
AnnotationDescriptor ad = new AnnotationDescriptor( annotationType ); AnnotationDescriptor ad = new AnnotationDescriptor( annotationType );
if ( defaults.canUseJavaAnnotations() ) { if ( defaults.canUseJavaAnnotations() ) {
JoinTable table = getPhysicalAnnotation( annotationType ); JoinTable table = getPhysicalAnnotation( annotationType );
@ -877,12 +879,12 @@ public class JPAXMLOverriddenAnnotationReader implements AnnotationReader {
ad.setValue( "inverseJoinColumns", table.inverseJoinColumns() ); ad.setValue( "inverseJoinColumns", table.inverseJoinColumns() );
} }
} }
if ( StringHelper.isEmpty( (String) ad.valueOf( "schema" ) ) if ( isEmpty( (String) ad.valueOf( "schema" ) )
&& StringHelper.isNotEmpty( defaults.getSchema() ) ) { && isNotEmpty( defaults.getSchema() ) ) {
ad.setValue( "schema", defaults.getSchema() ); ad.setValue( "schema", defaults.getSchema() );
} }
if ( StringHelper.isEmpty( (String) ad.valueOf( "catalog" ) ) if ( isEmpty( (String) ad.valueOf( "catalog" ) )
&& StringHelper.isNotEmpty( defaults.getCatalog() ) ) { && isNotEmpty( defaults.getCatalog() ) ) {
ad.setValue( "catalog", defaults.getCatalog() ); ad.setValue( "catalog", defaults.getCatalog() );
} }
return AnnotationFactory.create( ad ); return AnnotationFactory.create( ad );
@ -958,13 +960,13 @@ public class JPAXMLOverriddenAnnotationReader implements AnnotationReader {
AnnotationDescriptor annotation = new AnnotationDescriptor( annotationType ); AnnotationDescriptor annotation = new AnnotationDescriptor( annotationType );
copyAttribute( annotation, "name", subelement.getName(), false ); copyAttribute( annotation, "name", subelement.getName(), false );
copyAttribute( annotation, "catalog", subelement.getCatalog(), false ); copyAttribute( annotation, "catalog", subelement.getCatalog(), false );
if ( StringHelper.isNotEmpty( defaults.getCatalog() ) if ( isNotEmpty( defaults.getCatalog() )
&& StringHelper.isEmpty( (String) annotation.valueOf( "catalog" ) ) ) { && isEmpty( (String) annotation.valueOf( "catalog" ) ) ) {
annotation.setValue( "catalog", defaults.getCatalog() ); annotation.setValue( "catalog", defaults.getCatalog() );
} }
copyAttribute( annotation, "schema", subelement.getSchema(), false ); copyAttribute( annotation, "schema", subelement.getSchema(), false );
if ( StringHelper.isNotEmpty( defaults.getSchema() ) if ( isNotEmpty( defaults.getSchema() )
&& StringHelper.isEmpty( (String) annotation.valueOf( "schema" ) ) ) { && isEmpty( (String) annotation.valueOf( "schema" ) ) ) {
annotation.setValue( "schema", defaults.getSchema() ); annotation.setValue( "schema", defaults.getSchema() );
} }
buildUniqueConstraints( annotation, subelement.getUniqueConstraint() ); buildUniqueConstraints( annotation, subelement.getUniqueConstraint() );
@ -1433,7 +1435,7 @@ public class JPAXMLOverriddenAnnotationReader implements AnnotationReader {
if ( element != null ) { if ( element != null ) {
String mapKeyClassName = element.getClazz(); String mapKeyClassName = element.getClazz();
AnnotationDescriptor ad = new AnnotationDescriptor( MapKeyClass.class ); AnnotationDescriptor ad = new AnnotationDescriptor( MapKeyClass.class );
if ( StringHelper.isNotEmpty( mapKeyClassName ) ) { if ( isNotEmpty( mapKeyClassName ) ) {
Class clazz; Class clazz;
try { try {
clazz = classLoaderAccess.classForName( clazz = classLoaderAccess.classForName(
@ -1456,13 +1458,13 @@ public class JPAXMLOverriddenAnnotationReader implements AnnotationReader {
AnnotationDescriptor annotation = new AnnotationDescriptor( CollectionTable.class ); AnnotationDescriptor annotation = new AnnotationDescriptor( CollectionTable.class );
copyAttribute( annotation, "name", element.getName(), false ); copyAttribute( annotation, "name", element.getName(), false );
copyAttribute( annotation, "catalog", element.getCatalog(), false ); copyAttribute( annotation, "catalog", element.getCatalog(), false );
if ( StringHelper.isNotEmpty( defaults.getCatalog() ) if ( isNotEmpty( defaults.getCatalog() )
&& StringHelper.isEmpty( (String) annotation.valueOf( "catalog" ) ) ) { && isEmpty( (String) annotation.valueOf( "catalog" ) ) ) {
annotation.setValue( "catalog", defaults.getCatalog() ); annotation.setValue( "catalog", defaults.getCatalog() );
} }
copyAttribute( annotation, "schema", element.getSchema(), false ); copyAttribute( annotation, "schema", element.getSchema(), false );
if ( StringHelper.isNotEmpty( defaults.getSchema() ) if ( isNotEmpty( defaults.getSchema() )
&& StringHelper.isEmpty( (String) annotation.valueOf( "schema" ) ) ) { && isEmpty( (String) annotation.valueOf( "schema" ) ) ) {
annotation.setValue( "schema", defaults.getSchema() ); annotation.setValue( "schema", defaults.getSchema() );
} }
JoinColumn[] joinColumns = getJoinColumns( element.getJoinColumn(), false ); JoinColumn[] joinColumns = getJoinColumns( element.getJoinColumn(), false );
@ -2324,7 +2326,7 @@ public class JPAXMLOverriddenAnnotationReader implements AnnotationReader {
AnnotationDescriptor columnResultDescriptor = new AnnotationDescriptor( ColumnResult.class ); AnnotationDescriptor columnResultDescriptor = new AnnotationDescriptor( ColumnResult.class );
copyAttribute( columnResultDescriptor, "name", columnResultElement.getName(), true ); copyAttribute( columnResultDescriptor, "name", columnResultElement.getName(), true );
final String columnTypeName = columnResultElement.getClazz(); final String columnTypeName = columnResultElement.getClazz();
if ( StringHelper.isNotEmpty( columnTypeName ) ) { if ( isNotEmpty( columnTypeName ) ) {
columnResultDescriptor.setValue( "type", resolveClassReference( columnTypeName, defaults, classLoaderAccess ) ); columnResultDescriptor.setValue( "type", resolveClassReference( columnTypeName, defaults, classLoaderAccess ) );
} }
return AnnotationFactory.create( columnResultDescriptor ); return AnnotationFactory.create( columnResultDescriptor );
@ -2607,7 +2609,7 @@ public class JPAXMLOverriddenAnnotationReader implements AnnotationReader {
addSynchronizationsHint( additionalHints, element.getSynchronizations() ); addSynchronizationsHint( additionalHints, element.getSynchronizations() );
buildQueryHints( element.getHint(), ann, additionalHints ); buildQueryHints( element.getHint(), ann, additionalHints );
String clazzName = element.getResultClass(); String clazzName = element.getResultClass();
if ( StringHelper.isNotEmpty( clazzName ) ) { if ( isNotEmpty( clazzName ) ) {
Class clazz; Class clazz;
try { try {
clazz = classLoaderAccess.classForName( clazz = classLoaderAccess.classForName(
@ -2659,19 +2661,19 @@ public class JPAXMLOverriddenAnnotationReader implements AnnotationReader {
} }
else if ( defaults.canUseJavaAnnotations() && isPhysicalAnnotationPresent( TableGenerator.class ) ) { else if ( defaults.canUseJavaAnnotations() && isPhysicalAnnotationPresent( TableGenerator.class ) ) {
TableGenerator tableAnn = getPhysicalAnnotation( TableGenerator.class ); TableGenerator tableAnn = getPhysicalAnnotation( TableGenerator.class );
if ( StringHelper.isNotEmpty( defaults.getSchema() ) if ( isNotEmpty( defaults.getSchema() )
|| StringHelper.isNotEmpty( defaults.getCatalog() ) ) { || isNotEmpty( defaults.getCatalog() ) ) {
AnnotationDescriptor annotation = new AnnotationDescriptor( TableGenerator.class ); AnnotationDescriptor annotation = new AnnotationDescriptor( TableGenerator.class );
annotation.setValue( "name", tableAnn.name() ); annotation.setValue( "name", tableAnn.name() );
annotation.setValue( "table", tableAnn.table() ); annotation.setValue( "table", tableAnn.table() );
annotation.setValue( "catalog", tableAnn.table() ); annotation.setValue( "catalog", tableAnn.table() );
if ( StringHelper.isEmpty( (String) annotation.valueOf( "catalog" ) ) if ( isEmpty( (String) annotation.valueOf( "catalog" ) )
&& StringHelper.isNotEmpty( defaults.getCatalog() ) ) { && isNotEmpty( defaults.getCatalog() ) ) {
annotation.setValue( "catalog", defaults.getCatalog() ); annotation.setValue( "catalog", defaults.getCatalog() );
} }
annotation.setValue( "schema", tableAnn.table() ); annotation.setValue( "schema", tableAnn.table() );
if ( StringHelper.isEmpty( (String) annotation.valueOf( "schema" ) ) if ( isEmpty( (String) annotation.valueOf( "schema" ) )
&& StringHelper.isNotEmpty( defaults.getSchema() ) ) { && isNotEmpty( defaults.getSchema() ) ) {
annotation.setValue( "catalog", defaults.getSchema() ); annotation.setValue( "catalog", defaults.getSchema() );
} }
annotation.setValue( "pkColumnName", tableAnn.pkColumnName() ); annotation.setValue( "pkColumnName", tableAnn.pkColumnName() );
@ -2703,12 +2705,12 @@ public class JPAXMLOverriddenAnnotationReader implements AnnotationReader {
copyAttribute( ad, "initial-value", element.getInitialValue(), false ); copyAttribute( ad, "initial-value", element.getInitialValue(), false );
copyAttribute( ad, "allocation-size", element.getAllocationSize(), false ); copyAttribute( ad, "allocation-size", element.getAllocationSize(), false );
buildUniqueConstraints( ad, element.getUniqueConstraint() ); buildUniqueConstraints( ad, element.getUniqueConstraint() );
if ( StringHelper.isEmpty( (String) ad.valueOf( "schema" ) ) if ( isEmpty( (String) ad.valueOf( "schema" ) )
&& StringHelper.isNotEmpty( defaults.getSchema() ) ) { && isNotEmpty( defaults.getSchema() ) ) {
ad.setValue( "schema", defaults.getSchema() ); ad.setValue( "schema", defaults.getSchema() );
} }
if ( StringHelper.isEmpty( (String) ad.valueOf( "catalog" ) ) if ( isEmpty( (String) ad.valueOf( "catalog" ) )
&& StringHelper.isNotEmpty( defaults.getCatalog() ) ) { && isNotEmpty( defaults.getCatalog() ) ) {
ad.setValue( "catalog", defaults.getCatalog() ); ad.setValue( "catalog", defaults.getCatalog() );
} }
return AnnotationFactory.create( ad ); return AnnotationFactory.create( ad );
@ -2880,7 +2882,7 @@ public class JPAXMLOverriddenAnnotationReader implements AnnotationReader {
AnnotationDescriptor entity = new AnnotationDescriptor( Entity.class ); AnnotationDescriptor entity = new AnnotationDescriptor( Entity.class );
copyAttribute( entity, "name", entityElement.getName(), false ); copyAttribute( entity, "name", entityElement.getName(), false );
if ( defaults.canUseJavaAnnotations() if ( defaults.canUseJavaAnnotations()
&& StringHelper.isEmpty( (String) entity.valueOf( "name" ) ) ) { && isEmpty( (String) entity.valueOf( "name" ) ) ) {
Entity javaAnn = getPhysicalAnnotation( Entity.class ); Entity javaAnn = getPhysicalAnnotation( Entity.class );
if ( javaAnn != null ) { if ( javaAnn != null ) {
entity.setValue( "name", javaAnn.name() ); entity.setValue( "name", javaAnn.name() );
@ -2926,7 +2928,7 @@ public class JPAXMLOverriddenAnnotationReader implements AnnotationReader {
private Subselect getTableExpression(JaxbEntity entity, XMLContext.Default defaults) { private Subselect getTableExpression(JaxbEntity entity, XMLContext.Default defaults) {
final String tableExpression = entity.getTableExpression(); final String tableExpression = entity.getTableExpression();
if ( StringHelper.isEmpty( tableExpression ) ) { if ( isEmpty( tableExpression ) ) {
return null; return null;
} }
@ -2939,8 +2941,8 @@ public class JPAXMLOverriddenAnnotationReader implements AnnotationReader {
final JaxbTable element = root instanceof JaxbEntity ? ( (JaxbEntity) root ).getTable() : null; final JaxbTable element = root instanceof JaxbEntity ? ( (JaxbEntity) root ).getTable() : null;
if ( element == null ) { if ( element == null ) {
//no element but might have some default or some annotation //no element but might have some default or some annotation
if ( StringHelper.isNotEmpty( defaults.getCatalog() ) if ( isNotEmpty( defaults.getCatalog() )
|| StringHelper.isNotEmpty( defaults.getSchema() ) ) { || isNotEmpty( defaults.getSchema() ) ) {
AnnotationDescriptor annotation = new AnnotationDescriptor( Table.class ); AnnotationDescriptor annotation = new AnnotationDescriptor( Table.class );
if ( defaults.canUseJavaAnnotations() ) { if ( defaults.canUseJavaAnnotations() ) {
Table table = getPhysicalAnnotation( Table.class ); Table table = getPhysicalAnnotation( Table.class );
@ -2952,12 +2954,12 @@ public class JPAXMLOverriddenAnnotationReader implements AnnotationReader {
annotation.setValue( "indexes", table.indexes() ); annotation.setValue( "indexes", table.indexes() );
} }
} }
if ( StringHelper.isEmpty( (String) annotation.valueOf( "schema" ) ) if ( isEmpty( (String) annotation.valueOf( "schema" ) )
&& StringHelper.isNotEmpty( defaults.getSchema() ) ) { && isNotEmpty( defaults.getSchema() ) ) {
annotation.setValue( "schema", defaults.getSchema() ); annotation.setValue( "schema", defaults.getSchema() );
} }
if ( StringHelper.isEmpty( (String) annotation.valueOf( "catalog" ) ) if ( isEmpty( (String) annotation.valueOf( "catalog" ) )
&& StringHelper.isNotEmpty( defaults.getCatalog() ) ) { && isNotEmpty( defaults.getCatalog() ) ) {
annotation.setValue( "catalog", defaults.getCatalog() ); annotation.setValue( "catalog", defaults.getCatalog() );
} }
return AnnotationFactory.create( annotation ); return AnnotationFactory.create( annotation );
@ -2974,13 +2976,13 @@ public class JPAXMLOverriddenAnnotationReader implements AnnotationReader {
AnnotationDescriptor annotation = new AnnotationDescriptor( Table.class ); AnnotationDescriptor annotation = new AnnotationDescriptor( Table.class );
copyAttribute( annotation, "name", element.getName(), false ); copyAttribute( annotation, "name", element.getName(), false );
copyAttribute( annotation, "catalog", element.getCatalog(), false ); copyAttribute( annotation, "catalog", element.getCatalog(), false );
if ( StringHelper.isNotEmpty( defaults.getCatalog() ) if ( isNotEmpty( defaults.getCatalog() )
&& StringHelper.isEmpty( (String) annotation.valueOf( "catalog" ) ) ) { && isEmpty( (String) annotation.valueOf( "catalog" ) ) ) {
annotation.setValue( "catalog", defaults.getCatalog() ); annotation.setValue( "catalog", defaults.getCatalog() );
} }
copyAttribute( annotation, "schema", element.getSchema(), false ); copyAttribute( annotation, "schema", element.getSchema(), false );
if ( StringHelper.isNotEmpty( defaults.getSchema() ) if ( isNotEmpty( defaults.getSchema() )
&& StringHelper.isEmpty( (String) annotation.valueOf( "schema" ) ) ) { && isEmpty( (String) annotation.valueOf( "schema" ) ) ) {
annotation.setValue( "schema", defaults.getSchema() ); annotation.setValue( "schema", defaults.getSchema() );
} }
buildUniqueConstraints( annotation, element.getUniqueConstraint() ); buildUniqueConstraints( annotation, element.getUniqueConstraint() );
@ -2998,13 +3000,13 @@ public class JPAXMLOverriddenAnnotationReader implements AnnotationReader {
AnnotationDescriptor annotation = new AnnotationDescriptor( SecondaryTable.class ); AnnotationDescriptor annotation = new AnnotationDescriptor( SecondaryTable.class );
copyAttribute( annotation, "name", element.getName(), false ); copyAttribute( annotation, "name", element.getName(), false );
copyAttribute( annotation, "catalog", element.getCatalog(), false ); copyAttribute( annotation, "catalog", element.getCatalog(), false );
if ( StringHelper.isNotEmpty( defaults.getCatalog() ) if ( isNotEmpty( defaults.getCatalog() )
&& StringHelper.isEmpty( (String) annotation.valueOf( "catalog" ) ) ) { && isEmpty( (String) annotation.valueOf( "catalog" ) ) ) {
annotation.setValue( "catalog", defaults.getCatalog() ); annotation.setValue( "catalog", defaults.getCatalog() );
} }
copyAttribute( annotation, "schema", element.getSchema(), false ); copyAttribute( annotation, "schema", element.getSchema(), false );
if ( StringHelper.isNotEmpty( defaults.getSchema() ) if ( isNotEmpty( defaults.getSchema() )
&& StringHelper.isEmpty( (String) annotation.valueOf( "schema" ) ) ) { && isEmpty( (String) annotation.valueOf( "schema" ) ) ) {
annotation.setValue( "schema", defaults.getSchema() ); annotation.setValue( "schema", defaults.getSchema() );
} }
buildUniqueConstraints( annotation, element.getUniqueConstraint() ); buildUniqueConstraints( annotation, element.getUniqueConstraint() );
@ -3042,20 +3044,20 @@ public class JPAXMLOverriddenAnnotationReader implements AnnotationReader {
) { ) {
if ( secTableAnn != null ) { if ( secTableAnn != null ) {
//handle default values //handle default values
if ( StringHelper.isNotEmpty( defaults.getCatalog() ) if ( isNotEmpty( defaults.getCatalog() )
|| StringHelper.isNotEmpty( defaults.getSchema() ) ) { || isNotEmpty( defaults.getSchema() ) ) {
AnnotationDescriptor annotation = new AnnotationDescriptor( SecondaryTable.class ); AnnotationDescriptor annotation = new AnnotationDescriptor( SecondaryTable.class );
annotation.setValue( "name", secTableAnn.name() ); annotation.setValue( "name", secTableAnn.name() );
annotation.setValue( "schema", secTableAnn.schema() ); annotation.setValue( "schema", secTableAnn.schema() );
annotation.setValue( "catalog", secTableAnn.catalog() ); annotation.setValue( "catalog", secTableAnn.catalog() );
annotation.setValue( "uniqueConstraints", secTableAnn.uniqueConstraints() ); annotation.setValue( "uniqueConstraints", secTableAnn.uniqueConstraints() );
annotation.setValue( "pkJoinColumns", secTableAnn.pkJoinColumns() ); annotation.setValue( "pkJoinColumns", secTableAnn.pkJoinColumns() );
if ( StringHelper.isEmpty( (String) annotation.valueOf( "schema" ) ) if ( isEmpty( (String) annotation.valueOf( "schema" ) )
&& StringHelper.isNotEmpty( defaults.getSchema() ) ) { && isNotEmpty( defaults.getSchema() ) ) {
annotation.setValue( "schema", defaults.getSchema() ); annotation.setValue( "schema", defaults.getSchema() );
} }
if ( StringHelper.isEmpty( (String) annotation.valueOf( "catalog" ) ) if ( isEmpty( (String) annotation.valueOf( "catalog" ) )
&& StringHelper.isNotEmpty( defaults.getCatalog() ) ) { && isNotEmpty( defaults.getCatalog() ) ) {
annotation.setValue( "catalog", defaults.getCatalog() ); annotation.setValue( "catalog", defaults.getCatalog() );
} }
secondaryTables.add( AnnotationFactory.create( annotation ) ); secondaryTables.add( AnnotationFactory.create( annotation ) );

View File

@ -66,7 +66,7 @@ public class HibernateTraversableResolver implements TraversableResolver {
addAssociationsToTheSetForAllProperties( addAssociationsToTheSetForAllProperties(
componentType.getPropertyNames(), componentType.getPropertyNames(),
componentType.getSubtypes(), componentType.getSubtypes(),
( prefix.isEmpty() ? name : prefix + name) + '.', ( prefix.isEmpty() ? name : prefix + name ) + '.',
factory); factory);
} }
} }