Search in sources :

Example 26 with JdbcEnvironment

use of org.hibernate.engine.jdbc.env.spi.JdbcEnvironment in project hibernate-orm by hibernate.

the class Index method buildSqlCreateIndexString.

public static String buildSqlCreateIndexString(Dialect dialect, String name, Table table, Iterator<Column> columns, java.util.Map<Column, String> columnOrderMap, boolean unique, Metadata metadata) {
    final JdbcEnvironment jdbcEnvironment = metadata.getDatabase().getJdbcEnvironment();
    final String tableName = jdbcEnvironment.getQualifiedObjectNameFormatter().format(table.getQualifiedTableName(), dialect);
    return buildSqlCreateIndexString(dialect, name, tableName, columns, columnOrderMap, unique);
}
Also used : JdbcEnvironment(org.hibernate.engine.jdbc.env.spi.JdbcEnvironment)

Example 27 with JdbcEnvironment

use of org.hibernate.engine.jdbc.env.spi.JdbcEnvironment in project hibernate-orm by hibernate.

the class SchemaDropperImpl method dropFromMetadata.

private void dropFromMetadata(Metadata metadata, ExecutionOptions options, Dialect dialect, Formatter formatter, GenerationTarget... targets) {
    final Database database = metadata.getDatabase();
    final JdbcEnvironment jdbcEnvironment = database.getJdbcEnvironment();
    boolean tryToDropCatalogs = false;
    boolean tryToDropSchemas = false;
    if (options.shouldManageNamespaces()) {
        if (dialect.canCreateSchema()) {
            tryToDropSchemas = true;
        }
        if (dialect.canCreateCatalog()) {
            tryToDropCatalogs = true;
        }
    }
    final Set<String> exportIdentifiers = new HashSet<String>(50);
    for (AuxiliaryDatabaseObject auxiliaryDatabaseObject : database.getAuxiliaryDatabaseObjects()) {
        if (!auxiliaryDatabaseObject.beforeTablesOnCreation()) {
            continue;
        }
        if (!auxiliaryDatabaseObject.appliesToDialect(dialect)) {
            continue;
        }
        applySqlStrings(dialect.getAuxiliaryDatabaseObjectExporter().getSqlDropStrings(auxiliaryDatabaseObject, metadata), formatter, options, targets);
    }
    for (Namespace namespace : database.getNamespaces()) {
        if (!schemaFilter.includeNamespace(namespace)) {
            continue;
        }
        // we need to drop all constraints/indexes prior to dropping the tables
        applyConstraintDropping(namespace, metadata, formatter, options, targets);
        // now it's safe to drop the tables
        for (Table table : namespace.getTables()) {
            if (!table.isPhysicalTable()) {
                continue;
            }
            if (!schemaFilter.includeTable(table)) {
                continue;
            }
            checkExportIdentifier(table, exportIdentifiers);
            applySqlStrings(dialect.getTableExporter().getSqlDropStrings(table, metadata), formatter, options, targets);
        }
        for (Sequence sequence : namespace.getSequences()) {
            if (!schemaFilter.includeSequence(sequence)) {
                continue;
            }
            checkExportIdentifier(sequence, exportIdentifiers);
            applySqlStrings(dialect.getSequenceExporter().getSqlDropStrings(sequence, metadata), formatter, options, targets);
        }
    }
    for (AuxiliaryDatabaseObject auxiliaryDatabaseObject : database.getAuxiliaryDatabaseObjects()) {
        if (auxiliaryDatabaseObject.beforeTablesOnCreation()) {
            continue;
        }
        if (!auxiliaryDatabaseObject.appliesToDialect(dialect)) {
            continue;
        }
        applySqlStrings(auxiliaryDatabaseObject.sqlDropStrings(jdbcEnvironment.getDialect()), formatter, options, targets);
    }
    if (tryToDropCatalogs || tryToDropSchemas) {
        Set<Identifier> exportedCatalogs = new HashSet<Identifier>();
        for (Namespace namespace : database.getNamespaces()) {
            if (!schemaFilter.includeNamespace(namespace)) {
                continue;
            }
            if (tryToDropSchemas && namespace.getPhysicalName().getSchema() != null) {
                applySqlStrings(dialect.getDropSchemaCommand(namespace.getPhysicalName().getSchema().render(dialect)), formatter, options, targets);
            }
            if (tryToDropCatalogs) {
                final Identifier catalogLogicalName = namespace.getName().getCatalog();
                final Identifier catalogPhysicalName = namespace.getPhysicalName().getCatalog();
                if (catalogPhysicalName != null && !exportedCatalogs.contains(catalogLogicalName)) {
                    applySqlStrings(dialect.getDropCatalogCommand(catalogPhysicalName.render(dialect)), formatter, options, targets);
                    exportedCatalogs.add(catalogLogicalName);
                }
            }
        }
    }
}
Also used : Table(org.hibernate.mapping.Table) Identifier(org.hibernate.boot.model.naming.Identifier) Database(org.hibernate.boot.model.relational.Database) GenerationTargetToDatabase(org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase) AuxiliaryDatabaseObject(org.hibernate.boot.model.relational.AuxiliaryDatabaseObject) Sequence(org.hibernate.boot.model.relational.Sequence) JdbcEnvironment(org.hibernate.engine.jdbc.env.spi.JdbcEnvironment) Namespace(org.hibernate.boot.model.relational.Namespace) HashSet(java.util.HashSet)

