Search in sources :

Example 26 with OneToOne

use of org.hibernate.mapping.OneToOne in project hibernate-orm by hibernate.

the class ToOneFkSecondPass method doSecondPass.

public void doSecondPass(java.util.Map persistentClasses) throws MappingException {
    if (value instanceof ManyToOne) {
        ManyToOne manyToOne = (ManyToOne) value;
        PersistentClass ref = (PersistentClass) persistentClasses.get(manyToOne.getReferencedEntityName());
        if (ref == null) {
            throw new AnnotationException("@OneToOne or @ManyToOne on " + StringHelper.qualify(entityClassName, path) + " references an unknown entity: " + manyToOne.getReferencedEntityName());
        }
        manyToOne.setPropertyName(path);
        BinderHelper.createSyntheticPropertyReference(columns, ref, null, manyToOne, false, buildingContext);
        TableBinder.bindFk(ref, null, columns, manyToOne, unique, buildingContext);
        /*
			 * HbmMetadataSourceProcessorImpl does this only when property-ref != null, but IMO, it makes sense event if it is null
			 */
        if (!manyToOne.isIgnoreNotFound())
            manyToOne.createPropertyRefConstraints(persistentClasses);
    } else if (value instanceof OneToOne) {
        value.createForeignKey();
    } else {
        throw new AssertionFailure("FkSecondPass for a wrong value type: " + value.getClass().getName());
    }
}
Also used : OneToOne(org.hibernate.mapping.OneToOne) AssertionFailure(org.hibernate.AssertionFailure) AnnotationException(org.hibernate.AnnotationException) ManyToOne(org.hibernate.mapping.ManyToOne) PersistentClass(org.hibernate.mapping.PersistentClass)

Example 27 with OneToOne

use of org.hibernate.mapping.OneToOne 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)

Example 28 with OneToOne

use of org.hibernate.mapping.OneToOne in project hibernate-orm by hibernate.

the class ValueVisitorTest method testProperCallbacks.

@Test
public void testProperCallbacks() {
    final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources(serviceRegistry).buildMetadata();
    final Table tbl = new Table();
    final RootClass rootClass = new RootClass(metadataBuildingContext);
    ValueVisitor vv = new ValueVisitorValidator();
    MetadataBuildingContextTestingImpl metadataBuildingContext = new MetadataBuildingContextTestingImpl();
    new Any(metadataBuildingContext, tbl).accept(vv);
    new Array(metadataBuildingContext, rootClass).accept(vv);
    new Bag(metadataBuildingContext, rootClass).accept(vv);
    new Component(metadataBuildingContext, rootClass).accept(vv);
    new DependantValue(metadataBuildingContext, tbl, null).accept(vv);
    new IdentifierBag(metadataBuildingContext, rootClass).accept(vv);
    new List(metadataBuildingContext, rootClass).accept(vv);
    new ManyToOne(metadataBuildingContext, tbl).accept(vv);
    new Map(metadataBuildingContext, rootClass).accept(vv);
    new OneToMany(metadataBuildingContext, rootClass).accept(vv);
    new OneToOne(metadataBuildingContext, tbl, rootClass).accept(vv);
    new PrimitiveArray(metadataBuildingContext, rootClass).accept(vv);
    new Set(metadataBuildingContext, rootClass).accept(vv);
    new SimpleValue(metadataBuildingContext).accept(vv);
}
Also used : RootClass(org.hibernate.mapping.RootClass) Table(org.hibernate.mapping.Table) Set(org.hibernate.mapping.Set) ValueVisitor(org.hibernate.mapping.ValueVisitor) DependantValue(org.hibernate.mapping.DependantValue) MetadataSources(org.hibernate.boot.MetadataSources) Bag(org.hibernate.mapping.Bag) IdentifierBag(org.hibernate.mapping.IdentifierBag) MetadataImplementor(org.hibernate.boot.spi.MetadataImplementor) IdentifierBag(org.hibernate.mapping.IdentifierBag) OneToMany(org.hibernate.mapping.OneToMany) Any(org.hibernate.mapping.Any) ManyToOne(org.hibernate.mapping.ManyToOne) SimpleValue(org.hibernate.mapping.SimpleValue) MetadataBuildingContextTestingImpl(org.hibernate.testing.boot.MetadataBuildingContextTestingImpl) Array(org.hibernate.mapping.Array) PrimitiveArray(org.hibernate.mapping.PrimitiveArray) OneToOne(org.hibernate.mapping.OneToOne) PrimitiveArray(org.hibernate.mapping.PrimitiveArray) List(org.hibernate.mapping.List) Component(org.hibernate.mapping.Component) Map(org.hibernate.mapping.Map) Test(org.junit.Test)

