Search in sources :

Example 1 with Table

use of jakarta.persistence.Table in project hibernate-orm by hibernate.

the class AnnotationBinder method handleClassTable.

private static jakarta.persistence.Table handleClassTable(XClass clazzToProcess, MetadataBuildingContext context, InheritanceState inheritanceState, PersistentClass superEntity, EntityBinder entityBinder) {
    List<UniqueConstraintHolder> uniqueConstraints = new ArrayList<>();
    jakarta.persistence.Table tableAnnotation;
    String schema;
    String table;
    String catalog;
    boolean hasTableAnnotation = clazzToProcess.isAnnotationPresent(Table.class);
    if (hasTableAnnotation) {
        tableAnnotation = clazzToProcess.getAnnotation(jakarta.persistence.Table.class);
        table = tableAnnotation.name();
        schema = tableAnnotation.schema();
        catalog = tableAnnotation.catalog();
        uniqueConstraints = TableBinder.buildUniqueConstraintHolders(tableAnnotation.uniqueConstraints());
    } else {
        // might be no @Table annotation on the annotated class
        tableAnnotation = null;
        schema = "";
        table = "";
        catalog = "";
    }
    if (inheritanceState.hasTable()) {
        Check checkAnn = getOverridableAnnotation(clazzToProcess, Check.class, context);
        String constraints = checkAnn == null ? null : checkAnn.constraints();
        EntityTableXref denormalizedTableXref = inheritanceState.hasDenormalizedTable() ? context.getMetadataCollector().getEntityTableXref(superEntity.getEntityName()) : null;
        entityBinder.bindTable(schema, catalog, table, uniqueConstraints, constraints, denormalizedTableXref);
    } else {
        if (hasTableAnnotation) {
            LOG.invalidTableAnnotation(clazzToProcess.getName());
        }
        if (inheritanceState.getType() == InheritanceType.SINGLE_TABLE) {
            // we at least need to properly set up the EntityTableXref
            entityBinder.bindTableForDiscriminatedSubclass(context.getMetadataCollector().getEntityTableXref(superEntity.getEntityName()));
        }
    }
    return tableAnnotation;
}
Also used : Table(jakarta.persistence.Table) JoinTable(jakarta.persistence.JoinTable) CollectionTable(jakarta.persistence.CollectionTable) EntityTableXref(org.hibernate.boot.spi.InFlightMetadataCollector.EntityTableXref) ArrayList(java.util.ArrayList) Check(org.hibernate.annotations.Check) Table(jakarta.persistence.Table)

Example 2 with Table

use of jakarta.persistence.Table in project hibernate-orm by hibernate.

the class AnnotationBinder method bindClass.

/**
 * Bind a class having JSR175 annotations. Subclasses <b>have to</b> be bound after its parent class.
 *
 * @param clazzToProcess entity to bind as {@code XClass} instance
 * @param inheritanceStatePerClass Meta data about the inheritance relationships for all mapped classes
 *
 * @throws MappingException in case there is a configuration error
 */
