Search in sources :

Example 1 with Any

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

the class ModelBinder method bindAllEntityAttributes.

private void bindAllEntityAttributes(MappingDocument mappingDocument, EntitySource entitySource, PersistentClass entityDescriptor) {
    final EntityTableXref entityTableXref = mappingDocument.getMetadataCollector().getEntityTableXref(entityDescriptor.getEntityName());
    if (entityTableXref == null) {
        throw new AssertionFailure(String.format(Locale.ENGLISH, "Unable to locate EntityTableXref for entity [%s] : %s", entityDescriptor.getEntityName(), mappingDocument.getOrigin()));
    }
    // make sure we bind secondary tables first!
    for (SecondaryTableSource secondaryTableSource : entitySource.getSecondaryTableMap().values()) {
        final Join secondaryTableJoin = new Join();
        secondaryTableJoin.setPersistentClass(entityDescriptor);
        bindSecondaryTable(mappingDocument, secondaryTableSource, secondaryTableJoin, entityTableXref);
        entityDescriptor.addJoin(secondaryTableJoin);
    }
    for (AttributeSource attributeSource : entitySource.attributeSources()) {
        if (PluralAttributeSource.class.isInstance(attributeSource)) {
            // plural attribute
            final Property attribute = createPluralAttribute(mappingDocument, (PluralAttributeSource) attributeSource, entityDescriptor);
            entityDescriptor.addProperty(attribute);
        } else {
            // singular attribute
            if (SingularAttributeSourceBasic.class.isInstance(attributeSource)) {
                final SingularAttributeSourceBasic basicAttributeSource = (SingularAttributeSourceBasic) attributeSource;
                final Identifier tableName = determineTable(mappingDocument, basicAttributeSource.getName(), basicAttributeSource);
                final AttributeContainer attributeContainer;
                final Table table;
                final Join secondaryTableJoin = entityTableXref.locateJoin(tableName);
                if (secondaryTableJoin == null) {
                    table = entityDescriptor.getTable();
                    attributeContainer = entityDescriptor;
                } else {
                    table = secondaryTableJoin.getTable();
                    attributeContainer = secondaryTableJoin;
                }
                final Property attribute = createBasicAttribute(mappingDocument, basicAttributeSource, new SimpleValue(mappingDocument.getMetadataCollector(), table), entityDescriptor.getClassName());
                if (secondaryTableJoin != null) {
                    attribute.setOptional(secondaryTableJoin.isOptional());
                }
                attributeContainer.addProperty(attribute);
                handleNaturalIdBinding(mappingDocument, entityDescriptor, attribute, basicAttributeSource.getNaturalIdMutability());
            } else if (SingularAttributeSourceEmbedded.class.isInstance(attributeSource)) {
                final SingularAttributeSourceEmbedded embeddedAttributeSource = (SingularAttributeSourceEmbedded) attributeSource;
                final Identifier tableName = determineTable(mappingDocument, embeddedAttributeSource);
                final AttributeContainer attributeContainer;
                final Table table;
                final Join secondaryTableJoin = entityTableXref.locateJoin(tableName);
                if (secondaryTableJoin == null) {
                    table = entityDescriptor.getTable();
                    attributeContainer = entityDescriptor;
                } else {
                    table = secondaryTableJoin.getTable();
                    attributeContainer = secondaryTableJoin;
                }
                final Property attribute = createEmbeddedAttribute(mappingDocument, (SingularAttributeSourceEmbedded) attributeSource, new Component(mappingDocument.getMetadataCollector(), table, entityDescriptor), entityDescriptor.getClassName());
                if (secondaryTableJoin != null) {
                    attribute.setOptional(secondaryTableJoin.isOptional());
                }
                attributeContainer.addProperty(attribute);
                handleNaturalIdBinding(mappingDocument, entityDescriptor, attribute, embeddedAttributeSource.getNaturalIdMutability());
            } else if (SingularAttributeSourceManyToOne.class.isInstance(attributeSource)) {
                final SingularAttributeSourceManyToOne manyToOneAttributeSource = (SingularAttributeSourceManyToOne) attributeSource;
                final Identifier tableName = determineTable(mappingDocument, manyToOneAttributeSource.getName(), manyToOneAttributeSource);
                final AttributeContainer attributeContainer;
                final Table table;
                final Join secondaryTableJoin = entityTableXref.locateJoin(tableName);
                if (secondaryTableJoin == null) {
                    table = entityDescriptor.getTable();
                    attributeContainer = entityDescriptor;
                } else {
                    table = secondaryTableJoin.getTable();
                    attributeContainer = secondaryTableJoin;
                }
                final Property attribute = createManyToOneAttribute(mappingDocument, manyToOneAttributeSource, new ManyToOne(mappingDocument.getMetadataCollector(), table), entityDescriptor.getClassName());
                if (secondaryTableJoin != null) {
                    attribute.setOptional(secondaryTableJoin.isOptional());
                }
                attributeContainer.addProperty(attribute);
                handleNaturalIdBinding(mappingDocument, entityDescriptor, attribute, manyToOneAttributeSource.getNaturalIdMutability());
            } else if (SingularAttributeSourceOneToOne.class.isInstance(attributeSource)) {
                final SingularAttributeSourceOneToOne oneToOneAttributeSource = (SingularAttributeSourceOneToOne) attributeSource;
                final Table table = entityDescriptor.getTable();
                final Property attribute = createOneToOneAttribute(mappingDocument, oneToOneAttributeSource, new OneToOne(mappingDocument.getMetadataCollector(), table, entityDescriptor), entityDescriptor.getClassName());
                entityDescriptor.addProperty(attribute);
                handleNaturalIdBinding(mappingDocument, entityDescriptor, attribute, oneToOneAttributeSource.getNaturalIdMutability());
            } else if (SingularAttributeSourceAny.class.isInstance(attributeSource)) {
                final SingularAttributeSourceAny anyAttributeSource = (SingularAttributeSourceAny) attributeSource;
                final Identifier tableName = determineTable(mappingDocument, anyAttributeSource.getName(), anyAttributeSource.getKeySource().getRelationalValueSources());
                final AttributeContainer attributeContainer;
                final Table table;
                final Join secondaryTableJoin = entityTableXref.locateJoin(tableName);
                if (secondaryTableJoin == null) {
                    table = entityDescriptor.getTable();
                    attributeContainer = entityDescriptor;
                } else {
                    table = secondaryTableJoin.getTable();
                    attributeContainer = secondaryTableJoin;
                }
                final Property attribute = createAnyAssociationAttribute(mappingDocument, anyAttributeSource, new Any(mappingDocument.getMetadataCollector(), table), entityDescriptor.getEntityName());
                if (secondaryTableJoin != null) {
                    attribute.setOptional(secondaryTableJoin.isOptional());
                }
                attributeContainer.addProperty(attribute);
                handleNaturalIdBinding(mappingDocument, entityDescriptor, attribute, anyAttributeSource.getNaturalIdMutability());
            }
        }
    }
}
Also used : SingularAttributeSourceBasic(org.hibernate.boot.model.source.spi.SingularAttributeSourceBasic) AssertionFailure(org.hibernate.AssertionFailure) 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) Table(org.hibernate.mapping.Table) DenormalizedTable(org.hibernate.mapping.DenormalizedTable) SingularAttributeSourceAny(org.hibernate.boot.model.source.spi.SingularAttributeSourceAny) Join(org.hibernate.mapping.Join) SingularAttributeSourceManyToOne(org.hibernate.boot.model.source.spi.SingularAttributeSourceManyToOne) AttributeContainer(org.hibernate.mapping.AttributeContainer) SecondaryTableSource(org.hibernate.boot.model.source.spi.SecondaryTableSource) 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) OneToOne(org.hibernate.mapping.OneToOne) SingularAttributeSourceOneToOne(org.hibernate.boot.model.source.spi.SingularAttributeSourceOneToOne) Identifier(org.hibernate.boot.model.naming.Identifier) EntityTableXref(org.hibernate.boot.spi.InFlightMetadataCollector.EntityTableXref) Component(org.hibernate.mapping.Component) Property(org.hibernate.mapping.Property) SyntheticProperty(org.hibernate.mapping.SyntheticProperty)

