Search in sources :

Example 1 with ForeignKeyDirection

use of org.hibernate.type.ForeignKeyDirection 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<String, PersistentClass> persistentClasses) throws MappingException {
    OneToOne value = new 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);
    // value.setLazy( fetchMode != FetchMode.JOIN );
    value.setConstrained(!optional);
    final ForeignKeyDirection foreignKeyDirection = !BinderHelper.isEmptyAnnotationValue(mappedBy) ? ForeignKeyDirection.TO_PARENT : ForeignKeyDirection.FROM_PARENT;
    value.setForeignKeyType(foreignKeyDirection);
    AnnotationBinder.bindForeignKeyNameAndDefinition(value, inferredData.getProperty(), inferredData.getProperty().getAnnotation(jakarta.persistence.ForeignKey.class), inferredData.getProperty().getAnnotation(JoinColumn.class), inferredData.getProperty().getAnnotation(JoinColumns.class), buildingContext);
    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 {
        value.setMappedByProperty(mappedBy);
        PersistentClass otherSide = 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) {
            Join otherSideJoin = null;
            for (Join otherSideJoinValue : otherSide.getJoins()) {
                if (otherSideJoinValue.containsProperty(otherSideProperty)) {
                    otherSideJoin = otherSideJoinValue;
                    break;
                }
            }
            if (otherSideJoin != null) {
                // @OneToOne @JoinTable
                Join mappedByJoin = buildJoinFromMappedBySide(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());
                manyToOne.markAsLogicalOneToOne();
                prop.setValue(manyToOne);
                for (Column column : otherSideJoin.getKey().getColumns()) {
                    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());
                    copy.setGeneratedAs(column.getGeneratedAs());
                    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);
            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));
        }
    }
    value.sortProperties();
}
Also used : JoinColumns(jakarta.persistence.JoinColumns) Join(org.hibernate.mapping.Join) ForeignKeyDirection(org.hibernate.type.ForeignKeyDirection) ManyToOne(org.hibernate.mapping.ManyToOne) MappingException(org.hibernate.MappingException) OneToOne(org.hibernate.mapping.OneToOne) JoinColumn(jakarta.persistence.JoinColumn) Column(org.hibernate.mapping.Column) JoinColumn(jakarta.persistence.JoinColumn) LazyGroup(org.hibernate.annotations.LazyGroup) 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 2 with ForeignKeyDirection

use of org.hibernate.type.ForeignKeyDirection in project cdmlib by cybertaxonomy.

the class CdmGenericDaoImpl method makePropertyType.