public static void bindClass(XClass clazzToProcess, Map<XClass, InheritanceState> inheritanceStatePerClass, MetadataBuildingContext context) throws MappingException {
    detectMappedSuperclassProblems(clazzToProcess);
    switch(context.getMetadataCollector().getClassType(clazzToProcess)) {
        case MAPPED_SUPERCLASS:
            // Allow queries and filters to be declared by a @MappedSuperclass
            bindQueries(clazzToProcess, context);
            bindFilterDefs(clazzToProcess, context);
        // fall through:
        case EMBEDDABLE:
        case NONE:
            return;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debugf("Binding entity from annotated class: %s", clazzToProcess.getName());
    }
    // TODO: be more strict with secondary table allowance (not for ids, not for secondary table join columns etc)
    InheritanceState inheritanceState = inheritanceStatePerClass.get(clazzToProcess);
    PersistentClass superEntity = getSuperEntity(clazzToProcess, inheritanceStatePerClass, context, inheritanceState);
    detectedAttributeOverrideProblem(clazzToProcess, superEntity);
    PersistentClass persistentClass = makePersistentClass(inheritanceState, superEntity, context);
    EntityBinder entityBinder = new EntityBinder(clazzToProcess, persistentClass, context);
    bindQueries(clazzToProcess, context);
    bindFilterDefs(clazzToProcess, context);
    final AnnotatedJoinColumn[] inheritanceJoinedColumns = makeInheritanceJoinColumns(clazzToProcess, context, inheritanceState, superEntity);
    final AnnotatedDiscriminatorColumn discriminatorColumn = handleDiscriminatorColumn(clazzToProcess, context, inheritanceState, entityBinder);
    entityBinder.setProxy(clazzToProcess.getAnnotation(Proxy.class));
    entityBinder.setBatchSize(clazzToProcess.getAnnotation(BatchSize.class));
    entityBinder.setWhere(getOverridableAnnotation(clazzToProcess, Where.class, context));
    entityBinder.applyCaching(clazzToProcess, context.getBuildingOptions().getSharedCacheMode(), context);
    bindFiltersAndFilterDefs(clazzToProcess, entityBinder, context);
    entityBinder.bindEntity();
    Table table = handleClassTable(clazzToProcess, context, inheritanceState, superEntity, entityBinder);
    PropertyHolder propertyHolder = buildPropertyHolder(clazzToProcess, persistentClass, entityBinder, context, inheritanceStatePerClass);
    handleSecondaryTables(clazzToProcess, entityBinder);
    handleInheritance(clazzToProcess, context, inheritanceState, persistentClass, entityBinder, inheritanceJoinedColumns, discriminatorColumn, propertyHolder);
    // try to find class level generators
    HashMap<String, IdentifierGeneratorDefinition> classGenerators = buildGenerators(clazzToProcess, context);
    handleTypeDescriptorRegistrations(clazzToProcess, context);
    bindEmbeddableInstantiatorRegistrations(clazzToProcess, context);
    bindCompositeUserTypeRegistrations(clazzToProcess, context);
    // check properties
    final InheritanceState.ElementsToProcess elementsToProcess = inheritanceState.getElementsToProcess();
    inheritanceState.postProcess(persistentClass, entityBinder);
    Set<String> idPropertiesIfIdClass = handleIdClass(persistentClass, inheritanceState, context, entityBinder, propertyHolder, elementsToProcess, inheritanceStatePerClass);
    processIdPropertiesIfNotAlready(persistentClass, inheritanceState, context, entityBinder, propertyHolder, classGenerators, idPropertiesIfIdClass, elementsToProcess, inheritanceStatePerClass);
    if (persistentClass instanceof RootClass) {
        context.getMetadataCollector().addSecondPass(new CreateKeySecondPass((RootClass) persistentClass));
    }
    if (persistentClass instanceof Subclass) {
        assert superEntity != null;
        superEntity.addSubclass((Subclass) persistentClass);
    }
    context.getMetadataCollector().addEntityBinding(persistentClass);
    // Process secondary tables and complementary definitions (ie o.h.a.Table)
    context.getMetadataCollector().addSecondPass(new SecondaryTableSecondPass(entityBinder, propertyHolder, clazzToProcess));
    processComplementaryTableDefinitions(clazzToProcess, entityBinder, table);
    bindCallbacks(clazzToProcess, persistentClass, context);
}
Also used : RootClass(org.hibernate.mapping.RootClass) BatchSize(org.hibernate.annotations.BatchSize) Table(jakarta.persistence.Table) JoinTable(jakarta.persistence.JoinTable) CollectionTable(jakarta.persistence.CollectionTable) JoinedSubclass(org.hibernate.mapping.JoinedSubclass) Subclass(org.hibernate.mapping.Subclass) UnionSubclass(org.hibernate.mapping.UnionSubclass) SingleTableSubclass(org.hibernate.mapping.SingleTableSubclass) InheritanceState.getSuperclassInheritanceState(org.hibernate.cfg.InheritanceState.getSuperclassInheritanceState) Proxy(org.hibernate.annotations.Proxy) PropertyHolderBuilder.buildPropertyHolder(org.hibernate.cfg.PropertyHolderBuilder.buildPropertyHolder) IdentifierGeneratorDefinition(org.hibernate.boot.model.IdentifierGeneratorDefinition) EntityBinder(org.hibernate.cfg.annotations.EntityBinder) Where(org.hibernate.annotations.Where) PersistentClass(org.hibernate.mapping.PersistentClass)

Example 3 with Table

use of jakarta.persistence.Table in project hibernate-orm by hibernate.

the class JPAXMLOverriddenAnnotationReader method getTable.

