Search in sources :

Example 76 with AnnotationException

use of org.hibernate.AnnotationException in project hibernate-orm by hibernate.

the class CollectionBinder method bind.

public void bind() {
    this.collection = createCollection(propertyHolder.getPersistentClass());
    String role = StringHelper.qualify(propertyHolder.getPath(), propertyName);
    LOG.debugf("Collection role: %s", role);
    collection.setRole(role);
    collection.setMappedByProperty(mappedBy);
    if (property.isAnnotationPresent(MapKeyColumn.class) && mapKeyPropertyName != null) {
        throw new AnnotationException("Cannot mix @javax.persistence.MapKey and @MapKeyColumn or @org.hibernate.annotations.MapKey " + "on the same collection: " + StringHelper.qualify(propertyHolder.getPath(), propertyName));
    }
    // set explicit type information
    if (explicitType != null) {
        final TypeDefinition typeDef = buildingContext.getMetadataCollector().getTypeDefinition(explicitType);
        if (typeDef == null) {
            collection.setTypeName(explicitType);
            collection.setTypeParameters(explicitTypeParameters);
        } else {
            collection.setTypeName(typeDef.getTypeImplementorClass().getName());
            collection.setTypeParameters(typeDef.getParameters());
        }
    }
    // set laziness
    defineFetchingStrategy();
    collection.setBatchSize(batchSize);
    collection.setMutable(!property.isAnnotationPresent(Immutable.class));
    // work on association
    boolean isMappedBy = !BinderHelper.isEmptyAnnotationValue(mappedBy);
    final OptimisticLock lockAnn = property.getAnnotation(OptimisticLock.class);
    final boolean includeInOptimisticLockChecks = (lockAnn != null) ? !lockAnn.excluded() : !isMappedBy;
    collection.setOptimisticLocked(includeInOptimisticLockChecks);
    Persister persisterAnn = property.getAnnotation(Persister.class);
    if (persisterAnn != null) {
        collection.setCollectionPersisterClass(persisterAnn.impl());
    }
    applySortingAndOrdering(collection);
    // set cache
    if (StringHelper.isNotEmpty(cacheConcurrencyStrategy)) {
        collection.setCacheConcurrencyStrategy(cacheConcurrencyStrategy);
        collection.setCacheRegionName(cacheRegionName);
    }
    // SQL overriding
    SQLInsert sqlInsert = property.getAnnotation(SQLInsert.class);
    SQLUpdate sqlUpdate = property.getAnnotation(SQLUpdate.class);
    SQLDelete sqlDelete = property.getAnnotation(SQLDelete.class);
    SQLDeleteAll sqlDeleteAll = property.getAnnotation(SQLDeleteAll.class);
    Loader loader = property.getAnnotation(Loader.class);
    if (sqlInsert != null) {
        collection.setCustomSQLInsert(sqlInsert.sql().trim(), sqlInsert.callable(), ExecuteUpdateResultCheckStyle.fromExternalName(sqlInsert.check().toString().toLowerCase(Locale.ROOT)));
    }
    if (sqlUpdate != null) {
        collection.setCustomSQLUpdate(sqlUpdate.sql(), sqlUpdate.callable(), ExecuteUpdateResultCheckStyle.fromExternalName(sqlUpdate.check().toString().toLowerCase(Locale.ROOT)));
    }
    if (sqlDelete != null) {
        collection.setCustomSQLDelete(sqlDelete.sql(), sqlDelete.callable(), ExecuteUpdateResultCheckStyle.fromExternalName(sqlDelete.check().toString().toLowerCase(Locale.ROOT)));
    }
    if (sqlDeleteAll != null) {
        collection.setCustomSQLDeleteAll(sqlDeleteAll.sql(), sqlDeleteAll.callable(), ExecuteUpdateResultCheckStyle.fromExternalName(sqlDeleteAll.check().toString().toLowerCase(Locale.ROOT)));
    }
    if (loader != null) {
        collection.setLoaderName(loader.namedQuery());
    }
    if (isMappedBy && (property.isAnnotationPresent(JoinColumn.class) || property.isAnnotationPresent(JoinColumns.class) || propertyHolder.getJoinTable(property) != null)) {
        String message = "Associations marked as mappedBy must not define database mappings like @JoinTable or @JoinColumn: ";
        message += StringHelper.qualify(propertyHolder.getPath(), propertyName);
        throw new AnnotationException(message);
    }
    if (!isMappedBy && oneToMany && property.isAnnotationPresent(OnDelete.class) && !property.isAnnotationPresent(JoinColumn.class)) {
        String message = "Unidirectional one-to-many associations annotated with @OnDelete must define @JoinColumn: ";
        message += StringHelper.qualify(propertyHolder.getPath(), propertyName);
        throw new AnnotationException(message);
    }
    collection.setInverse(isMappedBy);
    // many to many may need some second pass informations
    if (!oneToMany && isMappedBy) {
        buildingContext.getMetadataCollector().addMappedBy(getCollectionType().getName(), mappedBy, propertyName);
    }
    // TODO reducce tableBinder != null and oneToMany
    XClass collectionType = getCollectionType();
    if (inheritanceStatePerClass == null)
        throw new AssertionFailure("inheritanceStatePerClass not set");
    SecondPass sp = getSecondPass(fkJoinColumns, joinColumns, inverseJoinColumns, elementColumns, mapKeyColumns, mapKeyManyToManyColumns, isEmbedded, property, collectionType, ignoreNotFound, oneToMany, tableBinder, buildingContext);
    if (collectionType.isAnnotationPresent(Embeddable.class) || // JPA 2
    property.isAnnotationPresent(ElementCollection.class)) {
        // do it right away, otherwise @ManyToOne on composite element call addSecondPass
        // and raise a ConcurrentModificationException
        // sp.doSecondPass( CollectionHelper.EMPTY_MAP );
        buildingContext.getMetadataCollector().addSecondPass(sp, !isMappedBy);
    } else {
        buildingContext.getMetadataCollector().addSecondPass(sp, !isMappedBy);
    }
    buildingContext.getMetadataCollector().addCollectionBinding(collection);
    // property building
    PropertyBinder binder = new PropertyBinder();
    binder.setName(propertyName);
    binder.setValue(collection);
    binder.setCascade(cascadeStrategy);
    if (cascadeStrategy != null && cascadeStrategy.contains("delete-orphan")) {
        collection.setOrphanDelete(true);
    }
    binder.setLazy(collection.isLazy());
    final LazyGroup lazyGroupAnnotation = property.getAnnotation(LazyGroup.class);
    if (lazyGroupAnnotation != null) {
        binder.setLazyGroup(lazyGroupAnnotation.value());
    }
    binder.setAccessType(accessType);
    binder.setProperty(property);
    binder.setInsertable(insertable);
    binder.setUpdatable(updatable);
    Property prop = binder.makeProperty();
    // we don't care about the join stuffs because the column is on the association table.
    if (!declaringClassSet)
        throw new AssertionFailure("DeclaringClass is not set in CollectionBinder while binding");
    propertyHolder.addProperty(prop, declaringClass);
}
Also used : AssertionFailure(org.hibernate.annotations.common.AssertionFailure) MapKeyColumn(javax.persistence.MapKeyColumn) Loader(org.hibernate.annotations.Loader) SQLDelete(org.hibernate.annotations.SQLDelete) XClass(org.hibernate.annotations.common.reflection.XClass) TypeDefinition(org.hibernate.boot.model.TypeDefinition) Embeddable(javax.persistence.Embeddable) SecondPass(org.hibernate.cfg.SecondPass) CollectionSecondPass(org.hibernate.cfg.CollectionSecondPass) LazyGroup(org.hibernate.annotations.LazyGroup) AnnotationException(org.hibernate.AnnotationException) SQLInsert(org.hibernate.annotations.SQLInsert) SQLUpdate(org.hibernate.annotations.SQLUpdate) SQLDeleteAll(org.hibernate.annotations.SQLDeleteAll) Persister(org.hibernate.annotations.Persister) ElementCollection(javax.persistence.ElementCollection) OptimisticLock(org.hibernate.annotations.OptimisticLock) Property(org.hibernate.mapping.Property) XProperty(org.hibernate.annotations.common.reflection.XProperty)

