Search in sources :

Example 1 with AssertionFailure

use of org.hibernate.annotations.common.AssertionFailure in project hibernate-orm by hibernate.

the class CollectionBinder method defineFetchingStrategy.

private void defineFetchingStrategy() {
    LazyCollection lazy = property.getAnnotation(LazyCollection.class);
    Fetch fetch = property.getAnnotation(Fetch.class);
    OneToMany oneToMany = property.getAnnotation(OneToMany.class);
    ManyToMany manyToMany = property.getAnnotation(ManyToMany.class);
    //jpa 2
    ElementCollection elementCollection = property.getAnnotation(ElementCollection.class);
    ManyToAny manyToAny = property.getAnnotation(ManyToAny.class);
    FetchType fetchType;
    if (oneToMany != null) {
        fetchType = oneToMany.fetch();
    } else if (manyToMany != null) {
        fetchType = manyToMany.fetch();
    } else if (elementCollection != null) {
        fetchType = elementCollection.fetch();
    } else if (manyToAny != null) {
        fetchType = FetchType.LAZY;
    } else {
        throw new AssertionFailure("Define fetch strategy on a property not annotated with @ManyToOne nor @OneToMany nor @CollectionOfElements");
    }
    if (lazy != null) {
        collection.setLazy(!(lazy.value() == LazyCollectionOption.FALSE));
        collection.setExtraLazy(lazy.value() == LazyCollectionOption.EXTRA);
    } else {
        collection.setLazy(fetchType == FetchType.LAZY);
        collection.setExtraLazy(false);
    }
    if (fetch != null) {
        if (fetch.value() == org.hibernate.annotations.FetchMode.JOIN) {
            collection.setFetchMode(FetchMode.JOIN);
            collection.setLazy(false);
        } else if (fetch.value() == org.hibernate.annotations.FetchMode.SELECT) {
            collection.setFetchMode(FetchMode.SELECT);
        } else if (fetch.value() == org.hibernate.annotations.FetchMode.SUBSELECT) {
            collection.setFetchMode(FetchMode.SELECT);
            collection.setSubselectLoadable(true);
            collection.getOwner().setSubselectLoadableCollections(true);
        } else {
            throw new AssertionFailure("Unknown FetchMode: " + fetch.value());
        }
    } else {
        collection.setFetchMode(AnnotationBinder.getFetchMode(fetchType));
    }
}
Also used : Fetch(org.hibernate.annotations.Fetch) ManyToAny(org.hibernate.annotations.ManyToAny) AssertionFailure(org.hibernate.annotations.common.AssertionFailure) LazyCollection(org.hibernate.annotations.LazyCollection) FetchType(javax.persistence.FetchType) ManyToMany(javax.persistence.ManyToMany) ElementCollection(javax.persistence.ElementCollection) OneToMany(javax.persistence.OneToMany)

Example 2 with AssertionFailure

use of org.hibernate.annotations.common.AssertionFailure in project hibernate-orm by hibernate.

the class CollectionBinder method bindOneToManySecondPass.