private Table getTable(ManagedType root, XMLContext.Default defaults) {
    JaxbTable element = root instanceof JaxbEntity ? ((JaxbEntity) root).getTable() : null;
    if (element == null) {
        // no element but might have some default or some annotation
        if (StringHelper.isNotEmpty(defaults.getCatalog()) || StringHelper.isNotEmpty(defaults.getSchema())) {
            AnnotationDescriptor annotation = new AnnotationDescriptor(Table.class);
            if (defaults.canUseJavaAnnotations()) {
                Table table = getPhysicalAnnotation(Table.class);
                if (table != null) {
                    annotation.setValue("name", table.name());
                    annotation.setValue("schema", table.schema());
                    annotation.setValue("catalog", table.catalog());
                    annotation.setValue("uniqueConstraints", table.uniqueConstraints());
                    annotation.setValue("indexes", table.indexes());
                }
            }
            if (StringHelper.isEmpty((String) annotation.valueOf("schema")) && StringHelper.isNotEmpty(defaults.getSchema())) {
                annotation.setValue("schema", defaults.getSchema());
            }
            if (StringHelper.isEmpty((String) annotation.valueOf("catalog")) && StringHelper.isNotEmpty(defaults.getCatalog())) {
                annotation.setValue("catalog", defaults.getCatalog());
            }
            return AnnotationFactory.create(annotation);
        } else if (defaults.canUseJavaAnnotations()) {
            return getPhysicalAnnotation(Table.class);
        } else {
            return null;
        }
    } else {
        // ignore java annotation, an element is defined
        AnnotationDescriptor annotation = new AnnotationDescriptor(Table.class);
        copyAttribute(annotation, "name", element.getName(), false);
        copyAttribute(annotation, "catalog", element.getCatalog(), false);
        if (StringHelper.isNotEmpty(defaults.getCatalog()) && StringHelper.isEmpty((String) annotation.valueOf("catalog"))) {
            annotation.setValue("catalog", defaults.getCatalog());
        }
        copyAttribute(annotation, "schema", element.getSchema(), false);
        if (StringHelper.isNotEmpty(defaults.getSchema()) && StringHelper.isEmpty((String) annotation.valueOf("schema"))) {
            annotation.setValue("schema", defaults.getSchema());
        }
        buildUniqueConstraints(annotation, element.getUniqueConstraint());
        buildIndex(annotation, element.getIndex());
        return AnnotationFactory.create(annotation);
    }
}
Also used : AnnotationDescriptor(org.hibernate.annotations.common.annotationfactory.AnnotationDescriptor) JaxbTable(org.hibernate.boot.jaxb.mapping.spi.JaxbTable) JaxbJoinTable(org.hibernate.boot.jaxb.mapping.spi.JaxbJoinTable) Table(jakarta.persistence.Table) CollectionTable(jakarta.persistence.CollectionTable) JaxbSecondaryTable(org.hibernate.boot.jaxb.mapping.spi.JaxbSecondaryTable) JoinTable(jakarta.persistence.JoinTable) JaxbCollectionTable(org.hibernate.boot.jaxb.mapping.spi.JaxbCollectionTable) SecondaryTable(jakarta.persistence.SecondaryTable) JaxbTable(org.hibernate.boot.jaxb.mapping.spi.JaxbTable) JaxbEntity(org.hibernate.boot.jaxb.mapping.spi.JaxbEntity)

Example 4 with Table

use of jakarta.persistence.Table in project hibernate-orm by hibernate.

the class DefaultCatalogAndSchemaTest method verifyEntityPersisterQualifiers.