Example 77 with AnnotationException

use of org.hibernate.AnnotationException in project hibernate-orm by hibernate.

the class EntityBinder method processComplementaryTableDefinitions.

public void processComplementaryTableDefinitions(org.hibernate.annotations.Table table) {
    // comment and index are processed here
    if (table == null)
        return;
    String appliedTable = table.appliesTo();
    Iterator tables = persistentClass.getTableClosureIterator();
    Table hibTable = null;
    while (tables.hasNext()) {
        Table pcTable = (Table) tables.next();
        if (pcTable.getQuotedName().equals(appliedTable)) {
            // we are in the correct table to find columns
            hibTable = pcTable;
            break;
        }
        hibTable = null;
    }
    if (hibTable == null) {
        // maybe a join/secondary table
        for (Join join : secondaryTables.values()) {
            if (join.getTable().getQuotedName().equals(appliedTable)) {
                hibTable = join.getTable();
                break;
            }
        }
    }
    if (hibTable == null) {
        throw new AnnotationException("@org.hibernate.annotations.Table references an unknown table: " + appliedTable);
    }
    if (!BinderHelper.isEmptyAnnotationValue(table.comment()))
        hibTable.setComment(table.comment());
    TableBinder.addIndexes(hibTable, table.indexes(), context);
}
Also used : JoinTable(javax.persistence.JoinTable) SecondaryTable(javax.persistence.SecondaryTable) Table(org.hibernate.mapping.Table) Iterator(java.util.Iterator) Join(org.hibernate.mapping.Join) AnnotationException(org.hibernate.AnnotationException)