Example 29 with OneToOne

use of org.hibernate.mapping.OneToOne in project hibernate-orm by hibernate.

the class ToOneRelationMetadataGenerator method addOneToOneNotOwning.

@SuppressWarnings({ "unchecked" })
void addOneToOneNotOwning(PropertyAuditingData propertyAuditingData, Value value, CompositeMapperBuilder mapper, String entityName) {
    final OneToOne propertyValue = (OneToOne) value;
    final String owningReferencePropertyName = propertyValue.getReferencedPropertyName();
    final EntityConfiguration configuration = mainGenerator.getEntitiesConfigurations().get(entityName);
    if (configuration == null) {
        throw new MappingException("An audited relation to a non-audited entity " + entityName + "!");
    }
    final IdMappingData ownedIdMapping = configuration.getIdMappingData();
    if (ownedIdMapping == null) {
        throw new MappingException("An audited relation to a non-audited entity " + entityName + "!");
    }
    final String lastPropertyPrefix = MappingTools.createToOneRelationPrefix(owningReferencePropertyName);
    final String referencedEntityName = propertyValue.getReferencedEntityName();
    // Generating the id mapper for the relation
    final IdMapper ownedIdMapper = ownedIdMapping.getIdMapper().prefixMappedProperties(lastPropertyPrefix);
    // Storing information about this relation
    mainGenerator.getEntitiesConfigurations().get(entityName).addToOneNotOwningRelation(propertyAuditingData.getName(), owningReferencePropertyName, referencedEntityName, ownedIdMapper, MappingTools.ignoreNotFound(value));
    // Adding mapper for the id
    final PropertyData propertyData = propertyAuditingData.getPropertyData();
    mapper.addComposite(propertyData, new OneToOneNotOwningMapper(entityName, referencedEntityName, owningReferencePropertyName, propertyData, mainGenerator.getServiceRegistry()));
}
Also used : OneToOne(org.hibernate.mapping.OneToOne) PropertyData(org.hibernate.envers.internal.entities.PropertyData) OneToOneNotOwningMapper(org.hibernate.envers.internal.entities.mapper.relation.OneToOneNotOwningMapper) EntityConfiguration(org.hibernate.envers.internal.entities.EntityConfiguration) IdMapper(org.hibernate.envers.internal.entities.mapper.id.IdMapper) ToOneIdMapper(org.hibernate.envers.internal.entities.mapper.relation.ToOneIdMapper) MappingException(org.hibernate.MappingException) IdMappingData(org.hibernate.envers.internal.entities.IdMappingData)

Example 30 with OneToOne

use of org.hibernate.mapping.OneToOne in project hibernate-orm by hibernate.

the class ModelBinder method bindAllCompositeAttributes.

