Search in sources :

Example 81 with AnnotationException

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

the class Ejb3Column method buildColumnFromAnnotation.

public static Ejb3Column[] buildColumnFromAnnotation(javax.persistence.Column[] anns, org.hibernate.annotations.Formula formulaAnn, Nullability nullability, PropertyHolder propertyHolder, PropertyData inferredData, String suffixForDefaultColumnName, Map<String, Join> secondaryTables, MetadataBuildingContext context) {
    Ejb3Column[] columns;
    if (formulaAnn != null) {
        Ejb3Column formulaColumn = new Ejb3Column();
        formulaColumn.setFormula(formulaAnn.value());
        formulaColumn.setImplicit(false);
        formulaColumn.setBuildingContext(context);
        formulaColumn.setPropertyHolder(propertyHolder);
        formulaColumn.bind();
        columns = new Ejb3Column[] { formulaColumn };
    } else {
        javax.persistence.Column[] actualCols = anns;
        javax.persistence.Column[] overriddenCols = propertyHolder.getOverriddenColumn(StringHelper.qualify(propertyHolder.getPath(), inferredData.getPropertyName()));
        if (overriddenCols != null) {
            // check for overridden first
            if (anns != null && overriddenCols.length != anns.length) {
                throw new AnnotationException("AttributeOverride.column() should override all columns for now");
            }
            actualCols = overriddenCols.length == 0 ? null : overriddenCols;
            LOG.debugf("Column(s) overridden for property %s", inferredData.getPropertyName());
        }
        if (actualCols == null) {
            columns = buildImplicitColumn(inferredData, suffixForDefaultColumnName, secondaryTables, propertyHolder, nullability, context);
        } else {
            final int length = actualCols.length;
            columns = new Ejb3Column[length];
            for (int index = 0; index < length; index++) {
                final ObjectNameNormalizer normalizer = context.getObjectNameNormalizer();
                final Database database = context.getMetadataCollector().getDatabase();
                final ImplicitNamingStrategy implicitNamingStrategy = context.getBuildingOptions().getImplicitNamingStrategy();
                final PhysicalNamingStrategy physicalNamingStrategy = context.getBuildingOptions().getPhysicalNamingStrategy();
                javax.persistence.Column col = actualCols[index];
                final String sqlType;
                if (col.columnDefinition().equals("")) {
                    sqlType = null;
                } else {
                    sqlType = normalizer.applyGlobalQuoting(col.columnDefinition());
                }
                final String tableName;
                if (StringHelper.isEmpty(col.table())) {
                    tableName = "";
                } else {
                    tableName = database.getJdbcEnvironment().getIdentifierHelper().toIdentifier(col.table()).render();
                // final Identifier logicalName = database.getJdbcEnvironment()
                // .getIdentifierHelper()
                // .toIdentifier( col.table() );
                // final Identifier physicalName = physicalNamingStrategy.toPhysicalTableName( logicalName );
                // tableName = physicalName.render( database.getDialect() );
                }
                final String columnName;
                if ("".equals(col.name())) {
                    columnName = null;
                } else {
                    // NOTE : this is the logical column name, not the physical!
                    columnName = database.getJdbcEnvironment().getIdentifierHelper().toIdentifier(col.name()).render();
                }
                Ejb3Column column = new Ejb3Column();
                if (length == 1) {
                    applyColumnDefault(column, inferredData);
                }
                column.setImplicit(false);
                column.setSqlType(sqlType);
                column.setLength(col.length());
                column.setPrecision(col.precision());
                column.setScale(col.scale());
                if (StringHelper.isEmpty(columnName) && !StringHelper.isEmpty(suffixForDefaultColumnName)) {
                    column.setLogicalColumnName(inferredData.getPropertyName() + suffixForDefaultColumnName);
                } else {
                    column.setLogicalColumnName(columnName);
                }
                column.setPropertyName(BinderHelper.getRelativePath(propertyHolder, inferredData.getPropertyName()));
                column.setNullable(col.nullable());
                // TODO force to not null if available? This is a (bad) user choice.
                column.setUnique(col.unique());
                column.setInsertable(col.insertable());
                column.setUpdatable(col.updatable());
                column.setExplicitTableName(tableName);
                column.setPropertyHolder(propertyHolder);
                column.setJoins(secondaryTables);
                column.setBuildingContext(context);
                column.extractDataFromPropertyData(inferredData);
                column.bind();
                columns[index] = column;
            }
        }
    }
    return columns;
}
Also used : ImplicitNamingStrategy(org.hibernate.boot.model.naming.ImplicitNamingStrategy) ObjectNameNormalizer(org.hibernate.boot.model.naming.ObjectNameNormalizer) PhysicalNamingStrategy(org.hibernate.boot.model.naming.PhysicalNamingStrategy) Column(org.hibernate.mapping.Column) Database(org.hibernate.boot.model.relational.Database) AnnotationException(org.hibernate.AnnotationException)