Example 78 with AnnotationException

use of org.hibernate.AnnotationException in project hibernate-orm by hibernate.

the class EntityBinder method applyCaching.

public void applyCaching(XClass clazzToProcess, SharedCacheMode sharedCacheMode, MetadataBuildingContext context) {
    final Cache explicitCacheAnn = clazzToProcess.getAnnotation(Cache.class);
    final Cacheable explicitCacheableAnn = clazzToProcess.getAnnotation(Cacheable.class);
    isCached = false;
    cacheConcurrentStrategy = null;
    cacheRegion = null;
    cacheLazyProperty = true;
    if (persistentClass instanceof RootClass) {
        Cache effectiveCacheAnn = explicitCacheAnn;
        if (explicitCacheAnn != null) {
            // preserve legacy behavior of circumventing SharedCacheMode when Hibernate's @Cache is used.
            isCached = true;
        } else {
            effectiveCacheAnn = buildCacheMock(clazzToProcess.getName(), context);
            switch(sharedCacheMode) {
                case ALL:
                    {
                        // all entities should be cached
                        isCached = true;
                        break;
                    }
                case ENABLE_SELECTIVE:
                    {
                        if (explicitCacheableAnn != null && explicitCacheableAnn.value()) {
                            isCached = true;
                        }
                        break;
                    }
                case DISABLE_SELECTIVE:
                    {
                        if (explicitCacheableAnn == null || explicitCacheableAnn.value()) {
                            isCached = true;
                        }
                        break;
                    }
                default:
                    {
                        // treat both NONE and UNSPECIFIED the same
                        isCached = false;
                        break;
                    }
            }
        }
        cacheConcurrentStrategy = resolveCacheConcurrencyStrategy(effectiveCacheAnn.usage());
        cacheRegion = effectiveCacheAnn.region();
        switch(effectiveCacheAnn.include().toLowerCase(Locale.ROOT)) {
            case "all":
                {
                    cacheLazyProperty = true;
                    break;
                }
            case "non-lazy":
                {
                    cacheLazyProperty = false;
                    break;
                }
            default:
                {
                    throw new AnnotationException("Unknown @Cache.include value [" + effectiveCacheAnn.include() + "] : " + annotatedClass.getName());
                }
        }
    } else {
        if (explicitCacheAnn != null) {
            LOG.cacheOrCacheableAnnotationOnNonRoot(persistentClass.getClassName());
        } else if (explicitCacheableAnn == null && persistentClass.getSuperclass() != null) {
            // we should inherit our super's caching config
            isCached = persistentClass.getSuperclass().isCached();
        } else {
            switch(sharedCacheMode) {
                case ALL:
                    {
                        // all entities should be cached
                        isCached = true;
                        break;
                    }
                case ENABLE_SELECTIVE:
                    {
                        // only entities with @Cacheable(true) should be cached
                        if (explicitCacheableAnn != null && explicitCacheableAnn.value()) {
                            isCached = true;
                        }
                        break;
                    }
                case DISABLE_SELECTIVE:
                    {
                        if (explicitCacheableAnn == null || !explicitCacheableAnn.value()) {
                            isCached = true;
                        }
                        break;
                    }
                default:
                    {
                        // treat both NONE and UNSPECIFIED the same
                        isCached = false;
                        break;
                    }
            }
        }
    }
    naturalIdCacheRegion = null;
    final NaturalIdCache naturalIdCacheAnn = clazzToProcess.getAnnotation(NaturalIdCache.class);
    if (naturalIdCacheAnn != null) {
        if (BinderHelper.isEmptyAnnotationValue(naturalIdCacheAnn.region())) {
            if (explicitCacheAnn != null && StringHelper.isNotEmpty(explicitCacheAnn.region())) {
                naturalIdCacheRegion = explicitCacheAnn.region() + NATURAL_ID_CACHE_SUFFIX;
            } else {
                naturalIdCacheRegion = clazzToProcess.getName() + NATURAL_ID_CACHE_SUFFIX;
            }
        } else {
            naturalIdCacheRegion = naturalIdCacheAnn.region();
        }
    }
}
Also used : RootClass(org.hibernate.mapping.RootClass) Cacheable(javax.persistence.Cacheable) NaturalIdCache(org.hibernate.annotations.NaturalIdCache) AnnotationException(org.hibernate.AnnotationException) NaturalIdCache(org.hibernate.annotations.NaturalIdCache) Cache(org.hibernate.annotations.Cache)