private void bindAllCompositeAttributes(MappingDocument sourceDocument, EmbeddableSource embeddableSource, Component component) {
    for (AttributeSource attributeSource : embeddableSource.attributeSources()) {
        Property attribute = null;
        if (SingularAttributeSourceBasic.class.isInstance(attributeSource)) {
            attribute = createBasicAttribute(sourceDocument, (SingularAttributeSourceBasic) attributeSource, new SimpleValue(sourceDocument, component.getTable()), component.getComponentClassName());
        } else if (SingularAttributeSourceEmbedded.class.isInstance(attributeSource)) {
            attribute = createEmbeddedAttribute(sourceDocument, (SingularAttributeSourceEmbedded) attributeSource, new Component(sourceDocument, component), component.getComponentClassName());
        } else if (SingularAttributeSourceManyToOne.class.isInstance(attributeSource)) {
            attribute = createManyToOneAttribute(sourceDocument, (SingularAttributeSourceManyToOne) attributeSource, new ManyToOne(sourceDocument, component.getTable()), component.getComponentClassName());
        } else if (SingularAttributeSourceOneToOne.class.isInstance(attributeSource)) {
            attribute = createOneToOneAttribute(sourceDocument, (SingularAttributeSourceOneToOne) attributeSource, new OneToOne(sourceDocument, component.getTable(), component.getOwner()), component.getComponentClassName());
        } else if (SingularAttributeSourceAny.class.isInstance(attributeSource)) {
            attribute = createAnyAssociationAttribute(sourceDocument, (SingularAttributeSourceAny) attributeSource, new Any(sourceDocument, component.getTable()), component.getComponentClassName());
        } else if (PluralAttributeSource.class.isInstance(attributeSource)) {
            attribute = createPluralAttribute(sourceDocument, (PluralAttributeSource) attributeSource, component.getOwner());
        } else {
            throw new AssertionFailure(String.format(Locale.ENGLISH, "Unexpected AttributeSource sub-type [%s] as part of composite [%s]", attributeSource.getClass().getName(), attributeSource.getAttributeRole().getFullPath()));
        }
        component.addProperty(attribute);
    }
}
Also used : SingularAttributeSourceBasic(org.hibernate.boot.model.source.spi.SingularAttributeSourceBasic) VersionAttributeSource(org.hibernate.boot.model.source.spi.VersionAttributeSource) AttributeSource(org.hibernate.boot.model.source.spi.AttributeSource) PluralAttributeSource(org.hibernate.boot.model.source.spi.PluralAttributeSource) SingularAttributeSource(org.hibernate.boot.model.source.spi.SingularAttributeSource) SingularAttributeSourceAny(org.hibernate.boot.model.source.spi.SingularAttributeSourceAny) AssertionFailure(org.hibernate.AssertionFailure) SingularAttributeSourceManyToOne(org.hibernate.boot.model.source.spi.SingularAttributeSourceManyToOne) SingularAttributeSourceOneToOne(org.hibernate.boot.model.source.spi.SingularAttributeSourceOneToOne) PluralAttributeElementSourceManyToAny(org.hibernate.boot.model.source.spi.PluralAttributeElementSourceManyToAny) Any(org.hibernate.mapping.Any) SingularAttributeSourceAny(org.hibernate.boot.model.source.spi.SingularAttributeSourceAny) SingularAttributeSourceEmbedded(org.hibernate.boot.model.source.spi.SingularAttributeSourceEmbedded) SingularAttributeSourceManyToOne(org.hibernate.boot.model.source.spi.SingularAttributeSourceManyToOne) ManyToOne(org.hibernate.mapping.ManyToOne) SimpleValue(org.hibernate.mapping.SimpleValue) PluralAttributeSource(org.hibernate.boot.model.source.spi.PluralAttributeSource) OneToOne(org.hibernate.mapping.OneToOne) SingularAttributeSourceOneToOne(org.hibernate.boot.model.source.spi.SingularAttributeSourceOneToOne) Component(org.hibernate.mapping.Component) Property(org.hibernate.mapping.Property) SyntheticProperty(org.hibernate.mapping.SyntheticProperty)

Aggregations

OneToOne (org.hibernate.mapping.OneToOne)54 Test (org.junit.jupiter.api.Test)44 RootClass (org.hibernate.mapping.RootClass)37 SimpleValue (org.hibernate.mapping.SimpleValue)37 ManyToOne (org.hibernate.mapping.ManyToOne)17 ToOne (org.hibernate.mapping.ToOne)12 IFacade (org.jboss.tools.hibernate.runtime.common.IFacade)11 IPersistentClass (org.jboss.tools.hibernate.runtime.spi.IPersistentClass)11 IValue (org.jboss.tools.hibernate.runtime.spi.IValue)11 Component (org.hibernate.mapping.Component)4 Test (org.junit.Test)4 AssertionFailure (org.hibernate.AssertionFailure)3 Any (org.hibernate.mapping.Any)3 BasicValue (org.hibernate.mapping.BasicValue)3 Property (org.hibernate.mapping.Property)3 AbstractValueFacade (org.jboss.tools.hibernate.runtime.common.AbstractValueFacade)3 AnnotationException (org.hibernate.AnnotationException)2 MappingException (org.hibernate.MappingException)2 AttributeSource (org.hibernate.boot.model.source.spi.AttributeSource)2 PluralAttributeElementSourceManyToAny (org.hibernate.boot.model.source.spi.PluralAttributeElementSourceManyToAny)2