Example 2 with Any

use of org.hibernate.mapping.Any 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.getMetadataCollector(), 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 3 with Any

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

the class CollectionBinder method bindManyToManySecondPass.

protected void bindManyToManySecondPass(Collection collValue, Map persistentClasses, Ejb3JoinColumn[] joinColumns, Ejb3JoinColumn[] inverseJoinColumns, Ejb3Column[] elementColumns, boolean isEmbedded, XClass collType, boolean ignoreNotFound, boolean unique, boolean cascadeDeleteEnabled, TableBinder associationTableBinder, XProperty property, PropertyHolder parentPropertyHolder, MetadataBuildingContext buildingContext) throws MappingException {
    if (property == null) {
        throw new IllegalArgumentException("null was passed for argument property");
    }
    final PersistentClass collectionEntity = (PersistentClass) persistentClasses.get(collType.getName());
    final String hqlOrderBy = extractHqlOrderBy(jpaOrderBy);
    boolean isCollectionOfEntities = collectionEntity != null;
    ManyToAny anyAnn = property.getAnnotation(ManyToAny.class);
    if (LOG.isDebugEnabled()) {
        String path = collValue.getOwnerEntityName() + "." + joinColumns[0].getPropertyName();
        if (isCollectionOfEntities && unique) {
            LOG.debugf("Binding a OneToMany: %s through an association table", path);
        } else if (isCollectionOfEntities) {
            LOG.debugf("Binding as ManyToMany: %s", path);
        } else if (anyAnn != null) {
            LOG.debugf("Binding a ManyToAny: %s", path);
        } else {
            LOG.debugf("Binding a collection of element: %s", path);
        }
    }
    //check for user error
    if (!isCollectionOfEntities) {
        if (property.isAnnotationPresent(ManyToMany.class) || property.isAnnotationPresent(OneToMany.class)) {
            String path = collValue.getOwnerEntityName() + "." + joinColumns[0].getPropertyName();
            throw new AnnotationException("Use of @OneToMany or @ManyToMany targeting an unmapped class: " + path + "[" + collType + "]");
        } else if (anyAnn != null) {
            if (parentPropertyHolder.getJoinTable(property) == null) {
                String path = collValue.getOwnerEntityName() + "." + joinColumns[0].getPropertyName();
                throw new AnnotationException("@JoinTable is mandatory when @ManyToAny is used: " + path);
            }
        } else {
            JoinTable joinTableAnn = parentPropertyHolder.getJoinTable(property);
            if (joinTableAnn != null && joinTableAnn.inverseJoinColumns().length > 0) {
                String path = collValue.getOwnerEntityName() + "." + joinColumns[0].getPropertyName();
                throw new AnnotationException("Use of @JoinTable.inverseJoinColumns targeting an unmapped class: " + path + "[" + collType + "]");
            }
        }
    }
    boolean mappedBy = !BinderHelper.isEmptyAnnotationValue(joinColumns[0].getMappedBy());
    if (mappedBy) {
        if (!isCollectionOfEntities) {
            StringBuilder error = new StringBuilder(80).append("Collection of elements must not have mappedBy or association reference an unmapped entity: ").append(collValue.getOwnerEntityName()).append(".").append(joinColumns[0].getPropertyName());
            throw new AnnotationException(error.toString());
        }
        Property otherSideProperty;
        try {
            otherSideProperty = collectionEntity.getRecursiveProperty(joinColumns[0].getMappedBy());
        } catch (MappingException e) {
            throw new AnnotationException("mappedBy reference an unknown target entity property: " + collType + "." + joinColumns[0].getMappedBy() + " in " + collValue.getOwnerEntityName() + "." + joinColumns[0].getPropertyName());
        }
        Table table;
        if (otherSideProperty.getValue() instanceof Collection) {
            //this is a collection on the other side
            table = ((Collection) otherSideProperty.getValue()).getCollectionTable();
        } else {
            //This is a ToOne with a @JoinTable or a regular property
            table = otherSideProperty.getValue().getTable();
        }
        collValue.setCollectionTable(table);
        String entityName = collectionEntity.getEntityName();
        for (Ejb3JoinColumn column : joinColumns) {
            //column.setDefaultColumnHeader( joinColumns[0].getMappedBy() ); //seems not to be used, make sense
            column.setManyToManyOwnerSideEntityName(entityName);
        }
    } else {
        //FIXME NamingStrategy
        for (Ejb3JoinColumn column : joinColumns) {
            String mappedByProperty = buildingContext.getMetadataCollector().getFromMappedBy(collValue.getOwnerEntityName(), column.getPropertyName());
            Table ownerTable = collValue.getOwner().getTable();
            column.setMappedBy(collValue.getOwner().getEntityName(), collValue.getOwner().getJpaEntityName(), buildingContext.getMetadataCollector().getLogicalTableName(ownerTable), mappedByProperty);
        //				String header = ( mappedByProperty == null ) ? mappings.getLogicalTableName( ownerTable ) : mappedByProperty;
        //				column.setDefaultColumnHeader( header );
        }
        if (StringHelper.isEmpty(associationTableBinder.getName())) {
            //default value
            associationTableBinder.setDefaultName(collValue.getOwner().getClassName(), collValue.getOwner().getEntityName(), collValue.getOwner().getJpaEntityName(), buildingContext.getMetadataCollector().getLogicalTableName(collValue.getOwner().getTable()), collectionEntity != null ? collectionEntity.getClassName() : null, collectionEntity != null ? collectionEntity.getEntityName() : null, collectionEntity != null ? collectionEntity.getJpaEntityName() : null, collectionEntity != null ? buildingContext.getMetadataCollector().getLogicalTableName(collectionEntity.getTable()) : null, joinColumns[0].getPropertyName());
        }
        associationTableBinder.setJPA2ElementCollection(!isCollectionOfEntities && property.isAnnotationPresent(ElementCollection.class));
        collValue.setCollectionTable(associationTableBinder.bind());
    }
    bindFilters(isCollectionOfEntities);
    bindCollectionSecondPass(collValue, collectionEntity, joinColumns, cascadeDeleteEnabled, property, propertyHolder, buildingContext);
    ManyToOne element = null;
    if (isCollectionOfEntities) {
        element = new ManyToOne(buildingContext.getMetadataCollector(), collValue.getCollectionTable());
        collValue.setElement(element);
        element.setReferencedEntityName(collType.getName());
        //element.setFetchMode( fetchMode );
        //element.setLazy( fetchMode != FetchMode.JOIN );
        //make the second join non lazy
        element.setFetchMode(FetchMode.JOIN);
        element.setLazy(false);
        element.setIgnoreNotFound(ignoreNotFound);
        // as per 11.1.38 of JPA 2.0 spec, default to primary key if no column is specified by @OrderBy.
        if (hqlOrderBy != null) {
            collValue.setManyToManyOrdering(buildOrderByClauseFromHql(hqlOrderBy, collectionEntity, collValue.getRole()));
        }
        final ForeignKey fk = property.getAnnotation(ForeignKey.class);
        if (fk != null && !BinderHelper.isEmptyAnnotationValue(fk.name())) {
            element.setForeignKeyName(fk.name());
        } else {
            final JoinTable joinTableAnn = property.getAnnotation(JoinTable.class);
            if (joinTableAnn != null) {
                String foreignKeyName = joinTableAnn.inverseForeignKey().name();
                String foreignKeyDefinition = joinTableAnn.inverseForeignKey().foreignKeyDefinition();
                ConstraintMode foreignKeyValue = joinTableAnn.inverseForeignKey().value();
                if (joinTableAnn.inverseJoinColumns().length != 0) {
                    final JoinColumn joinColumnAnn = joinTableAnn.inverseJoinColumns()[0];
                    if ("".equals(foreignKeyName)) {
                        foreignKeyName = joinColumnAnn.foreignKey().name();
                        foreignKeyDefinition = joinColumnAnn.foreignKey().foreignKeyDefinition();
                    }
                    if (foreignKeyValue != ConstraintMode.NO_CONSTRAINT) {
                        foreignKeyValue = joinColumnAnn.foreignKey().value();
                    }
                }
                if (joinTableAnn.inverseForeignKey().value() == ConstraintMode.NO_CONSTRAINT) {
                    element.setForeignKeyName("none");
                } else {
                    element.setForeignKeyName(StringHelper.nullIfEmpty(foreignKeyName));
                    element.setForeignKeyDefinition(StringHelper.nullIfEmpty(foreignKeyDefinition));
                }
            }
        }
    } else if (anyAnn != null) {
        //@ManyToAny
        //Make sure that collTyp is never used during the @ManyToAny branch: it will be set to void.class
        PropertyData inferredData = new PropertyInferredData(null, property, "unsupported", buildingContext.getBuildingOptions().getReflectionManager());
        //override the table
        for (Ejb3Column column : inverseJoinColumns) {
            column.setTable(collValue.getCollectionTable());
        }
        Any any = BinderHelper.buildAnyValue(anyAnn.metaDef(), inverseJoinColumns, anyAnn.metaColumn(), inferredData, cascadeDeleteEnabled, Nullability.NO_CONSTRAINT, propertyHolder, new EntityBinder(), true, buildingContext);
        collValue.setElement(any);
    } else {
        XClass elementClass;
        AnnotatedClassType classType;
        CollectionPropertyHolder holder = null;
        if (BinderHelper.PRIMITIVE_NAMES.contains(collType.getName())) {
            classType = AnnotatedClassType.NONE;
            elementClass = null;
            holder = PropertyHolderBuilder.buildPropertyHolder(collValue, collValue.getRole(), null, property, parentPropertyHolder, buildingContext);
        } else {
            elementClass = collType;
            classType = buildingContext.getMetadataCollector().getClassType(elementClass);
            holder = PropertyHolderBuilder.buildPropertyHolder(collValue, collValue.getRole(), elementClass, property, parentPropertyHolder, buildingContext);
            // 'parentPropertyHolder' is the PropertyHolder for the owner of the collection
            // 'holder' is the CollectionPropertyHolder.
            // 'property' is the collection XProperty
            parentPropertyHolder.startingProperty(property);
            //force in case of attribute override
            boolean attributeOverride = property.isAnnotationPresent(AttributeOverride.class) || property.isAnnotationPresent(AttributeOverrides.class);
            // todo : force in the case of Convert annotation(s) with embedded paths (beyond key/value prefixes)?
            if (isEmbedded || attributeOverride) {
                classType = AnnotatedClassType.EMBEDDABLE;
            }
        }
        if (AnnotatedClassType.EMBEDDABLE.equals(classType)) {
            holder.prepare(property);
            EntityBinder entityBinder = new EntityBinder();
            PersistentClass owner = collValue.getOwner();
            boolean isPropertyAnnotated;
            //String accessType = access != null ? access.value() : null;
            if (owner.getIdentifierProperty() != null) {
                isPropertyAnnotated = owner.getIdentifierProperty().getPropertyAccessorName().equals("property");
            } else if (owner.getIdentifierMapper() != null && owner.getIdentifierMapper().getPropertySpan() > 0) {
                Property prop = (Property) owner.getIdentifierMapper().getPropertyIterator().next();
                isPropertyAnnotated = prop.getPropertyAccessorName().equals("property");
            } else {
                throw new AssertionFailure("Unable to guess collection property accessor name");
            }
            PropertyData inferredData;
            if (isMap()) {
                //"value" is the JPA 2 prefix for map values (used to be "element")
                if (isHibernateExtensionMapping()) {
                    inferredData = new PropertyPreloadedData(AccessType.PROPERTY, "element", elementClass);
                } else {
                    inferredData = new PropertyPreloadedData(AccessType.PROPERTY, "value", elementClass);
                }
            } else {
                if (isHibernateExtensionMapping()) {
                    inferredData = new PropertyPreloadedData(AccessType.PROPERTY, "element", elementClass);
                } else {
                    //"collection&&element" is not a valid property name => placeholder
                    inferredData = new PropertyPreloadedData(AccessType.PROPERTY, "collection&&element", elementClass);
                }
            }
            //TODO be smart with isNullable
            boolean isNullable = true;
            Component component = AnnotationBinder.fillComponent(holder, inferredData, isPropertyAnnotated ? AccessType.PROPERTY : AccessType.FIELD, isNullable, entityBinder, false, false, true, buildingContext, inheritanceStatePerClass);
            collValue.setElement(component);
            if (StringHelper.isNotEmpty(hqlOrderBy)) {
                String path = collValue.getOwnerEntityName() + "." + joinColumns[0].getPropertyName();
                String orderBy = adjustUserSuppliedValueCollectionOrderingFragment(hqlOrderBy);
                if (orderBy != null) {
                    collValue.setOrderBy(orderBy);
                }
            }
        } else {
            holder.prepare(property);
            SimpleValueBinder elementBinder = new SimpleValueBinder();
            elementBinder.setBuildingContext(buildingContext);
            elementBinder.setReturnedClassName(collType.getName());
            if (elementColumns == null || elementColumns.length == 0) {
                elementColumns = new Ejb3Column[1];
                Ejb3Column column = new Ejb3Column();
                column.setImplicit(false);
                //not following the spec but more clean
                column.setNullable(true);
                column.setLength(Ejb3Column.DEFAULT_COLUMN_LENGTH);
                column.setLogicalColumnName(Collection.DEFAULT_ELEMENT_COLUMN_NAME);
                //TODO create an EMPTY_JOINS collection
                column.setJoins(new HashMap<String, Join>());
                column.setBuildingContext(buildingContext);
                column.bind();
                elementColumns[0] = column;
            }
            //override the table
            for (Ejb3Column column : elementColumns) {
                column.setTable(collValue.getCollectionTable());
            }
            elementBinder.setColumns(elementColumns);
            elementBinder.setType(property, elementClass, collValue.getOwnerEntityName(), holder.resolveElementAttributeConverterDescriptor(property, elementClass));
            elementBinder.setPersistentClassName(propertyHolder.getEntityName());
            elementBinder.setAccessType(accessType);
            collValue.setElement(elementBinder.make());
            String orderBy = adjustUserSuppliedValueCollectionOrderingFragment(hqlOrderBy);
            if (orderBy != null) {
                collValue.setOrderBy(orderBy);
            }
        }
    }
    checkFilterConditions(collValue);
    //FIXME: do optional = false
    if (isCollectionOfEntities) {
        bindManytoManyInverseFk(collectionEntity, inverseJoinColumns, element, unique, buildingContext);
    }
}
Also used : PropertyData(org.hibernate.cfg.PropertyData) HashMap(java.util.HashMap) PropertyInferredData(org.hibernate.cfg.PropertyInferredData) PropertyPreloadedData(org.hibernate.cfg.PropertyPreloadedData) Any(org.hibernate.mapping.Any) ManyToAny(org.hibernate.annotations.ManyToAny) XClass(org.hibernate.annotations.common.reflection.XClass) ManyToOne(org.hibernate.mapping.ManyToOne) MappingException(org.hibernate.MappingException) ManyToAny(org.hibernate.annotations.ManyToAny) JoinColumn(javax.persistence.JoinColumn) Ejb3JoinColumn(org.hibernate.cfg.Ejb3JoinColumn) AnnotationException(org.hibernate.AnnotationException) Ejb3Column(org.hibernate.cfg.Ejb3Column) Component(org.hibernate.mapping.Component) Property(org.hibernate.mapping.Property) XProperty(org.hibernate.annotations.common.reflection.XProperty) PersistentClass(org.hibernate.mapping.PersistentClass) JoinTable(javax.persistence.JoinTable) CollectionTable(javax.persistence.CollectionTable) WhereJoinTable(org.hibernate.annotations.WhereJoinTable) Table(org.hibernate.mapping.Table) FilterJoinTable(org.hibernate.annotations.FilterJoinTable) CollectionPropertyHolder(org.hibernate.cfg.CollectionPropertyHolder) AssertionFailure(org.hibernate.annotations.common.AssertionFailure) ManyToMany(javax.persistence.ManyToMany) ConstraintMode(javax.persistence.ConstraintMode) OneToMany(javax.persistence.OneToMany) ForeignKey(org.hibernate.annotations.ForeignKey) LazyCollection(org.hibernate.annotations.LazyCollection) Collection(org.hibernate.mapping.Collection) ElementCollection(javax.persistence.ElementCollection) Ejb3JoinColumn(org.hibernate.cfg.Ejb3JoinColumn) AnnotatedClassType(org.hibernate.cfg.AnnotatedClassType) JoinTable(javax.persistence.JoinTable) WhereJoinTable(org.hibernate.annotations.WhereJoinTable) FilterJoinTable(org.hibernate.annotations.FilterJoinTable)