Example 79 with AnnotationException

use of org.hibernate.AnnotationException in project hibernate-orm by hibernate.

the class ColumnsBuilder method extractMetadata.

public ColumnsBuilder extractMetadata() {
    columns = null;
    joinColumns = buildExplicitJoinColumns(property, inferredData);
    if (property.isAnnotationPresent(Column.class) || property.isAnnotationPresent(Formula.class)) {
        Column ann = property.getAnnotation(Column.class);
        Formula formulaAnn = property.getAnnotation(Formula.class);
        columns = Ejb3Column.buildColumnFromAnnotation(new Column[] { ann }, formulaAnn, nullability, propertyHolder, inferredData, entityBinder.getSecondaryTables(), buildingContext);
    } else if (property.isAnnotationPresent(Columns.class)) {
        Columns anns = property.getAnnotation(Columns.class);
        columns = Ejb3Column.buildColumnFromAnnotation(anns.columns(), null, nullability, propertyHolder, inferredData, entityBinder.getSecondaryTables(), buildingContext);
    }
    // set default values if needed
    if (joinColumns == null && (property.isAnnotationPresent(ManyToOne.class) || property.isAnnotationPresent(OneToOne.class))) {
        joinColumns = buildDefaultJoinColumnsForXToOne(property, inferredData);
    } else if (joinColumns == null && (property.isAnnotationPresent(OneToMany.class) || property.isAnnotationPresent(ElementCollection.class))) {
        OneToMany oneToMany = property.getAnnotation(OneToMany.class);
        String mappedBy = oneToMany != null ? oneToMany.mappedBy() : "";
        joinColumns = Ejb3JoinColumn.buildJoinColumns(null, mappedBy, entityBinder.getSecondaryTables(), propertyHolder, inferredData.getPropertyName(), buildingContext);
    } else if (joinColumns == null && property.isAnnotationPresent(org.hibernate.annotations.Any.class)) {
        throw new AnnotationException("@Any requires an explicit @JoinColumn(s): " + BinderHelper.getPath(propertyHolder, inferredData));
    }
    if (columns == null && !property.isAnnotationPresent(ManyToMany.class)) {
        // useful for collection of embedded elements
        columns = Ejb3Column.buildColumnFromAnnotation(null, null, nullability, propertyHolder, inferredData, entityBinder.getSecondaryTables(), buildingContext);
    }
    if (nullability == Nullability.FORCED_NOT_NULL) {
        // force columns to not null
        for (Ejb3Column col : columns) {
            col.forceNotNull();
        }
    }
    return this;
}
Also used : Formula(org.hibernate.annotations.Formula) JoinColumnOrFormula(org.hibernate.annotations.JoinColumnOrFormula) JoinFormula(org.hibernate.annotations.JoinFormula) OneToOne(javax.persistence.OneToOne) JoinColumn(javax.persistence.JoinColumn) Column(javax.persistence.Column) JoinColumns(javax.persistence.JoinColumns) Columns(org.hibernate.annotations.Columns) AnnotationException(org.hibernate.AnnotationException) OneToMany(javax.persistence.OneToMany) ManyToOne(javax.persistence.ManyToOne)