Example 82 with AnnotationException

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

the class EntityBinder method bindEntity.

public void bindEntity() {
    persistentClass.setAbstract(annotatedClass.isAbstract());
    persistentClass.setClassName(annotatedClass.getName());
    persistentClass.setJpaEntityName(name);
    // persistentClass.setDynamic(false); //no longer needed with the Entity name refactoring?
    persistentClass.setEntityName(annotatedClass.getName());
    bindDiscriminatorValue();
    persistentClass.setLazy(lazy);
    if (proxyClass != null) {
        persistentClass.setProxyInterfaceName(proxyClass.getName());
    }
    persistentClass.setDynamicInsert(dynamicInsert);
    persistentClass.setDynamicUpdate(dynamicUpdate);
    if (persistentClass instanceof RootClass) {
        RootClass rootClass = (RootClass) persistentClass;
        boolean mutable = true;
        // priority on @Immutable, then @Entity.mutable()
        if (annotatedClass.isAnnotationPresent(Immutable.class)) {
            mutable = false;
        } else {
            org.hibernate.annotations.Entity entityAnn = annotatedClass.getAnnotation(org.hibernate.annotations.Entity.class);
            if (entityAnn != null) {
                mutable = entityAnn.mutable();
            }
        }
        rootClass.setMutable(mutable);
        rootClass.setExplicitPolymorphism(isExplicitPolymorphism(polymorphismType));
        if (StringHelper.isNotEmpty(where)) {
            rootClass.setWhere(where);
        }
        if (cacheConcurrentStrategy != null) {
            rootClass.setCacheConcurrencyStrategy(cacheConcurrentStrategy);
            rootClass.setCacheRegionName(cacheRegion);
            rootClass.setLazyPropertiesCacheable(cacheLazyProperty);
        }
        rootClass.setNaturalIdCacheRegionName(naturalIdCacheRegion);
        boolean forceDiscriminatorInSelects = forceDiscriminator == null ? context.getBuildingOptions().shouldImplicitlyForceDiscriminatorInSelect() : forceDiscriminator;
        rootClass.setForceDiscriminator(forceDiscriminatorInSelects);
        if (insertableDiscriminator != null) {
            rootClass.setDiscriminatorInsertable(insertableDiscriminator);
        }
    } else {
        if (explicitHibernateEntityAnnotation) {
            LOG.entityAnnotationOnNonRoot(annotatedClass.getName());
        }
        if (annotatedClass.isAnnotationPresent(Immutable.class)) {
            LOG.immutableAnnotationOnNonRoot(annotatedClass.getName());
        }
    }
    persistentClass.setCached(isCached);
    persistentClass.setOptimisticLockStyle(getVersioning(optimisticLockType));
    persistentClass.setSelectBeforeUpdate(selectBeforeUpdate);
    // set persister if needed
    Persister persisterAnn = annotatedClass.getAnnotation(Persister.class);
    Class persister = null;
    if (persisterAnn != null) {
        persister = persisterAnn.impl();
    } else {
        org.hibernate.annotations.Entity entityAnn = annotatedClass.getAnnotation(org.hibernate.annotations.Entity.class);
        if (entityAnn != null && !BinderHelper.isEmptyAnnotationValue(entityAnn.persister())) {
            try {
                persister = context.getBootstrapContext().getClassLoaderAccess().classForName(entityAnn.persister());
            } catch (ClassLoadingException e) {
                throw new AnnotationException("Could not find persister class: " + entityAnn.persister(), e);
            }
        }
    }
    if (persister != null) {
        persistentClass.setEntityPersisterClass(persister);
    }
    persistentClass.setBatchSize(batchSize);
    // SQL overriding
    SQLInsert sqlInsert = annotatedClass.getAnnotation(SQLInsert.class);
    SQLUpdate sqlUpdate = annotatedClass.getAnnotation(SQLUpdate.class);
    SQLDelete sqlDelete = annotatedClass.getAnnotation(SQLDelete.class);
    SQLDeleteAll sqlDeleteAll = annotatedClass.getAnnotation(SQLDeleteAll.class);
    Loader loader = annotatedClass.getAnnotation(Loader.class);
    if (sqlInsert != null) {
        persistentClass.setCustomSQLInsert(sqlInsert.sql().trim(), sqlInsert.callable(), ExecuteUpdateResultCheckStyle.fromExternalName(sqlInsert.check().toString().toLowerCase(Locale.ROOT)));
    }
    if (sqlUpdate != null) {
        persistentClass.setCustomSQLUpdate(sqlUpdate.sql(), sqlUpdate.callable(), ExecuteUpdateResultCheckStyle.fromExternalName(sqlUpdate.check().toString().toLowerCase(Locale.ROOT)));
    }
    if (sqlDelete != null) {
        persistentClass.setCustomSQLDelete(sqlDelete.sql(), sqlDelete.callable(), ExecuteUpdateResultCheckStyle.fromExternalName(sqlDelete.check().toString().toLowerCase(Locale.ROOT)));
    }
    if (sqlDeleteAll != null) {
        persistentClass.setCustomSQLDelete(sqlDeleteAll.sql(), sqlDeleteAll.callable(), ExecuteUpdateResultCheckStyle.fromExternalName(sqlDeleteAll.check().toString().toLowerCase(Locale.ROOT)));
    }
    if (loader != null) {
        persistentClass.setLoaderName(loader.namedQuery());
    }
    final JdbcEnvironment jdbcEnvironment = context.getMetadataCollector().getDatabase().getJdbcEnvironment();
    if (annotatedClass.isAnnotationPresent(Synchronize.class)) {
        Synchronize synchronizedWith = annotatedClass.getAnnotation(Synchronize.class);
        String[] tables = synchronizedWith.value();
        for (String table : tables) {
            persistentClass.addSynchronizedTable(context.getBuildingOptions().getPhysicalNamingStrategy().toPhysicalTableName(jdbcEnvironment.getIdentifierHelper().toIdentifier(table), jdbcEnvironment).render(jdbcEnvironment.getDialect()));
        }
    }
    if (annotatedClass.isAnnotationPresent(Subselect.class)) {
        Subselect subselect = annotatedClass.getAnnotation(Subselect.class);
        this.subselect = subselect.value();
    }
    // tuplizers
    if (annotatedClass.isAnnotationPresent(Tuplizers.class)) {
        for (Tuplizer tuplizer : annotatedClass.getAnnotation(Tuplizers.class).value()) {
            EntityMode mode = EntityMode.parse(tuplizer.entityMode());
            // todo tuplizer.entityModeType
            persistentClass.addTuplizer(mode, tuplizer.impl().getName());
        }
    }
    if (annotatedClass.isAnnotationPresent(Tuplizer.class)) {
        Tuplizer tuplizer = annotatedClass.getAnnotation(Tuplizer.class);
        EntityMode mode = EntityMode.parse(tuplizer.entityMode());
        // todo tuplizer.entityModeType
        persistentClass.addTuplizer(mode, tuplizer.impl().getName());
    }
    for (Filter filter : filters) {
        String filterName = filter.name();
        String cond = filter.condition();
        if (BinderHelper.isEmptyAnnotationValue(cond)) {
            FilterDefinition definition = context.getMetadataCollector().getFilterDefinition(filterName);
            cond = definition == null ? null : definition.getDefaultFilterCondition();
            if (StringHelper.isEmpty(cond)) {
                throw new AnnotationException("no filter condition found for filter " + filterName + " in " + this.name);
            }
        }
        persistentClass.addFilter(filterName, cond, filter.deduceAliasInjectionPoints(), toAliasTableMap(filter.aliases()), toAliasEntityMap(filter.aliases()));
    }
    LOG.debugf("Import with entity name %s", name);
    try {
        context.getMetadataCollector().addImport(name, persistentClass.getEntityName());
        String entityName = persistentClass.getEntityName();
        if (!entityName.equals(name)) {
            context.getMetadataCollector().addImport(entityName, entityName);
        }
    } catch (MappingException me) {
        throw new AnnotationException("Use of the same entity name twice: " + name, me);
    }
    processNamedEntityGraphs();
}
Also used : Synchronize(org.hibernate.annotations.Synchronize) Loader(org.hibernate.annotations.Loader) JdbcEnvironment(org.hibernate.engine.jdbc.env.spi.JdbcEnvironment) MappingException(org.hibernate.MappingException) FilterDefinition(org.hibernate.engine.spi.FilterDefinition) AnnotationException(org.hibernate.AnnotationException) SQLInsert(org.hibernate.annotations.SQLInsert) Persister(org.hibernate.annotations.Persister) RootClass(org.hibernate.mapping.RootClass) Tuplizer(org.hibernate.annotations.Tuplizer) ClassLoadingException(org.hibernate.boot.registry.classloading.spi.ClassLoadingException) Subselect(org.hibernate.annotations.Subselect) SQLDelete(org.hibernate.annotations.SQLDelete) EntityMode(org.hibernate.EntityMode) Filter(org.hibernate.annotations.Filter) PersistentClass(org.hibernate.mapping.PersistentClass) RootClass(org.hibernate.mapping.RootClass) XClass(org.hibernate.annotations.common.reflection.XClass) SQLUpdate(org.hibernate.annotations.SQLUpdate) SQLDeleteAll(org.hibernate.annotations.SQLDeleteAll) Tuplizers(org.hibernate.annotations.Tuplizers)