Example 4 with Any

use of org.hibernate.mapping.Any 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();
    new Any(metadata, tbl).accept(vv);
    new Array(metadata, rootClass).accept(vv);
    new Bag(metadata, rootClass).accept(vv);
    new Component(metadata, rootClass).accept(vv);
    new DependantValue(metadata, tbl, null).accept(vv);
    new IdentifierBag(metadata, rootClass).accept(vv);
    new List(metadata, rootClass).accept(vv);
    new ManyToOne(metadata, tbl).accept(vv);
    new Map(metadata, rootClass).accept(vv);
    new OneToMany(metadata, rootClass).accept(vv);
    new OneToOne(metadata, tbl, rootClass).accept(vv);
    new PrimitiveArray(metadata, rootClass).accept(vv);
    new Set(metadata, rootClass).accept(vv);
    new SimpleValue(metadata).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) 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 5 with Any

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

the class ModelBinder method bindMapKey.

private void bindMapKey(final MappingDocument mappingDocument, final IndexedPluralAttributeSource pluralAttributeSource, final org.hibernate.mapping.Map collectionBinding) {
    if (pluralAttributeSource.getIndexSource() instanceof PluralAttributeMapKeySourceBasic) {
        final PluralAttributeMapKeySourceBasic mapKeySource = (PluralAttributeMapKeySourceBasic) pluralAttributeSource.getIndexSource();
        final SimpleValue value = new SimpleValue(mappingDocument.getMetadataCollector(), collectionBinding.getCollectionTable());
        bindSimpleValueType(mappingDocument, mapKeySource.getTypeInformation(), value);
        if (!value.isTypeSpecified()) {
            throw new MappingException("map index element must specify a type: " + pluralAttributeSource.getAttributeRole().getFullPath(), mappingDocument.getOrigin());
        }
        relationalObjectBinder.bindColumnsAndFormulas(mappingDocument, mapKeySource.getRelationalValueSources(), value, true, new RelationalObjectBinder.ColumnNamingDelegate() {

            @Override
            public Identifier determineImplicitName(LocalMetadataBuildingContext context) {
                return database.toIdentifier(IndexedCollection.DEFAULT_INDEX_COLUMN_NAME);
            }
        });
        collectionBinding.setIndex(value);
    } else if (pluralAttributeSource.getIndexSource() instanceof PluralAttributeMapKeySourceEmbedded) {
        final PluralAttributeMapKeySourceEmbedded mapKeySource = (PluralAttributeMapKeySourceEmbedded) pluralAttributeSource.getIndexSource();
        final Component componentBinding = new Component(mappingDocument.getMetadataCollector(), collectionBinding);
        bindComponent(mappingDocument, mapKeySource.getEmbeddableSource(), componentBinding, null, pluralAttributeSource.getName(), mapKeySource.getXmlNodeName(), false);
        collectionBinding.setIndex(componentBinding);
    } else if (pluralAttributeSource.getIndexSource() instanceof PluralAttributeMapKeyManyToManySource) {
        final PluralAttributeMapKeyManyToManySource mapKeySource = (PluralAttributeMapKeyManyToManySource) pluralAttributeSource.getIndexSource();
        final ManyToOne mapKeyBinding = new ManyToOne(mappingDocument.getMetadataCollector(), collectionBinding.getCollectionTable());
        mapKeyBinding.setReferencedEntityName(mapKeySource.getReferencedEntityName());
        relationalObjectBinder.bindColumnsAndFormulas(mappingDocument, mapKeySource.getRelationalValueSources(), mapKeyBinding, true, new RelationalObjectBinder.ColumnNamingDelegate() {

            @Override
            public Identifier determineImplicitName(final LocalMetadataBuildingContext context) {
                return implicitNamingStrategy.determineMapKeyColumnName(new ImplicitMapKeyColumnNameSource() {

                    @Override
                    public AttributePath getPluralAttributePath() {
                        return pluralAttributeSource.getAttributePath();
                    }

                    @Override
                    public MetadataBuildingContext getBuildingContext() {
                        return context;
                    }
                });
            }
        });
        collectionBinding.setIndex(mapKeyBinding);
    } else if (pluralAttributeSource.getIndexSource() instanceof PluralAttributeMapKeyManyToAnySource) {
        final PluralAttributeMapKeyManyToAnySource mapKeySource = (PluralAttributeMapKeyManyToAnySource) pluralAttributeSource.getIndexSource();
        final Any mapKeyBinding = new Any(mappingDocument.getMetadataCollector(), collectionBinding.getCollectionTable());
        bindAny(mappingDocument, mapKeySource, mapKeyBinding, pluralAttributeSource.getAttributeRole().append("key"), pluralAttributeSource.getAttributePath().append("key"));
        collectionBinding.setIndex(mapKeyBinding);
    }
}
Also used : PluralAttributeMapKeyManyToAnySource(org.hibernate.boot.model.source.spi.PluralAttributeMapKeyManyToAnySource) PluralAttributeElementSourceManyToAny(org.hibernate.boot.model.source.spi.PluralAttributeElementSourceManyToAny) Any(org.hibernate.mapping.Any) SingularAttributeSourceAny(org.hibernate.boot.model.source.spi.SingularAttributeSourceAny) SingularAttributeSourceManyToOne(org.hibernate.boot.model.source.spi.SingularAttributeSourceManyToOne) ManyToOne(org.hibernate.mapping.ManyToOne) SimpleValue(org.hibernate.mapping.SimpleValue) MappingException(org.hibernate.boot.MappingException) Identifier(org.hibernate.boot.model.naming.Identifier) PluralAttributeMapKeySourceEmbedded(org.hibernate.boot.model.source.spi.PluralAttributeMapKeySourceEmbedded) PluralAttributeMapKeyManyToManySource(org.hibernate.boot.model.source.spi.PluralAttributeMapKeyManyToManySource) LocalMetadataBuildingContext(org.hibernate.boot.model.source.spi.LocalMetadataBuildingContext) Component(org.hibernate.mapping.Component) ImplicitMapKeyColumnNameSource(org.hibernate.boot.model.naming.ImplicitMapKeyColumnNameSource) PluralAttributeMapKeySourceBasic(org.hibernate.boot.model.source.spi.PluralAttributeMapKeySourceBasic)

