Search in sources :

Example 36 with AnnotationException

use of org.hibernate.AnnotationException in project hibernate-orm by hibernate.

the class BinderHelper method buildAnyValue.

public static Any buildAnyValue(String anyMetaDefName, Ejb3JoinColumn[] columns, javax.persistence.Column metaColumn, PropertyData inferredData, boolean cascadeOnDelete, Nullability nullability, PropertyHolder propertyHolder, EntityBinder entityBinder, boolean optional, MetadataBuildingContext context) {
    // All FK columns should be in the same table
    Any value = new Any(context, columns[0].getTable());
    AnyMetaDef metaAnnDef = inferredData.getProperty().getAnnotation(AnyMetaDef.class);
    if (metaAnnDef != null) {
        // local has precedence over general and can be mapped for future reference if named
        bindAnyMetaDefs(inferredData.getProperty(), context);
    } else {
        metaAnnDef = context.getMetadataCollector().getAnyMetaDef(anyMetaDefName);
    }
    if (metaAnnDef != null) {
        value.setIdentifierType(metaAnnDef.idType());
        value.setMetaType(metaAnnDef.metaType());
        HashMap values = new HashMap();
        org.hibernate.type.Type metaType = context.getMetadataCollector().getTypeResolver().heuristicType(value.getMetaType());
        for (MetaValue metaValue : metaAnnDef.metaValues()) {
            try {
                Object discrim = ((org.hibernate.type.DiscriminatorType) metaType).stringToObject(metaValue.value());
                String entityName = metaValue.targetEntity().getName();
                values.put(discrim, entityName);
            } catch (ClassCastException cce) {
                throw new MappingException("metaType was not a DiscriminatorType: " + metaType.getName());
            } catch (Exception e) {
                throw new MappingException("could not interpret metaValue", e);
            }
        }
        if (!values.isEmpty()) {
            value.setMetaValues(values);
        }
    } else {
        throw new AnnotationException("Unable to find @AnyMetaDef for an @(ManyTo)Any mapping: " + StringHelper.qualify(propertyHolder.getPath(), inferredData.getPropertyName()));
    }
    value.setCascadeDeleteEnabled(cascadeOnDelete);
    if (!optional) {
        for (Ejb3JoinColumn column : columns) {
            column.setNullable(false);
        }
    }
    Ejb3Column[] metaColumns = Ejb3Column.buildColumnFromAnnotation(new javax.persistence.Column[] { metaColumn }, null, nullability, propertyHolder, inferredData, entityBinder.getSecondaryTables(), context);
    // set metaColumn to the right table
    for (Ejb3Column column : metaColumns) {
        column.setTable(value.getTable());
    }
    // meta column
    for (Ejb3Column column : metaColumns) {
        column.linkWithValue(value);
    }
    // id columns
    final String propertyName = inferredData.getPropertyName();
    Ejb3Column.checkPropertyConsistency(columns, propertyHolder.getEntityName() + "." + propertyName);
    for (Ejb3JoinColumn column : columns) {
        column.linkWithValue(value);
    }
    return value;
}
Also used : MetaValue(org.hibernate.annotations.MetaValue) HashMap(java.util.HashMap) Any(org.hibernate.mapping.Any) AnnotationException(org.hibernate.AnnotationException) MappingException(org.hibernate.MappingException) ClassLoadingException(org.hibernate.annotations.common.reflection.ClassLoadingException) MappingException(org.hibernate.MappingException) AnyMetaDef(org.hibernate.annotations.AnyMetaDef) AnnotationException(org.hibernate.AnnotationException)

Example 37 with AnnotationException

use of org.hibernate.AnnotationException in project hibernate-orm by hibernate.

the class BinderHelper method makeIdGenerator.

/**
 * apply an id generator to a SimpleValue
 */