Example 83 with AnnotationException

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

the class IdBagBinder method bindStarToManySecondPass.

@Override
protected boolean bindStarToManySecondPass(Map persistentClasses, XClass collType, Ejb3JoinColumn[] fkJoinColumns, Ejb3JoinColumn[] keyColumns, Ejb3JoinColumn[] inverseColumns, Ejb3Column[] elementColumns, boolean isEmbedded, XProperty property, boolean unique, TableBinder associationTableBinder, boolean ignoreNotFound, MetadataBuildingContext buildingContext) {
    boolean result = super.bindStarToManySecondPass(persistentClasses, collType, fkJoinColumns, keyColumns, inverseColumns, elementColumns, isEmbedded, property, unique, associationTableBinder, ignoreNotFound, getBuildingContext());
    CollectionId collectionIdAnn = property.getAnnotation(CollectionId.class);
    if (collectionIdAnn != null) {
        SimpleValueBinder simpleValue = new SimpleValueBinder();
        PropertyData propertyData = new WrappedInferredData(new PropertyInferredData(null, property, // default access should not be useful
        null, buildingContext.getBootstrapContext().getReflectionManager()), "id");
        Ejb3Column[] idColumns = Ejb3Column.buildColumnFromAnnotation(collectionIdAnn.columns(), null, Nullability.FORCED_NOT_NULL, propertyHolder, propertyData, Collections.EMPTY_MAP, buildingContext);
        // we need to make sure all id columns must be not-null.
        for (Ejb3Column idColumn : idColumns) {
            idColumn.setNullable(false);
        }
        Table table = collection.getCollectionTable();
        simpleValue.setTable(table);
        simpleValue.setColumns(idColumns);
        Type typeAnn = collectionIdAnn.type();
        if (typeAnn != null && !BinderHelper.isEmptyAnnotationValue(typeAnn.type())) {
            simpleValue.setExplicitType(typeAnn);
        } else {
            throw new AnnotationException("@CollectionId is missing type: " + StringHelper.qualify(propertyHolder.getPath(), propertyName));
        }
        simpleValue.setBuildingContext(getBuildingContext());
        SimpleValue id = simpleValue.make();
        ((IdentifierCollection) collection).setIdentifier(id);
        String generator = collectionIdAnn.generator();
        String generatorType;
        if ("identity".equals(generator) || "assigned".equals(generator) || "sequence".equals(generator) || "native".equals(generator)) {
            generatorType = generator;
            generator = "";
        } else {
            generatorType = null;
        }
        SecondPass secondPass = new IdGeneratorResolverSecondPass(id, property, generatorType, generator, getBuildingContext());
        buildingContext.getMetadataCollector().addSecondPass(secondPass);
    }
    return result;
}
Also used : IdGeneratorResolverSecondPass(org.hibernate.cfg.IdGeneratorResolverSecondPass) WrappedInferredData(org.hibernate.cfg.WrappedInferredData) PropertyData(org.hibernate.cfg.PropertyData) Table(org.hibernate.mapping.Table) PropertyInferredData(org.hibernate.cfg.PropertyInferredData) SimpleValue(org.hibernate.mapping.SimpleValue) IdentifierCollection(org.hibernate.mapping.IdentifierCollection) Type(org.hibernate.annotations.Type) CollectionId(org.hibernate.annotations.CollectionId) IdGeneratorResolverSecondPass(org.hibernate.cfg.IdGeneratorResolverSecondPass) SecondPass(org.hibernate.cfg.SecondPass) AnnotationException(org.hibernate.AnnotationException) Ejb3Column(org.hibernate.cfg.Ejb3Column)