Aggregations

Any (org.hibernate.mapping.Any)7 Component (org.hibernate.mapping.Component)5 ManyToOne (org.hibernate.mapping.ManyToOne)5 Property (org.hibernate.mapping.Property)4 SimpleValue (org.hibernate.mapping.SimpleValue)4 AssertionFailure (org.hibernate.AssertionFailure)3 PluralAttributeElementSourceManyToAny (org.hibernate.boot.model.source.spi.PluralAttributeElementSourceManyToAny)3 SingularAttributeSourceAny (org.hibernate.boot.model.source.spi.SingularAttributeSourceAny)3 SingularAttributeSourceManyToOne (org.hibernate.boot.model.source.spi.SingularAttributeSourceManyToOne)3 OneToOne (org.hibernate.mapping.OneToOne)3 Table (org.hibernate.mapping.Table)3 HashMap (java.util.HashMap)2 AnnotationException (org.hibernate.AnnotationException)2 MappingException (org.hibernate.MappingException)2 ManyToAny (org.hibernate.annotations.ManyToAny)2 XProperty (org.hibernate.annotations.common.reflection.XProperty)2 Identifier (org.hibernate.boot.model.naming.Identifier)2 AttributeSource (org.hibernate.boot.model.source.spi.AttributeSource)2 PluralAttributeSource (org.hibernate.boot.model.source.spi.PluralAttributeSource)2 SingularAttributeSource (org.hibernate.boot.model.source.spi.SingularAttributeSource)2