public static void makeIdGenerator(SimpleValue id, XProperty idXProperty, String generatorType, String generatorName, MetadataBuildingContext buildingContext, Map<String, IdentifierGeneratorDefinition> localGenerators) {
    log.debugf("#makeIdGenerator(%s, %s, %s, %s, ...)", id, idXProperty, generatorType, generatorName);
    Table table = id.getTable();
    table.setIdentifierValue(id);
    // generator settings
    id.setIdentifierGeneratorStrategy(generatorType);
    Properties params = new Properties();
    // always settable
    params.setProperty(PersistentIdentifierGenerator.TABLE, table.getName());
    final String implicitCatalogName = buildingContext.getBuildingOptions().getMappingDefaults().getImplicitCatalogName();
    if (implicitCatalogName != null) {
        params.put(PersistentIdentifierGenerator.CATALOG, implicitCatalogName);
    }
    final String implicitSchemaName = buildingContext.getBuildingOptions().getMappingDefaults().getImplicitSchemaName();
    if (implicitSchemaName != null) {
        params.put(PersistentIdentifierGenerator.SCHEMA, implicitSchemaName);
    }
    if (id.getColumnSpan() == 1) {
        params.setProperty(PersistentIdentifierGenerator.PK, ((org.hibernate.mapping.Column) id.getColumnIterator().next()).getName());
    }
    // YUCK!  but cannot think of a clean way to do this given the string-config based scheme
    params.put(PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER, buildingContext.getObjectNameNormalizer());
    params.put(IdentifierGenerator.GENERATOR_NAME, generatorName);
    if (!isEmptyAnnotationValue(generatorName)) {
        // we have a named generator
        IdentifierGeneratorDefinition gen = getIdentifierGenerator(generatorName, idXProperty, localGenerators, buildingContext);
        if (gen == null) {
            throw new AnnotationException("Unknown named generator (@GeneratedValue#generatorName): " + generatorName);
        }
        // This is quite vague in the spec but a generator could override the generate choice
        String identifierGeneratorStrategy = gen.getStrategy();
        // yuk! this is a hack not to override 'AUTO' even if generator is set
        final boolean avoidOverriding = identifierGeneratorStrategy.equals("identity") || identifierGeneratorStrategy.equals("seqhilo") || identifierGeneratorStrategy.equals(MultipleHiLoPerTableGenerator.class.getName());
        if (generatorType == null || !avoidOverriding) {
            id.setIdentifierGeneratorStrategy(identifierGeneratorStrategy);
        }
        // checkIfMatchingGenerator(gen, generatorType, generatorName);
        for (Object o : gen.getParameters().entrySet()) {
            Map.Entry elt = (Map.Entry) o;
            if (elt.getKey() == null) {
                continue;
            }
            params.setProperty((String) elt.getKey(), (String) elt.getValue());
        }
    }
    if ("assigned".equals(generatorType)) {
        id.setNullValue("undefined");
    }
    id.setIdentifierGeneratorProperties(params);
}
Also used : Table(org.hibernate.mapping.Table) IdentifierGeneratorDefinition(org.hibernate.boot.model.IdentifierGeneratorDefinition) AnnotationException(org.hibernate.AnnotationException) Properties(java.util.Properties) Map(java.util.Map) HashMap(java.util.HashMap)

Example 38 with AnnotationException

use of org.hibernate.AnnotationException in project hibernate-orm by hibernate.

the class SimpleValueBinder method fillSimpleValue.