protected void bindOneToManySecondPass(Collection collection, Map persistentClasses, Ejb3JoinColumn[] fkJoinColumns, XClass collectionType, boolean cascadeDeleteEnabled, boolean ignoreNotFound, MetadataBuildingContext buildingContext, Map<XClass, InheritanceState> inheritanceStatePerClass) {
    final boolean debugEnabled = LOG.isDebugEnabled();
    if (debugEnabled) {
        LOG.debugf("Binding a OneToMany: %s.%s through a foreign key", propertyHolder.getEntityName(), propertyName);
    }
    if (buildingContext == null) {
        throw new AssertionFailure("CollectionSecondPass for oneToMany should not be called with null mappings");
    }
    org.hibernate.mapping.OneToMany oneToMany = new org.hibernate.mapping.OneToMany(buildingContext.getMetadataCollector(), collection.getOwner());
    collection.setElement(oneToMany);
    oneToMany.setReferencedEntityName(collectionType.getName());
    oneToMany.setIgnoreNotFound(ignoreNotFound);
    String assocClass = oneToMany.getReferencedEntityName();
    PersistentClass associatedClass = (PersistentClass) persistentClasses.get(assocClass);
    if (jpaOrderBy != null) {
        final String orderByFragment = buildOrderByClauseFromHql(jpaOrderBy.value(), associatedClass, collection.getRole());
        if (StringHelper.isNotEmpty(orderByFragment)) {
            collection.setOrderBy(orderByFragment);
        }
    }
    Map<String, Join> joins = buildingContext.getMetadataCollector().getJoins(assocClass);
    if (associatedClass == null) {
        throw new MappingException(String.format("Association [%s] for entity [%s] references unmapped class [%s]", propertyName, propertyHolder.getClassName(), assocClass));
    }
    oneToMany.setAssociatedClass(associatedClass);
    for (Ejb3JoinColumn column : fkJoinColumns) {
        column.setPersistentClass(associatedClass, joins, inheritanceStatePerClass);
        column.setJoins(joins);
        collection.setCollectionTable(column.getTable());
    }
    if (debugEnabled) {
        LOG.debugf("Mapping collection: %s -> %s", collection.getRole(), collection.getCollectionTable().getName());
    }
    bindFilters(false);
    bindCollectionSecondPass(collection, null, fkJoinColumns, cascadeDeleteEnabled, property, propertyHolder, buildingContext);
    if (!collection.isInverse() && !collection.getKey().isNullable()) {
        // for non-inverse one-to-many, with a not-null fk, add a backref!
        String entityName = oneToMany.getReferencedEntityName();
        PersistentClass referenced = buildingContext.getMetadataCollector().getEntityBinding(entityName);
        Backref prop = new Backref();
        prop.setName('_' + fkJoinColumns[0].getPropertyName() + '_' + fkJoinColumns[0].getLogicalColumnName() + "Backref");
        prop.setUpdateable(false);
        prop.setSelectable(false);
        prop.setCollectionRole(collection.getRole());
        prop.setEntityName(collection.getOwner().getEntityName());
        prop.setValue(collection.getKey());
        referenced.addProperty(prop);
    }
}
Also used : AssertionFailure(org.hibernate.annotations.common.AssertionFailure) Join(org.hibernate.mapping.Join) Backref(org.hibernate.mapping.Backref) OneToMany(javax.persistence.OneToMany) MappingException(org.hibernate.MappingException) Ejb3JoinColumn(org.hibernate.cfg.Ejb3JoinColumn) PersistentClass(org.hibernate.mapping.PersistentClass)

Example 3 with AssertionFailure

use of org.hibernate.annotations.common.AssertionFailure 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 AssertionFailure

use of org.hibernate.annotations.common.AssertionFailure in project hibernate-orm by hibernate.

the class AbstractManagedType method getBuilder.

public Builder<X> getBuilder() {
    if (locked) {
        throw new IllegalStateException("Type has been locked");
    }
    return new Builder<X>() {

        @Override
        @SuppressWarnings("unchecked")
        public void addAttribute(Attribute<X, ?> attribute) {
            declaredAttributes.put(attribute.getName(), attribute);
            final Bindable.BindableType bindableType = ((Bindable) attribute).getBindableType();
            switch(bindableType) {
                case SINGULAR_ATTRIBUTE:
                    {
                        declaredSingularAttributes.put(attribute.getName(), (SingularAttribute<X, ?>) attribute);
                        break;
                    }
                case PLURAL_ATTRIBUTE:
                    {
                        declaredPluralAttributes.put(attribute.getName(), (PluralAttribute<X, ?, ?>) attribute);
                        break;
                    }
                default:
                    {
                        throw new AssertionFailure("unknown bindable type: " + bindableType);
                    }
            }
        }
    };
}
Also used : SingularAttribute(javax.persistence.metamodel.SingularAttribute) AssertionFailure(org.hibernate.annotations.common.AssertionFailure) SingularAttribute(javax.persistence.metamodel.SingularAttribute) Attribute(javax.persistence.metamodel.Attribute) PluralAttribute(javax.persistence.metamodel.PluralAttribute) SetAttribute(javax.persistence.metamodel.SetAttribute) CollectionAttribute(javax.persistence.metamodel.CollectionAttribute) MapAttribute(javax.persistence.metamodel.MapAttribute) ListAttribute(javax.persistence.metamodel.ListAttribute) PluralAttribute(javax.persistence.metamodel.PluralAttribute) Bindable(javax.persistence.metamodel.Bindable)

