Search in sources :

Example 91 with PersistentClass

use of org.hibernate.mapping.PersistentClass 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 92 with PersistentClass

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

the class PersisterTest method testEntityEntityPersisterSpecified.

@Test
public void testEntityEntityPersisterSpecified() throws Exception {
    // tests the persister specified with an @Entity.persister()
    PersistentClass persistentClass = metadata().getEntityBinding(Card.class.getName());
    assertEquals("Incorrect Persister class for " + persistentClass.getMappedClass(), SingleTableEntityPersister.class, persistentClass.getEntityPersisterClass());
}
Also used : PersistentClass(org.hibernate.mapping.PersistentClass) Test(org.junit.Test)

Example 93 with PersistentClass

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

the class PersisterTest method testEntityEntityPersisterAndPersisterSpecified.

@Test
public void testEntityEntityPersisterAndPersisterSpecified() throws Exception {
    // checks to see that the persister specified with the @Persister annotation takes precedence if a @Entity.persister() is also specified
    PersistentClass persistentClass = metadata().getEntityBinding(Deck.class.getName());
    assertEquals("Incorrect Persister class for " + persistentClass.getMappedClass(), EntityPersister.class, persistentClass.getEntityPersisterClass());
}
Also used : PersistentClass(org.hibernate.mapping.PersistentClass) Test(org.junit.Test)

Example 94 with PersistentClass

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

the class ClassesAuditingData method updateCalculatedFields.

/**
 * After all meta-data is read, updates calculated fields. This includes:
 * <ul>
 * <li>setting {@code forceInsertable} to {@code true} for properties specified by {@code @AuditMappedBy}</li>
 * <li>adding {@code synthetic} properties to mappedBy relations which have {@code IndexColumn} or {@code OrderColumn}.</li>
 * </ul>
 */
public void updateCalculatedFields() {
    for (Map.Entry<PersistentClass, ClassAuditingData> classAuditingDataEntry : persistentClassToAuditingData.entrySet()) {
        final PersistentClass pc = classAuditingDataEntry.getKey();
        final ClassAuditingData classAuditingData = classAuditingDataEntry.getValue();
        for (String propertyName : classAuditingData.getNonSyntheticPropertyNames()) {
            final Property property = pc.getProperty(propertyName);
            updateCalculatedProperty(pc.getEntityName(), property, propertyName, classAuditingData);
        }
    }
}
Also used : ClassAuditingData(org.hibernate.envers.configuration.internal.metadata.reader.ClassAuditingData) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) Property(org.hibernate.mapping.Property) PersistentClass(org.hibernate.mapping.PersistentClass)

Example 95 with PersistentClass

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

the class BaseNonConfigCoreFunctionalTestCase method applyCacheSettings.

protected final void applyCacheSettings(Metadata metadata) {
    if (!overrideCacheStrategy()) {
        return;
    }
    if (getCacheConcurrencyStrategy() == null) {
        return;
    }
    for (PersistentClass entityBinding : metadata.getEntityBindings()) {
        if (entityBinding.isInherited()) {
            continue;
        }
        boolean hasLob = false;
        final Iterator props = entityBinding.getPropertyClosureIterator();
        while (props.hasNext()) {
            final Property prop = (Property) props.next();
            if (prop.getValue().isSimpleValue()) {
                if (isLob(((SimpleValue) prop.getValue()).getTypeName())) {
                    hasLob = true;
                    break;
                }
            }
        }
        if (!hasLob) {
            ((RootClass) entityBinding).setCacheConcurrencyStrategy(getCacheConcurrencyStrategy());
            entityBinding.setCached(true);
        }
    }
    for (Collection collectionBinding : metadata.getCollectionBindings()) {
        boolean isLob = false;
        if (collectionBinding.getElement().isSimpleValue()) {
            isLob = isLob(((SimpleValue) collectionBinding.getElement()).getTypeName());
        }
        if (!isLob) {
            collectionBinding.setCacheConcurrencyStrategy(getCacheConcurrencyStrategy());
        }
    }
}
Also used : RootClass(org.hibernate.mapping.RootClass) Iterator(java.util.Iterator) Collection(org.hibernate.mapping.Collection) Property(org.hibernate.mapping.Property) PersistentClass(org.hibernate.mapping.PersistentClass) SimpleValue(org.hibernate.mapping.SimpleValue)

Aggregations

PersistentClass (org.hibernate.mapping.PersistentClass)229 Test (org.junit.Test)121 Property (org.hibernate.mapping.Property)65 MetadataSources (org.hibernate.boot.MetadataSources)53 IPersistentClass (org.jboss.tools.hibernate.runtime.spi.IPersistentClass)52 RootClass (org.hibernate.mapping.RootClass)50 Metadata (org.hibernate.boot.Metadata)45 Column (org.hibernate.mapping.Column)43 StandardServiceRegistryBuilder (org.hibernate.boot.registry.StandardServiceRegistryBuilder)42 StandardServiceRegistry (org.hibernate.boot.registry.StandardServiceRegistry)38 Iterator (java.util.Iterator)30 SimpleValue (org.hibernate.mapping.SimpleValue)24 HashMap (java.util.HashMap)22 Collection (org.hibernate.mapping.Collection)21 MappingException (org.hibernate.MappingException)20 MetadataImplementor (org.hibernate.boot.spi.MetadataImplementor)20 Table (org.hibernate.mapping.Table)20 Map (java.util.Map)19 ArrayList (java.util.ArrayList)18 TestForIssue (org.hibernate.testing.TestForIssue)18