Example 84 with AnnotationException

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

the class SafeMappingTest method testDeclarativeMix.

@Test
public void testDeclarativeMix() throws Exception {
    Configuration cfg = new Configuration();
    cfg.addAnnotatedClass(IncorrectEntity.class);
    cfg.setProperty(Environment.HBM2DDL_AUTO, "create-drop");
    ServiceRegistry serviceRegistry = null;
    SessionFactory sessionFactory = null;
    try {
        serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry(cfg.getProperties());
        sessionFactory = cfg.buildSessionFactory(serviceRegistry);
        fail("Entity wo id should fail");
    } catch (AnnotationException e) {
    // success
    } finally {
        if (sessionFactory != null) {
            sessionFactory.close();
        }
        if (serviceRegistry != null) {
            ServiceRegistryBuilder.destroy(serviceRegistry);
        }
    }
}
Also used : SessionFactory(org.hibernate.SessionFactory) Configuration(org.hibernate.cfg.Configuration) AnnotationException(org.hibernate.AnnotationException) ServiceRegistry(org.hibernate.service.ServiceRegistry) Test(org.junit.Test)

Example 85 with AnnotationException

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

the class OneToOneErrorTest method testWrongOneToOne.

@Test
public void testWrongOneToOne() throws Exception {
    Configuration cfg = new Configuration();
    cfg.addAnnotatedClass(Show.class).addAnnotatedClass(ShowDescription.class);
    cfg.setProperty(Environment.HBM2DDL_AUTO, "create-drop");
    ServiceRegistry serviceRegistry = null;
    SessionFactory sessionFactory = null;
    try {
        serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry(Environment.getProperties());
        sessionFactory = cfg.buildSessionFactory(serviceRegistry);
        Assert.fail("Wrong mappedBy does not fail property");
    } catch (AnnotationException e) {
    // success
    } finally {
        if (sessionFactory != null) {
            sessionFactory.close();
        }
        if (serviceRegistry != null) {
            ServiceRegistryBuilder.destroy(serviceRegistry);
        }
    }
}
Also used : SessionFactory(org.hibernate.SessionFactory) Configuration(org.hibernate.cfg.Configuration) AnnotationException(org.hibernate.AnnotationException) ServiceRegistry(org.hibernate.service.ServiceRegistry) Test(org.junit.Test)

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