public void fillSimpleValue() {
    LOG.debugf("Starting fillSimpleValue for %s", propertyName);
    if (attributeConverterDescriptor != null) {
        if (!BinderHelper.isEmptyAnnotationValue(explicitType)) {
            throw new AnnotationException(String.format("AttributeConverter and explicit Type cannot be applied to same attribute [%s.%s];" + "remove @Type or specify @Convert(disableConversion = true)", persistentClassName, propertyName));
        }
        LOG.debugf("Applying JPA AttributeConverter [%s] to [%s:%s]", attributeConverterDescriptor, persistentClassName, propertyName);
        simpleValue.setJpaAttributeConverterDescriptor(attributeConverterDescriptor);
    } else {
        String type;
        TypeDefinition typeDef;
        if (!BinderHelper.isEmptyAnnotationValue(explicitType)) {
            type = explicitType;
            typeDef = buildingContext.getMetadataCollector().getTypeDefinition(type);
        } else {
            // try implicit type
            TypeDefinition implicitTypeDef = buildingContext.getMetadataCollector().getTypeDefinition(returnedClassName);
            if (implicitTypeDef != null) {
                typeDef = implicitTypeDef;
                type = returnedClassName;
            } else {
                typeDef = buildingContext.getMetadataCollector().getTypeDefinition(defaultType);
                type = defaultType;
            }
        }
        if (typeDef != null) {
            type = typeDef.getTypeImplementorClass().getName();
            simpleValue.setTypeParameters(typeDef.getParametersAsProperties());
        }
        if (typeParameters != null && typeParameters.size() != 0) {
            // explicit type params takes precedence over type def params
            simpleValue.setTypeParameters(typeParameters);
        }
        simpleValue.setTypeName(type);
    }
    if (persistentClassName != null || attributeConverterDescriptor != null) {
        try {
            simpleValue.setTypeUsingReflection(persistentClassName, propertyName);
        } catch (Exception e) {
            throw new MappingException(String.format(Locale.ROOT, "Unable to determine basic type mapping via reflection [%s -> %s]", persistentClassName, propertyName), e);
        }
    }
    if (!simpleValue.isTypeSpecified() && isVersion()) {
        simpleValue.setTypeName("integer");
    }
    // HHH-5205
    if (timeStampVersionType != null) {
        simpleValue.setTypeName(timeStampVersionType);
    }
    if (simpleValue.getTypeName() != null && simpleValue.getTypeName().length() > 0 && simpleValue.getMetadata().getTypeResolver().basic(simpleValue.getTypeName()) == null) {
        try {
            Class typeClass = buildingContext.getBootstrapContext().getClassLoaderAccess().classForName(simpleValue.getTypeName());
            if (typeClass != null && DynamicParameterizedType.class.isAssignableFrom(typeClass)) {
                Properties parameters = simpleValue.getTypeParameters();
                if (parameters == null) {
                    parameters = new Properties();
                }
                parameters.put(DynamicParameterizedType.IS_DYNAMIC, Boolean.toString(true));
                parameters.put(DynamicParameterizedType.RETURNED_CLASS, returnedClassName);
                parameters.put(DynamicParameterizedType.IS_PRIMARY_KEY, Boolean.toString(key));
                parameters.put(DynamicParameterizedType.ENTITY, persistentClassName);
                parameters.put(DynamicParameterizedType.XPROPERTY, xproperty);
                parameters.put(DynamicParameterizedType.PROPERTY, xproperty.getName());
                parameters.put(DynamicParameterizedType.ACCESS_TYPE, accessType.getType());
                simpleValue.setTypeParameters(parameters);
            }
        } catch (ClassLoadingException e) {
            throw new MappingException("Could not determine type for: " + simpleValue.getTypeName(), e);
        }
    }
}
Also used : ClassLoadingException(org.hibernate.annotations.common.reflection.ClassLoadingException) AnnotationException(org.hibernate.AnnotationException) XClass(org.hibernate.annotations.common.reflection.XClass) DynamicParameterizedType(org.hibernate.usertype.DynamicParameterizedType) Properties(java.util.Properties) AnnotationException(org.hibernate.AnnotationException) MappingException(org.hibernate.MappingException) ClassLoadingException(org.hibernate.annotations.common.reflection.ClassLoadingException) NotYetImplementedException(org.hibernate.cfg.NotYetImplementedException) TypeDefinition(org.hibernate.boot.model.TypeDefinition) MappingException(org.hibernate.MappingException)

Example 39 with AnnotationException

use of org.hibernate.AnnotationException in project hibernate-orm by hibernate.

the class SimpleValueBinder method setType.