private void verifyEntityPersisterQualifiers(Class<?> entityClass, ExpectedQualifier expectedQualifier) {
    // The hbm.xml mapping unfortunately sets the native entity name on top of the JPA entity name,
    // so many methods that allow retrieving the entity persister or entity metamodel from the entity class no longer work,
    // because these methods generally assume the native entity name is the FQCN.
    // Thus we use custom code.
    AbstractEntityPersister persister = (AbstractEntityPersister) sessionFactory.getRuntimeMetamodels().getMappingMetamodel().streamEntityDescriptors().filter(p -> p.getMappedClass().equals(entityClass)).findFirst().orElseThrow(() -> new IllegalStateException("Cannot find persister for " + entityClass));
    String jpaEntityName = sessionFactory.getRuntimeMetamodels().getJpaMetamodel().getEntities().stream().filter(p -> p.getBindableJavaType().equals(entityClass)).findFirst().orElseThrow(() -> new IllegalStateException("Cannot find entity metamodel for " + entityClass)).getName();
    // Table names are what's used for Query, in particular.
    verifyOnlyQualifier(persister.getTableName(), SqlType.RUNTIME, jpaEntityName, expectedQualifier);
    // Here, to simplify assertions, we assume all derived entity types have:
    // - an entity name prefixed with the name of their super entity type
    // - the same explicit catalog and schema, if any, as their super entity type
    verifyOnlyQualifier(persister.getTableNames(), SqlType.RUNTIME, jpaEntityName, expectedQualifier);
    // This will include SQL generated by ID generators in some cases, which will be validated here
    // because ID generators table/sequence names are prefixed with the owning entity name.
    verifyOnlyQualifier(persister.getSQLInsertStrings(), SqlType.RUNTIME, jpaEntityName, expectedQualifier);
    if (persister.isIdentifierAssignedByInsert()) {
        verifyOnlyQualifier(persister.getSQLIdentityInsertString(), SqlType.RUNTIME, jpaEntityName, expectedQualifier);
    }
    try {
        verifyOnlyQualifierOptional(persister.getIdentitySelectString(), SqlType.RUNTIME, jpaEntityName, expectedQualifier);
    } catch (MappingException e) {
        if (e.getMessage().contains("does not support identity key generation")) {
        // For some reason Oracle12cIdentityColumnSupport#supportsInsertSelectIdentity() returns true,
        // but getIdentitySelectString is not implemented, resulting in runtime exceptions.
        // Whatever, we'll just ignore this for now.
        } else {
            throw e;
        }
    }
    verifyOnlyQualifier(persister.getSQLUpdateStrings(), SqlType.RUNTIME, jpaEntityName, expectedQualifier);
    verifyOnlyQualifier(persister.getSQLLazyUpdateStrings(), SqlType.RUNTIME, jpaEntityName, expectedQualifier);
    verifyOnlyQualifier(persister.getSQLDeleteStrings(), SqlType.RUNTIME, jpaEntityName, expectedQualifier);
    // This is used in the "select" id generator in particular.
    verifyOnlyQualifierOptional(persister.getSelectByUniqueKeyString("basic"), SqlType.RUNTIME, jpaEntityName, expectedQualifier);
}
Also used : Entity(jakarta.persistence.Entity) Arrays(java.util.Arrays) TargetDescriptor(org.hibernate.tool.schema.spi.TargetDescriptor) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) SessionFactoryBuilder(org.hibernate.boot.SessionFactoryBuilder) SessionFactoryOptionsBuilder(org.hibernate.boot.internal.SessionFactoryOptionsBuilder) GenerationType(jakarta.persistence.GenerationType) Table(jakarta.persistence.Table) TestForIssue(org.hibernate.testing.TestForIssue) Map(java.util.Map) NameQualifierSupport(org.hibernate.engine.jdbc.env.spi.NameQualifierSupport) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) EnumSet(java.util.EnumSet) StandardServiceRegistry(org.hibernate.boot.registry.StandardServiceRegistry) Parameterized(org.junit.runners.Parameterized) SessionFactoryBuilderImpl(org.hibernate.boot.internal.SessionFactoryBuilderImpl) IdentifierGenerator(org.hibernate.id.IdentifierGenerator) Parameter(org.hibernate.annotations.Parameter) JoinColumn(jakarta.persistence.JoinColumn) Id(jakarta.persistence.Id) MetadataSources(org.hibernate.boot.MetadataSources) SchemaManagementToolCoordinator(org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator) SQLServerDialect(org.hibernate.dialect.SQLServerDialect) List(java.util.List) AfterClassOnce(org.hibernate.testing.AfterClassOnce) Basic(jakarta.persistence.Basic) MetadataImpl(org.hibernate.boot.internal.MetadataImpl) MappingException(org.hibernate.MappingException) JoinTable(jakarta.persistence.JoinTable) AbstractEntityPersister(org.hibernate.persister.entity.AbstractEntityPersister) Pattern(java.util.regex.Pattern) DelayedDropRegistryNotAvailableImpl(org.hibernate.tool.schema.spi.DelayedDropRegistryNotAvailableImpl) SharedDriverManagerConnectionProviderImpl(org.hibernate.testing.jdbc.SharedDriverManagerConnectionProviderImpl) ScriptTargetOutput(org.hibernate.tool.schema.spi.ScriptTargetOutput) BootstrapServiceRegistryBuilder(org.hibernate.boot.registry.BootstrapServiceRegistryBuilder) Inheritance(jakarta.persistence.Inheritance) AvailableSettings(org.hibernate.cfg.AvailableSettings) OneToMany(jakarta.persistence.OneToMany) RunWith(org.junit.runner.RunWith) HashMap(java.util.HashMap) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) ArrayList(java.util.ArrayList) TableGenerator(jakarta.persistence.TableGenerator) SequenceGenerator(jakarta.persistence.SequenceGenerator) SQLDelete(org.hibernate.annotations.SQLDelete) MetadataImplementor(org.hibernate.boot.spi.MetadataImplementor) ConfigurationService(org.hibernate.engine.config.spi.ConfigurationService) Environment(org.hibernate.cfg.Environment) SchemaExport(org.hibernate.tool.hbm2ddl.SchemaExport) ServiceRegistryImplementor(org.hibernate.service.spi.ServiceRegistryImplementor) SQLUpdate(org.hibernate.annotations.SQLUpdate) TargetType(org.hibernate.tool.schema.TargetType) ForeignKey(jakarta.persistence.ForeignKey) LocalTemporaryTableStrategy(org.hibernate.query.sqm.mutation.internal.temptable.LocalTemporaryTableStrategy) CustomParameterized(org.hibernate.testing.junit4.CustomParameterized) InheritanceType(jakarta.persistence.InheritanceType) StringWriter(java.io.StringWriter) BootstrapServiceRegistry(org.hibernate.boot.registry.BootstrapServiceRegistry) Test(org.junit.Test) GeneratedValue(jakarta.persistence.GeneratedValue) GenericGenerator(org.hibernate.annotations.GenericGenerator) ScriptTargetOutputToWriter(org.hibernate.tool.schema.internal.exec.ScriptTargetOutputToWriter) ElementCollection(jakarta.persistence.ElementCollection) MetadataBuilder(org.hibernate.boot.MetadataBuilder) GlobalTemporaryTableStrategy(org.hibernate.query.sqm.mutation.internal.temptable.GlobalTemporaryTableStrategy) BeforeClassOnce(org.hibernate.testing.BeforeClassOnce) Collections(java.util.Collections) SQLInsert(org.hibernate.annotations.SQLInsert) AbstractEntityPersister(org.hibernate.persister.entity.AbstractEntityPersister) MappingException(org.hibernate.MappingException)