Example 80 with AnnotationException

use of org.hibernate.AnnotationException in project hibernate-orm by hibernate.

the class CopyIdentifierComponentSecondPass method createSimpleProperty.

private Property createSimpleProperty(PersistentClass referencedPersistentClass, boolean isExplicitReference, Map<String, Ejb3JoinColumn> columnByReferencedName, AtomicInteger index, Property referencedProperty) {
    Property property = new Property();
    property.setName(referencedProperty.getName());
    // FIXME set optional?
    // property.setOptional( property.isOptional() );
    property.setPersistentClass(component.getOwner());
    property.setPropertyAccessorName(referencedProperty.getPropertyAccessorName());
    SimpleValue value = new SimpleValue(buildingContext, component.getTable());
    property.setValue(value);
    final SimpleValue referencedValue = (SimpleValue) referencedProperty.getValue();
    value.setTypeName(referencedValue.getTypeName());
    value.setTypeParameters(referencedValue.getTypeParameters());
    final Iterator<Selectable> columns = referencedValue.getColumnIterator();
    if (joinColumns[0].isNameDeferred()) {
        joinColumns[0].copyReferencedStructureAndCreateDefaultJoinColumns(referencedPersistentClass, columns, value);
    } else {
        // FIXME take care of Formula
        while (columns.hasNext()) {
            final Selectable selectable = columns.next();
            if (!Column.class.isInstance(selectable)) {
                log.debug("Encountered formula definition; skipping");
                continue;
            }
            final Column column = (Column) selectable;
            final Ejb3JoinColumn joinColumn;
            String logicalColumnName = null;
            if (isExplicitReference) {
                final String columnName = column.getName();
                logicalColumnName = buildingContext.getMetadataCollector().getLogicalColumnName(referencedPersistentClass.getTable(), columnName);
                // JPA 2 requires referencedColumnNames to be case insensitive
                joinColumn = columnByReferencedName.get(logicalColumnName.toLowerCase(Locale.ROOT));
            } else {
                joinColumn = columnByReferencedName.get("" + index.get());
                index.getAndIncrement();
            }
            if (joinColumn == null && !joinColumns[0].isNameDeferred()) {
                throw new AnnotationException(isExplicitReference ? "Unable to find column reference in the @MapsId mapping: " + logicalColumnName : "Implicit column reference in the @MapsId mapping fails, try to use explicit referenceColumnNames: " + referencedEntityName);
            }
            final String columnName = joinColumn == null || joinColumn.isNameDeferred() ? "tata_" + column.getName() : joinColumn.getName();
            value.addColumn(new Column(columnName));
            if (joinColumn != null) {
                applyComponentColumnSizeValueToJoinColumn(column, joinColumn);
                joinColumn.linkWithValue(value);
            }
            column.setValue(value);
        }
    }
    return property;
}
Also used : Selectable(org.hibernate.mapping.Selectable) Column(org.hibernate.mapping.Column) AnnotationException(org.hibernate.AnnotationException) Property(org.hibernate.mapping.Property) SimpleValue(org.hibernate.mapping.SimpleValue)

Aggregations

AnnotationException (org.hibernate.AnnotationException)85 AnnotationDescriptor (org.hibernate.annotations.common.annotationfactory.AnnotationDescriptor)15 PersistentClass (org.hibernate.mapping.PersistentClass)14 AnnotatedElement (java.lang.reflect.AnnotatedElement)12 Element (org.dom4j.Element)12 XClass (org.hibernate.annotations.common.reflection.XClass)12 HashMap (java.util.HashMap)11 MappingException (org.hibernate.MappingException)11 XProperty (org.hibernate.annotations.common.reflection.XProperty)11 Property (org.hibernate.mapping.Property)11 SimpleValue (org.hibernate.mapping.SimpleValue)11 Test (org.junit.Test)10 AssertionFailure (org.hibernate.AssertionFailure)9 ArrayList (java.util.ArrayList)8 ClassLoadingException (org.hibernate.boot.registry.classloading.spi.ClassLoadingException)8 Column (org.hibernate.mapping.Column)8 IdClass (javax.persistence.IdClass)7 MapKeyClass (javax.persistence.MapKeyClass)7 Component (org.hibernate.mapping.Component)7 Properties (java.util.Properties)6