// TODO execute it lazily to be order safe
public void setType(XProperty property, XClass returnedClass, String declaringClassName, ConverterDescriptor attributeConverterDescriptor) {
    if (returnedClass == null) {
        // we cannot guess anything
        return;
    }
    XClass returnedClassOrElement = returnedClass;
    boolean isArray = false;
    if (property.isArray()) {
        returnedClassOrElement = property.getElementClass();
        isArray = true;
    }
    this.xproperty = property;
    Properties typeParameters = this.typeParameters;
    typeParameters.clear();
    String type = BinderHelper.ANNOTATION_STRING_DEFAULT;
    if (getDialect().supportsNationalizedTypes()) {
        isNationalized = property.isAnnotationPresent(Nationalized.class) || buildingContext.getBuildingOptions().useNationalizedCharacterData();
    }
    Type annType = null;
    if ((!key && property.isAnnotationPresent(Type.class)) || (key && property.isAnnotationPresent(MapKeyType.class))) {
        if (key) {
            MapKeyType ann = property.getAnnotation(MapKeyType.class);
            annType = ann.value();
        } else {
            annType = property.getAnnotation(Type.class);
        }
    }
    if (annType != null) {
        setExplicitType(annType);
        type = explicitType;
    } else if ((!key && property.isAnnotationPresent(Temporal.class)) || (key && property.isAnnotationPresent(MapKeyTemporal.class))) {
        boolean isDate;
        if (buildingContext.getBootstrapContext().getReflectionManager().equals(returnedClassOrElement, Date.class)) {
            isDate = true;
        } else if (buildingContext.getBootstrapContext().getReflectionManager().equals(returnedClassOrElement, Calendar.class)) {
            isDate = false;
        } else {
            throw new AnnotationException("@Temporal should only be set on a java.util.Date or java.util.Calendar property: " + StringHelper.qualify(persistentClassName, propertyName));
        }
        final TemporalType temporalType = getTemporalType(property);
        switch(temporalType) {
            case DATE:
                type = isDate ? "date" : "calendar_date";
                break;
            case TIME:
                type = "time";
                if (!isDate) {
                    throw new NotYetImplementedException("Calendar cannot persist TIME only" + StringHelper.qualify(persistentClassName, propertyName));
                }
                break;
            case TIMESTAMP:
                type = isDate ? "timestamp" : "calendar";
                break;
            default:
                throw new AssertionFailure("Unknown temporal type: " + temporalType);
        }
        explicitType = type;
    } else if (!key && property.isAnnotationPresent(Lob.class)) {
        isLob = true;
        if (buildingContext.getBootstrapContext().getReflectionManager().equals(returnedClassOrElement, java.sql.Clob.class)) {
            type = isNationalized ? StandardBasicTypes.NCLOB.getName() : StandardBasicTypes.CLOB.getName();
        } else if (buildingContext.getBootstrapContext().getReflectionManager().equals(returnedClassOrElement, java.sql.NClob.class)) {
            type = StandardBasicTypes.NCLOB.getName();
        } else if (buildingContext.getBootstrapContext().getReflectionManager().equals(returnedClassOrElement, java.sql.Blob.class)) {
            type = "blob";
        } else if (buildingContext.getBootstrapContext().getReflectionManager().equals(returnedClassOrElement, String.class)) {
            type = isNationalized ? StandardBasicTypes.MATERIALIZED_NCLOB.getName() : StandardBasicTypes.MATERIALIZED_CLOB.getName();
        } else if (buildingContext.getBootstrapContext().getReflectionManager().equals(returnedClassOrElement, Character.class) && isArray) {
            type = isNationalized ? CharacterArrayNClobType.class.getName() : CharacterArrayClobType.class.getName();
        } else if (buildingContext.getBootstrapContext().getReflectionManager().equals(returnedClassOrElement, char.class) && isArray) {
            type = isNationalized ? PrimitiveCharacterArrayNClobType.class.getName() : PrimitiveCharacterArrayClobType.class.getName();
        } else if (buildingContext.getBootstrapContext().getReflectionManager().equals(returnedClassOrElement, Byte.class) && isArray) {
            type = WrappedMaterializedBlobType.class.getName();
        } else if (buildingContext.getBootstrapContext().getReflectionManager().equals(returnedClassOrElement, byte.class) && isArray) {
            type = StandardBasicTypes.MATERIALIZED_BLOB.getName();
        } else if (buildingContext.getBootstrapContext().getReflectionManager().toXClass(Serializable.class).isAssignableFrom(returnedClassOrElement)) {
            type = SerializableToBlobType.class.getName();
            typeParameters.setProperty(SerializableToBlobType.CLASS_NAME, returnedClassOrElement.getName());
        } else {
            type = "blob";
        }
        defaultType = type;
    } else if ((!key && property.isAnnotationPresent(Enumerated.class)) || (key && property.isAnnotationPresent(MapKeyEnumerated.class))) {
        final Class attributeJavaType = buildingContext.getBootstrapContext().getReflectionManager().toClass(returnedClassOrElement);
        if (!Enum.class.isAssignableFrom(attributeJavaType)) {
            throw new AnnotationException(String.format("Attribute [%s.%s] was annotated as enumerated, but its java type is not an enum [%s]", declaringClassName, xproperty.getName(), attributeJavaType.getName()));
        }
        type = EnumType.class.getName();
        explicitType = type;
    } else if (isNationalized) {
        if (buildingContext.getBootstrapContext().getReflectionManager().equals(returnedClassOrElement, String.class)) {
            // nvarchar
            type = StringNVarcharType.INSTANCE.getName();
            explicitType = type;
        } else if (buildingContext.getBootstrapContext().getReflectionManager().equals(returnedClassOrElement, Character.class) || buildingContext.getBootstrapContext().getReflectionManager().equals(returnedClassOrElement, char.class)) {
            if (isArray) {
                // nvarchar
                type = StringNVarcharType.INSTANCE.getName();
            } else {
                // nchar
                type = CharacterNCharType.INSTANCE.getName();
            }
            explicitType = type;
        }
    }
    // implicit type will check basic types and Serializable classes
    if (columns == null) {
        throw new AssertionFailure("SimpleValueBinder.setColumns should be set before SimpleValueBinder.setType");
    }
    if (BinderHelper.ANNOTATION_STRING_DEFAULT.equals(type)) {
        if (returnedClassOrElement.isEnum()) {
            type = EnumType.class.getName();
        }
    }
    defaultType = BinderHelper.isEmptyAnnotationValue(type) ? returnedClassName : type;
    this.typeParameters = typeParameters;
    applyAttributeConverter(property, attributeConverterDescriptor);
}
Also used : Serializable(java.io.Serializable) AssertionFailure(org.hibernate.AssertionFailure) WrappedMaterializedBlobType(org.hibernate.type.WrappedMaterializedBlobType) Properties(java.util.Properties) XClass(org.hibernate.annotations.common.reflection.XClass) Date(java.util.Date) NotYetImplementedException(org.hibernate.cfg.NotYetImplementedException) PrimitiveCharacterArrayNClobType(org.hibernate.type.PrimitiveCharacterArrayNClobType) EnumType(org.hibernate.type.EnumType) AccessType(org.hibernate.cfg.AccessType) WrappedMaterializedBlobType(org.hibernate.type.WrappedMaterializedBlobType) DynamicParameterizedType(org.hibernate.usertype.DynamicParameterizedType) Type(org.hibernate.annotations.Type) CharacterArrayNClobType(org.hibernate.type.CharacterArrayNClobType) PrimitiveCharacterArrayNClobType(org.hibernate.type.PrimitiveCharacterArrayNClobType) SerializableToBlobType(org.hibernate.type.SerializableToBlobType) PrimitiveCharacterArrayClobType(org.hibernate.type.PrimitiveCharacterArrayClobType) CharacterNCharType(org.hibernate.type.CharacterNCharType) CharacterArrayClobType(org.hibernate.type.CharacterArrayClobType) StringNVarcharType(org.hibernate.type.StringNVarcharType) TemporalType(javax.persistence.TemporalType) MapKeyType(org.hibernate.annotations.MapKeyType) PrimitiveCharacterArrayClobType(org.hibernate.type.PrimitiveCharacterArrayClobType) SerializableToBlobType(org.hibernate.type.SerializableToBlobType) EnumType(org.hibernate.type.EnumType) AnnotationException(org.hibernate.AnnotationException) XClass(org.hibernate.annotations.common.reflection.XClass) MapKeyType(org.hibernate.annotations.MapKeyType) Lob(javax.persistence.Lob) TemporalType(javax.persistence.TemporalType)