Example 5 with Table

use of jakarta.persistence.Table in project olca-modules by GreenDelta.

the class Seq method initType.

private void initType(ModelType type) {
    Table table = type.getModelClass().getAnnotation(Table.class);
    String query = "select id, ref_id from " + table.name();
    HashMap<String, Long> seq = new HashMap<>();
    HashSet<String> inDb = new HashSet<>();
    try {
        NativeSql.on(db).query(query, result -> {
            String refId = result.getString(2);
            seq.put(refId, result.getLong(1));
            inDb.add(refId);
            return true;
        });
    } catch (Exception e) {
        log.error("failed to initialize sequence map for " + type, e);
    }
    sequences[type.ordinal()] = seq;
    inDatabase[type.ordinal()] = inDb;
}
Also used : Table(jakarta.persistence.Table) HashMap(java.util.HashMap) AtomicLong(java.util.concurrent.atomic.AtomicLong) HashSet(java.util.HashSet)

Aggregations

Table (jakarta.persistence.Table)5 JoinTable (jakarta.persistence.JoinTable)4 CollectionTable (jakarta.persistence.CollectionTable)3 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 Basic (jakarta.persistence.Basic)1 ElementCollection (jakarta.persistence.ElementCollection)1 Entity (jakarta.persistence.Entity)1 ForeignKey (jakarta.persistence.ForeignKey)1 GeneratedValue (jakarta.persistence.GeneratedValue)1 GenerationType (jakarta.persistence.GenerationType)1 Id (jakarta.persistence.Id)1 Inheritance (jakarta.persistence.Inheritance)1 InheritanceType (jakarta.persistence.InheritanceType)1 JoinColumn (jakarta.persistence.JoinColumn)1 OneToMany (jakarta.persistence.OneToMany)1 SecondaryTable (jakarta.persistence.SecondaryTable)1 SequenceGenerator (jakarta.persistence.SequenceGenerator)1 TableGenerator (jakarta.persistence.TableGenerator)1 StringWriter (java.io.StringWriter)1