Example 28 with JdbcEnvironment

use of org.hibernate.engine.jdbc.env.spi.JdbcEnvironment in project hibernate-orm by hibernate.

the class NoDatabaseMetaDataTest method testNoJdbcMetadataDialectOverride.

@Test
@TestForIssue(jiraKey = "HHH-10515")
public void testNoJdbcMetadataDialectOverride() {
    final StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySetting("hibernate.temp.use_jdbc_metadata_defaults", "false").applySetting(AvailableSettings.DIALECT, TestDialect.class.getName()).build();
    JdbcEnvironment jdbcEnvironment = serviceRegistry.getService(JdbcEnvironment.class);
    ExtractedDatabaseMetaData extractedDatabaseMetaData = jdbcEnvironment.getExtractedDatabaseMetaData();
    assertNull(extractedDatabaseMetaData.getConnectionCatalogName());
    assertNull(extractedDatabaseMetaData.getConnectionSchemaName());
    assertTrue(extractedDatabaseMetaData.getTypeInfoSet().isEmpty());
    assertTrue(extractedDatabaseMetaData.getExtraKeywords().isEmpty());
    assertTrue(extractedDatabaseMetaData.supportsNamedParameters());
    assertFalse(extractedDatabaseMetaData.supportsRefCursors());
    assertFalse(extractedDatabaseMetaData.supportsScrollableResults());
    assertFalse(extractedDatabaseMetaData.supportsGetGeneratedKeys());
    assertFalse(extractedDatabaseMetaData.supportsBatchUpdates());
    assertFalse(extractedDatabaseMetaData.supportsDataDefinitionInTransaction());
    assertFalse(extractedDatabaseMetaData.doesDataDefinitionCauseTransactionCommit());
    assertNull(extractedDatabaseMetaData.getSqlStateType());
    assertFalse(extractedDatabaseMetaData.doesLobLocatorUpdateCopy());
    StandardServiceRegistryBuilder.destroy(serviceRegistry);
}
Also used : StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) JdbcEnvironment(org.hibernate.engine.jdbc.env.spi.JdbcEnvironment) StandardServiceRegistry(org.hibernate.boot.registry.StandardServiceRegistry) ExtractedDatabaseMetaData(org.hibernate.engine.jdbc.env.spi.ExtractedDatabaseMetaData) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 29 with JdbcEnvironment

use of org.hibernate.engine.jdbc.env.spi.JdbcEnvironment 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());
        }
        if (annotatedClass.isAnnotationPresent(Cacheable.class) || annotatedClass.isAnnotationPresent(Cache.class)) {
            LOG.cacheOrCacheableAnnotationOnNonRoot(annotatedClass.getName());
        }
    }
    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.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 : Cacheable(javax.persistence.Cacheable) 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) NaturalIdCache(org.hibernate.annotations.NaturalIdCache) Cache(org.hibernate.annotations.Cache)

Aggregations

JdbcEnvironment (org.hibernate.engine.jdbc.env.spi.JdbcEnvironment)29 Iterator (java.util.Iterator)6 Namespace (org.hibernate.boot.model.relational.Namespace)5 Dialect (org.hibernate.dialect.Dialect)5 Column (org.hibernate.mapping.Column)5 Table (org.hibernate.mapping.Table)5 Identifier (org.hibernate.boot.model.naming.Identifier)4 QualifiedName (org.hibernate.boot.model.relational.QualifiedName)3 Sequence (org.hibernate.boot.model.relational.Sequence)3 StandardServiceRegistry (org.hibernate.boot.registry.StandardServiceRegistry)3 ArrayList (java.util.ArrayList)2 HashSet (java.util.HashSet)2 EntityMode (org.hibernate.EntityMode)2 AuxiliaryDatabaseObject (org.hibernate.boot.model.relational.AuxiliaryDatabaseObject)2 Database (org.hibernate.boot.model.relational.Database)2 InitCommand (org.hibernate.boot.model.relational.InitCommand)2 StandardServiceRegistryBuilder (org.hibernate.boot.registry.StandardServiceRegistryBuilder)2 ClassLoadingException (org.hibernate.boot.registry.classloading.spi.ClassLoadingException)2 ExtractedDatabaseMetaData (org.hibernate.engine.jdbc.env.spi.ExtractedDatabaseMetaData)2 FilterDefinition (org.hibernate.engine.spi.FilterDefinition)2