private void makePropertyType(// CdmBase referencedCdmBase,
Set<ReferenceHolder> result, Class<?> referencedClass, SessionFactory sessionFactory, Class<? extends CdmBase> cdmClass, Type propertyType, String propertyName, boolean isCollection) throws ClassNotFoundException, NoSuchFieldException {
    if (propertyType.isEntityType()) {
        EntityType entityType = (EntityType) propertyType;
        String associatedEntityName = entityType.getAssociatedEntityName();
        Class<?> entityClass = Class.forName(associatedEntityName);
        if (entityClass.isInterface()) {
            logger.debug("There is an interface");
        }
        if (entityType instanceof OneToOneType) {
            OneToOneType oneToOneType = (OneToOneType) entityType;
            ForeignKeyDirection direction = oneToOneType.getForeignKeyDirection();
            if (direction == ForeignKeyDirection.TO_PARENT) {
                // this
                return;
            }
        }
        if (entityClass.isAssignableFrom(referencedClass)) {
            makeSingleProperty(referencedClass, entityClass, propertyName, cdmClass, result, isCollection);
        }
    } else if (propertyType.isCollectionType()) {
        CollectionType collectionType = (CollectionType) propertyType;
        // String role = collectionType.getRole();
        Type elType = collectionType.getElementType((SessionFactoryImplementor) sessionFactory);
        makePropertyType(result, referencedClass, sessionFactory, cdmClass, elType, propertyName, true);
    } else if (propertyType.isAnyType()) {
        // AnyType anyType = (AnyType)propertyType;
        Field field = cdmClass.getDeclaredField(propertyName);
        Class<?> returnType = field.getType();
        if (returnType.isInterface()) {
            logger.debug("There is an interface");
        }
        if (returnType.isAssignableFrom(referencedClass)) {
            makeSingleProperty(referencedClass, returnType, propertyName, cdmClass, result, isCollection);
        }
    } else if (propertyType.isComponentType()) {
        ComponentType componentType = (ComponentType) propertyType;
        Type[] subTypes = componentType.getSubtypes();
        // Field field = cdmClass.getDeclaredField(propertyName);
        // Class returnType = field.getType();
        int propertyNr = 0;
        for (Type subType : subTypes) {
            String subPropertyName = componentType.getPropertyNames()[propertyNr];
            if (!isNoDoType(subType)) {
                logger.warn("SubType not yet handled: " + subType);
            }
            // handlePropertyType(referencedCdmBase, result, referencedClass,
            // sessionFactory, cdmClass, subType, subPropertyName, isCollection);
            propertyNr++;
        }
    } else if (isNoDoType(propertyType)) {
    // do nothing
    } else {
        logger.warn("propertyType not yet handled: " + propertyType.getName());
    }
// OLD:
// if (! type.isInterface()){
// if (referencedClass.isAssignableFrom(type)||
// type.isAssignableFrom(referencedClass) && CdmBase.class.isAssignableFrom(type)){
// handleSingleClass(referencedClass, type, field, cdmClass, result, referencedCdmBase, false);
// }
// //interface
// }else if (type.isAssignableFrom(referencedClass)){
// handleSingleClass(referencedClass, type, field, cdmClass, result, referencedCdmBase, false);
}
Also used : EntityType(org.hibernate.type.EntityType) Field(java.lang.reflect.Field) OrcidUserType(eu.etaxonomy.cdm.hibernate.OrcidUserType) IntegerType(org.hibernate.type.IntegerType) EnumType(org.hibernate.type.EnumType) JoinType(org.hibernate.sql.JoinType) OneToOneType(org.hibernate.type.OneToOneType) DoubleType(org.hibernate.type.DoubleType) MaterializedClobType(org.hibernate.type.MaterializedClobType) BooleanType(org.hibernate.type.BooleanType) PartialUserType(eu.etaxonomy.cdm.hibernate.PartialUserType) EnumUserType(eu.etaxonomy.cdm.hibernate.EnumUserType) FloatType(org.hibernate.type.FloatType) CollectionType(org.hibernate.type.CollectionType) EntityType(org.hibernate.type.EntityType) WSDLDefinitionUserType(eu.etaxonomy.cdm.hibernate.WSDLDefinitionUserType) DOIUserType(eu.etaxonomy.cdm.hibernate.DOIUserType) ComponentType(org.hibernate.type.ComponentType) StringType(org.hibernate.type.StringType) LongType(org.hibernate.type.LongType) SeverityUserType(eu.etaxonomy.cdm.hibernate.SeverityUserType) SerializableType(org.hibernate.type.SerializableType) UUIDUserType(eu.etaxonomy.cdm.hibernate.UUIDUserType) URIUserType(eu.etaxonomy.cdm.hibernate.URIUserType) BigDecimalUserType(eu.etaxonomy.cdm.hibernate.BigDecimalUserType) ShiftUserType(eu.etaxonomy.cdm.hibernate.ShiftUserType) Type(org.hibernate.type.Type) EnumSetUserType(eu.etaxonomy.cdm.hibernate.EnumSetUserType) ComponentType(org.hibernate.type.ComponentType) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) CollectionType(org.hibernate.type.CollectionType) ForeignKeyDirection(org.hibernate.type.ForeignKeyDirection) OneToOneType(org.hibernate.type.OneToOneType)

Aggregations

ForeignKeyDirection (org.hibernate.type.ForeignKeyDirection)2 BigDecimalUserType (eu.etaxonomy.cdm.hibernate.BigDecimalUserType)1 DOIUserType (eu.etaxonomy.cdm.hibernate.DOIUserType)1 EnumSetUserType (eu.etaxonomy.cdm.hibernate.EnumSetUserType)1 EnumUserType (eu.etaxonomy.cdm.hibernate.EnumUserType)1 OrcidUserType (eu.etaxonomy.cdm.hibernate.OrcidUserType)1 PartialUserType (eu.etaxonomy.cdm.hibernate.PartialUserType)1 SeverityUserType (eu.etaxonomy.cdm.hibernate.SeverityUserType)1 ShiftUserType (eu.etaxonomy.cdm.hibernate.ShiftUserType)1 URIUserType (eu.etaxonomy.cdm.hibernate.URIUserType)1 UUIDUserType (eu.etaxonomy.cdm.hibernate.UUIDUserType)1 WSDLDefinitionUserType (eu.etaxonomy.cdm.hibernate.WSDLDefinitionUserType)1 JoinColumn (jakarta.persistence.JoinColumn)1 JoinColumns (jakarta.persistence.JoinColumns)1 Field (java.lang.reflect.Field)1 AnnotationException (org.hibernate.AnnotationException)1 MappingException (org.hibernate.MappingException)1 LazyGroup (org.hibernate.annotations.LazyGroup)1 PropertyBinder (org.hibernate.cfg.annotations.PropertyBinder)1 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)1