Example 40 with AnnotationException

use of org.hibernate.AnnotationException in project hibernate-orm by hibernate.

the class OneToOneSecondPass method doSecondPass.

// TODO refactor this code, there is a lot of duplication in this method
public void doSecondPass(Map persistentClasses) throws MappingException {
    org.hibernate.mapping.OneToOne value = new org.hibernate.mapping.OneToOne(buildingContext, propertyHolder.getTable(), propertyHolder.getPersistentClass());
    final String propertyName = inferredData.getPropertyName();
    value.setPropertyName(propertyName);
    String referencedEntityName = ToOneBinder.getReferenceEntityName(inferredData, targetEntity, buildingContext);
    value.setReferencedEntityName(referencedEntityName);
    AnnotationBinder.defineFetchingStrategy(value, inferredData.getProperty());
    // value.setFetchMode( fetchMode );
    value.setCascadeDeleteEnabled(cascadeOnDelete);
    if (!optional) {
        value.setConstrained(true);
    }
    if (value.isReferenceToPrimaryKey()) {
        value.setForeignKeyType(ForeignKeyDirection.TO_PARENT);
    } else {
        value.setForeignKeyType(value.isConstrained() ? ForeignKeyDirection.FROM_PARENT : ForeignKeyDirection.TO_PARENT);
    }
    PropertyBinder binder = new PropertyBinder();
    binder.setName(propertyName);
    binder.setValue(value);
    binder.setCascade(cascadeStrategy);
    binder.setAccessType(inferredData.getDefaultAccess());
    final LazyGroup lazyGroupAnnotation = inferredData.getProperty().getAnnotation(LazyGroup.class);
    if (lazyGroupAnnotation != null) {
        binder.setLazyGroup(lazyGroupAnnotation.value());
    }
    Property prop = binder.makeProperty();
    prop.setOptional(optional);
    if (BinderHelper.isEmptyAnnotationValue(mappedBy)) {
        /*
			 * 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
			 * but actually, since entities linked by a one to one need
			 * to share the same composite id class, this cannot happen in hibernate
			 */
        boolean rightOrder = true;
        if (rightOrder) {
            String path = StringHelper.qualify(propertyHolder.getPath(), propertyName);
            final ToOneFkSecondPass secondPass = new ToOneFkSecondPass(value, joinColumns, // cannot have nullabe and unique on certain DBs
            !optional, propertyHolder.getEntityOwnerClassName(), path, buildingContext);
            secondPass.doSecondPass(persistentClasses);
            // no column associated since its a one to one
            propertyHolder.addProperty(prop, inferredData.getDeclaringClass());
        } else {
        // this is a many to one with Formula
        }
    } else {
        PersistentClass otherSide = (PersistentClass) persistentClasses.get(value.getReferencedEntityName());
        Property otherSideProperty;
        try {
            if (otherSide == null) {
                throw new MappingException("Unable to find entity: " + value.getReferencedEntityName());
            }
            otherSideProperty = BinderHelper.findPropertyByName(otherSide, mappedBy);
        } catch (MappingException e) {
            throw new AnnotationException("Unknown mappedBy in: " + StringHelper.qualify(ownerEntity, ownerProperty) + ", referenced property unknown: " + StringHelper.qualify(value.getReferencedEntityName(), mappedBy));
        }
        if (otherSideProperty == null) {
            throw new AnnotationException("Unknown mappedBy in: " + StringHelper.qualify(ownerEntity, ownerProperty) + ", referenced property unknown: " + StringHelper.qualify(value.getReferencedEntityName(), mappedBy));
        }
        if (otherSideProperty.getValue() instanceof OneToOne) {
            propertyHolder.addProperty(prop, inferredData.getDeclaringClass());
        } else if (otherSideProperty.getValue() instanceof ManyToOne) {
            Iterator it = otherSide.getJoinIterator();
            Join otherSideJoin = null;
            while (it.hasNext()) {
                Join otherSideJoinValue = (Join) it.next();
                if (otherSideJoinValue.containsProperty(otherSideProperty)) {
                    otherSideJoin = otherSideJoinValue;
                    break;
                }
            }
            if (otherSideJoin != null) {
                // @OneToOne @JoinTable
                Join mappedByJoin = buildJoinFromMappedBySide((PersistentClass) persistentClasses.get(ownerEntity), otherSideProperty, otherSideJoin);
                ManyToOne manyToOne = new ManyToOne(buildingContext, mappedByJoin.getTable());
                // FIXME use ignore not found here
                manyToOne.setIgnoreNotFound(ignoreNotFound);
                manyToOne.setCascadeDeleteEnabled(value.isCascadeDeleteEnabled());
                manyToOne.setFetchMode(value.getFetchMode());
                manyToOne.setLazy(value.isLazy());
                manyToOne.setReferencedEntityName(value.getReferencedEntityName());
                manyToOne.setUnwrapProxy(value.isUnwrapProxy());
                prop.setValue(manyToOne);
                Iterator otherSideJoinKeyColumns = otherSideJoin.getKey().getColumnIterator();
                while (otherSideJoinKeyColumns.hasNext()) {
                    Column column = (Column) otherSideJoinKeyColumns.next();
                    Column copy = new Column();
                    copy.setLength(column.getLength());
                    copy.setScale(column.getScale());
                    copy.setValue(manyToOne);
                    copy.setName(column.getQuotedName());
                    copy.setNullable(column.isNullable());
                    copy.setPrecision(column.getPrecision());
                    copy.setUnique(column.isUnique());
                    copy.setSqlType(column.getSqlType());
                    copy.setCheckConstraint(column.getCheckConstraint());
                    copy.setComment(column.getComment());
                    copy.setDefaultValue(column.getDefaultValue());
                    manyToOne.addColumn(copy);
                }
                mappedByJoin.addProperty(prop);
            } else {
                propertyHolder.addProperty(prop, inferredData.getDeclaringClass());
            }
            value.setReferencedPropertyName(mappedBy);
            // HHH-6813
            // Foo: @Id long id, @OneToOne(mappedBy="foo") Bar bar
            // Bar: @Id @OneToOne Foo foo
            boolean referencesDerivedId = false;
            try {
                referencesDerivedId = otherSide.getIdentifier() instanceof Component && ((Component) otherSide.getIdentifier()).getProperty(mappedBy) != null;
            } catch (MappingException e) {
            // ignore
            }
            boolean referenceToPrimaryKey = referencesDerivedId || mappedBy == null;
            value.setReferenceToPrimaryKey(referenceToPrimaryKey);
            // loop of attempts to resolve identifiers.
            if (referencesDerivedId) {
                ((ManyToOne) otherSideProperty.getValue()).setReferenceToPrimaryKey(false);
            }
            String propertyRef = value.getReferencedPropertyName();
            if (propertyRef != null) {
                buildingContext.getMetadataCollector().addUniquePropertyReference(value.getReferencedEntityName(), propertyRef);
            }
        } else {
            throw new AnnotationException("Referenced property not a (One|Many)ToOne: " + StringHelper.qualify(otherSide.getEntityName(), mappedBy) + " in mappedBy of " + StringHelper.qualify(ownerEntity, ownerProperty));
        }
    }
    final ForeignKey fk = inferredData.getProperty().getAnnotation(ForeignKey.class);
    if (fk != null && !BinderHelper.isEmptyAnnotationValue(fk.name())) {
        value.setForeignKeyName(fk.name());
    } else {
        final javax.persistence.ForeignKey jpaFk = inferredData.getProperty().getAnnotation(javax.persistence.ForeignKey.class);
        if (jpaFk != null) {
            if (jpaFk.value() == ConstraintMode.NO_CONSTRAINT) {
                value.setForeignKeyName("none");
            } else {
                value.setForeignKeyName(StringHelper.nullIfEmpty(jpaFk.name()));
                value.setForeignKeyDefinition(StringHelper.nullIfEmpty(jpaFk.foreignKeyDefinition()));
            }
        }
    }
}
Also used : OneToOne(org.hibernate.mapping.OneToOne) Join(org.hibernate.mapping.Join) ForeignKey(org.hibernate.annotations.ForeignKey) ManyToOne(org.hibernate.mapping.ManyToOne) MappingException(org.hibernate.MappingException) OneToOne(org.hibernate.mapping.OneToOne) Column(org.hibernate.mapping.Column) LazyGroup(org.hibernate.annotations.LazyGroup) Iterator(java.util.Iterator) AnnotationException(org.hibernate.AnnotationException) PropertyBinder(org.hibernate.cfg.annotations.PropertyBinder) Component(org.hibernate.mapping.Component) Property(org.hibernate.mapping.Property) PersistentClass(org.hibernate.mapping.PersistentClass)

Aggregations

AnnotationException (org.hibernate.AnnotationException)85 AnnotationDescriptor (org.hibernate.annotations.common.annotationfactory.AnnotationDescriptor)15 PersistentClass (org.hibernate.mapping.PersistentClass)14 AnnotatedElement (java.lang.reflect.AnnotatedElement)12 Element (org.dom4j.Element)12 XClass (org.hibernate.annotations.common.reflection.XClass)12 HashMap (java.util.HashMap)11 MappingException (org.hibernate.MappingException)11 XProperty (org.hibernate.annotations.common.reflection.XProperty)11 Property (org.hibernate.mapping.Property)11 SimpleValue (org.hibernate.mapping.SimpleValue)11 Test (org.junit.Test)10 AssertionFailure (org.hibernate.AssertionFailure)9 ArrayList (java.util.ArrayList)8 ClassLoadingException (org.hibernate.boot.registry.classloading.spi.ClassLoadingException)8 Column (org.hibernate.mapping.Column)8 IdClass (javax.persistence.IdClass)7 MapKeyClass (javax.persistence.MapKeyClass)7 Component (org.hibernate.mapping.Component)7 Properties (java.util.Properties)6