Example 5 with AssertionFailure

use of org.hibernate.annotations.common.AssertionFailure in project hibernate-orm by hibernate.

the class MetadataContext method registerAttribute.

private <X> void registerAttribute(Class metamodelClass, Attribute<X, ?> attribute) {
    final String name = attribute.getName();
    try {
        // there is a shortcoming in the existing Hibernate code in terms of the way MappedSuperclass
        // support was bolted on which comes to bear right here when the attribute is an embeddable type
        // defined on a MappedSuperclass.  We do not have the correct information to determine the
        // appropriate attribute declarer in such cases and so the incoming metamodelClass most likely
        // does not represent the declarer in such cases.
        //
        // As a result, in the case of embeddable classes we simply use getField rather than get
        // getDeclaredField
        final boolean allowNonDeclaredFieldReference = attribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.EMBEDDED || attribute.getDeclaringType().getPersistenceType() == Type.PersistenceType.EMBEDDABLE;
        final Field field = allowNonDeclaredFieldReference ? metamodelClass.getField(name) : metamodelClass.getDeclaredField(name);
        try {
            // should be public anyway, but to be sure...
            field.setAccessible(true);
            field.set(null, attribute);
        } catch (IllegalAccessException e) {
            // todo : exception type?
            throw new AssertionFailure("Unable to inject static metamodel attribute : " + metamodelClass.getName() + '#' + name, e);
        } catch (IllegalArgumentException e) {
            // most likely a mismatch in the type we are injecting and the defined field; this represents a
            // mismatch in how the annotation processor interpretted the attribute and how our metamodel
            // and/or annotation binder did.
            //              This is particularly the case as arrays are nto handled propery by the StaticMetamodel generator
            //				throw new AssertionFailure(
            //						"Illegal argument on static metamodel field injection : " + metamodelClass.getName() + '#' + name
            //								+ "; expected type :  " + attribute.getClass().getName()
            //								+ "; encountered type : " + field.getType().getName()
            //				);
            LOG.illegalArgumentOnStaticMetamodelFieldInjection(metamodelClass.getName(), name, attribute.getClass().getName(), field.getType().getName());
        }
    } catch (NoSuchFieldException e) {
        LOG.unableToLocateStaticMetamodelField(metamodelClass.getName(), name);
    //			throw new AssertionFailure(
    //					"Unable to locate static metamodel field : " + metamodelClass.getName() + '#' + name
    //			);
    }
}
Also used : Field(java.lang.reflect.Field) AssertionFailure(org.hibernate.annotations.common.AssertionFailure)

Aggregations

AssertionFailure (org.hibernate.annotations.common.AssertionFailure)7 ElementCollection (javax.persistence.ElementCollection)3 OneToMany (javax.persistence.OneToMany)3 PersistentClass (org.hibernate.mapping.PersistentClass)3 ManyToMany (javax.persistence.ManyToMany)2 Attribute (javax.persistence.metamodel.Attribute)2 SingularAttribute (javax.persistence.metamodel.SingularAttribute)2 AnnotationException (org.hibernate.AnnotationException)2 MappingException (org.hibernate.MappingException)2 LazyCollection (org.hibernate.annotations.LazyCollection)2 ManyToAny (org.hibernate.annotations.ManyToAny)2 XClass (org.hibernate.annotations.common.reflection.XClass)2 XProperty (org.hibernate.annotations.common.reflection.XProperty)2 Ejb3JoinColumn (org.hibernate.cfg.Ejb3JoinColumn)2 Property (org.hibernate.mapping.Property)2 Field (java.lang.reflect.Field)1 HashMap (java.util.HashMap)1 Iterator (java.util.Iterator)1 CollectionTable (javax.persistence.CollectionTable)1 ConstraintMode (javax.persistence.ConstraintMode)1