Search in sources :

Example 16 with Identifier

use of org.hibernate.boot.model.naming.Identifier in project hibernate-orm by hibernate.

the class Ejb3JoinColumn method buildDefaultColumnName.

private String buildDefaultColumnName(final PersistentClass referencedEntity, final String logicalReferencedColumn) {
    final Database database = getBuildingContext().getMetadataCollector().getDatabase();
    final ImplicitNamingStrategy implicitNamingStrategy = getBuildingContext().getBuildingOptions().getImplicitNamingStrategy();
    final PhysicalNamingStrategy physicalNamingStrategy = getBuildingContext().getBuildingOptions().getPhysicalNamingStrategy();
    Identifier columnIdentifier;
    boolean mappedBySide = mappedByTableName != null || mappedByPropertyName != null;
    boolean ownerSide = getPropertyName() != null;
    Boolean isRefColumnQuoted = StringHelper.isQuoted(logicalReferencedColumn);
    final String unquotedLogicalReferenceColumn = isRefColumnQuoted ? StringHelper.unquote(logicalReferencedColumn) : logicalReferencedColumn;
    if (mappedBySide) {
        // NOTE : While it is completely misleading here to allow for the combination
        //		of a "JPA ElementCollection" to be mappedBy, the code that uses this
        // 		class relies on this behavior for handling the inverse side of
        // 		many-to-many mappings
        final AttributePath attributePath = AttributePath.parse(mappedByPropertyName);
        final ImplicitJoinColumnNameSource.Nature implicitNamingNature;
        if (getPropertyHolder().isEntity()) {
            implicitNamingNature = ImplicitJoinColumnNameSource.Nature.ENTITY;
        } else if (JPA2ElementCollection) {
            implicitNamingNature = ImplicitJoinColumnNameSource.Nature.ELEMENT_COLLECTION;
        } else {
            implicitNamingNature = ImplicitJoinColumnNameSource.Nature.ENTITY_COLLECTION;
        }
        columnIdentifier = implicitNamingStrategy.determineJoinColumnName(new ImplicitJoinColumnNameSource() {

            private final EntityNaming entityNaming = new EntityNaming() {

                @Override
                public String getClassName() {
                    return referencedEntity.getClassName();
                }

                @Override
                public String getEntityName() {
                    return referencedEntity.getEntityName();
                }

                @Override
                public String getJpaEntityName() {
                    return referencedEntity.getJpaEntityName();
                }
            };

            private final Identifier referencedTableName = getBuildingContext().getMetadataCollector().getDatabase().toIdentifier(mappedByTableName);

            @Override
            public Nature getNature() {
                return implicitNamingNature;
            }

            @Override
            public EntityNaming getEntityNaming() {
                return entityNaming;
            }

            @Override
            public AttributePath getAttributePath() {
                return attributePath;
            }

            @Override
            public Identifier getReferencedTableName() {
                return referencedTableName;
            }

            @Override
            public Identifier getReferencedColumnName() {
                if (logicalReferencedColumn != null) {
                    return getBuildingContext().getMetadataCollector().getDatabase().toIdentifier(logicalReferencedColumn);
                }
                if (mappedByEntityName == null || mappedByPropertyName == null) {
                    return null;
                }
                final PersistentClass mappedByEntityBinding = getBuildingContext().getMetadataCollector().getEntityBinding(mappedByEntityName);
                final Property mappedByProperty = mappedByEntityBinding.getProperty(mappedByPropertyName);
                final SimpleValue value = (SimpleValue) mappedByProperty.getValue();
                final Iterator<Selectable> selectableValues = value.getColumnIterator();
                if (!selectableValues.hasNext()) {
                    throw new AnnotationException(String.format(Locale.ENGLISH, "mapped-by [%s] defined for attribute [%s] referenced an invalid property (no columns)", mappedByPropertyName, propertyHolder.getPath()));
                }
                final Selectable selectable = selectableValues.next();
                if (!Column.class.isInstance(selectable)) {
                    throw new AnnotationException(String.format(Locale.ENGLISH, "mapped-by [%s] defined for attribute [%s] referenced an invalid property (formula)", mappedByPropertyName, propertyHolder.getPath()));
                }
                if (selectableValues.hasNext()) {
                    throw new AnnotationException(String.format(Locale.ENGLISH, "mapped-by [%s] defined for attribute [%s] referenced an invalid property (multiple columns)", mappedByPropertyName, propertyHolder.getPath()));
                }
                return getBuildingContext().getMetadataCollector().getDatabase().toIdentifier(((Column) selectable).getQuotedName());
            }

            @Override
            public MetadataBuildingContext getBuildingContext() {
                return Ejb3JoinColumn.this.getBuildingContext();
            }
        });
        //one element was quoted so we quote
        if (isRefColumnQuoted || StringHelper.isQuoted(mappedByTableName)) {
            columnIdentifier = Identifier.quote(columnIdentifier);
        }
    } else if (ownerSide) {
        final String logicalTableName = getBuildingContext().getMetadataCollector().getLogicalTableName(referencedEntity.getTable());
        final ImplicitJoinColumnNameSource.Nature implicitNamingNature;
        if (JPA2ElementCollection) {
            implicitNamingNature = ImplicitJoinColumnNameSource.Nature.ELEMENT_COLLECTION;
        } else if (getPropertyHolder().isEntity()) {
            implicitNamingNature = ImplicitJoinColumnNameSource.Nature.ENTITY;
        } else {
            implicitNamingNature = ImplicitJoinColumnNameSource.Nature.ENTITY_COLLECTION;
        }
        columnIdentifier = getBuildingContext().getBuildingOptions().getImplicitNamingStrategy().determineJoinColumnName(new ImplicitJoinColumnNameSource() {

            private final EntityNaming entityNaming = new EntityNaming() {

                @Override
                public String getClassName() {
                    return referencedEntity.getClassName();
                }

                @Override
                public String getEntityName() {
                    return referencedEntity.getEntityName();
                }

                @Override
                public String getJpaEntityName() {
                    return referencedEntity.getJpaEntityName();
                }
            };

            private final AttributePath attributePath = AttributePath.parse(getPropertyName());

            private final Identifier referencedTableName = getBuildingContext().getMetadataCollector().getDatabase().toIdentifier(logicalTableName);

            private final Identifier referencedColumnName = getBuildingContext().getMetadataCollector().getDatabase().toIdentifier(logicalReferencedColumn);

            @Override
            public Nature getNature() {
                return implicitNamingNature;
            }

            @Override
            public EntityNaming getEntityNaming() {
                return entityNaming;
            }

            @Override
            public AttributePath getAttributePath() {
                return attributePath;
            }

            @Override
            public Identifier getReferencedTableName() {
                return referencedTableName;
            }

            @Override
            public Identifier getReferencedColumnName() {
                return referencedColumnName;
            }

            @Override
            public MetadataBuildingContext getBuildingContext() {
                return Ejb3JoinColumn.this.getBuildingContext();
            }
        });
        //one element was quoted so we quote
        if (isRefColumnQuoted || StringHelper.isQuoted(logicalTableName)) {
            columnIdentifier = Identifier.quote(columnIdentifier);
        }
    } else {
        final Identifier logicalTableName = database.toIdentifier(getBuildingContext().getMetadataCollector().getLogicalTableName(referencedEntity.getTable()));
        // is an intra-entity hierarchy table join so copy the name by default
        columnIdentifier = implicitNamingStrategy.determinePrimaryKeyJoinColumnName(new ImplicitPrimaryKeyJoinColumnNameSource() {

            @Override
            public MetadataBuildingContext getBuildingContext() {
                return Ejb3JoinColumn.this.getBuildingContext();
            }

            @Override
            public Identifier getReferencedTableName() {
                return logicalTableName;
            }

            @Override
            public Identifier getReferencedPrimaryKeyColumnName() {
                return database.toIdentifier(logicalReferencedColumn);
            }
        });
        if (!columnIdentifier.isQuoted() && (isRefColumnQuoted || logicalTableName.isQuoted())) {
            columnIdentifier = Identifier.quote(columnIdentifier);
        }
    }
    return physicalNamingStrategy.toPhysicalColumnName(columnIdentifier, database.getJdbcEnvironment()).render(database.getJdbcEnvironment().getDialect());
}
Also used : ImplicitNamingStrategy(org.hibernate.boot.model.naming.ImplicitNamingStrategy) ImplicitJoinColumnNameSource(org.hibernate.boot.model.naming.ImplicitJoinColumnNameSource) ImplicitPrimaryKeyJoinColumnNameSource(org.hibernate.boot.model.naming.ImplicitPrimaryKeyJoinColumnNameSource) MetadataBuildingContext(org.hibernate.boot.spi.MetadataBuildingContext) PhysicalNamingStrategy(org.hibernate.boot.model.naming.PhysicalNamingStrategy) SimpleValue(org.hibernate.mapping.SimpleValue) Identifier(org.hibernate.boot.model.naming.Identifier) Selectable(org.hibernate.mapping.Selectable) JoinColumn(javax.persistence.JoinColumn) Column(org.hibernate.mapping.Column) PrimaryKeyJoinColumn(javax.persistence.PrimaryKeyJoinColumn) EntityNaming(org.hibernate.boot.model.naming.EntityNaming) Database(org.hibernate.boot.model.relational.Database) AnnotationException(org.hibernate.AnnotationException) Property(org.hibernate.mapping.Property) AttributePath(org.hibernate.boot.model.source.spi.AttributePath) PersistentClass(org.hibernate.mapping.PersistentClass)

Example 17 with Identifier

use of org.hibernate.boot.model.naming.Identifier in project hibernate-orm by hibernate.

the class EntityBinder method addJoin.

private Join addJoin(SecondaryTable secondaryTable, JoinTable joinTable, PropertyHolder propertyHolder, boolean noDelayInPkColumnCreation) {
    // A non null propertyHolder means than we process the Pk creation without delay
    Join join = new Join();
    join.setPersistentClass(persistentClass);
    final String schema;
    final String catalog;
    final SecondaryTableNameSource secondaryTableNameContext;
    final Object joinColumns;
    final List<UniqueConstraintHolder> uniqueConstraintHolders;
    final Identifier logicalName;
    if (secondaryTable != null) {
        schema = secondaryTable.schema();
        catalog = secondaryTable.catalog();
        logicalName = context.getMetadataCollector().getDatabase().getJdbcEnvironment().getIdentifierHelper().toIdentifier(secondaryTable.name());
        joinColumns = secondaryTable.pkJoinColumns();
        uniqueConstraintHolders = TableBinder.buildUniqueConstraintHolders(secondaryTable.uniqueConstraints());
    } else if (joinTable != null) {
        schema = joinTable.schema();
        catalog = joinTable.catalog();
        logicalName = context.getMetadataCollector().getDatabase().getJdbcEnvironment().getIdentifierHelper().toIdentifier(joinTable.name());
        joinColumns = joinTable.joinColumns();
        uniqueConstraintHolders = TableBinder.buildUniqueConstraintHolders(joinTable.uniqueConstraints());
    } else {
        throw new AssertionFailure("Both JoinTable and SecondaryTable are null");
    }
    final Table table = TableBinder.buildAndFillTable(schema, catalog, logicalName, false, uniqueConstraintHolders, null, null, context, null, null);
    final InFlightMetadataCollector.EntityTableXref tableXref = context.getMetadataCollector().getEntityTableXref(persistentClass.getEntityName());
    assert tableXref != null : "Could not locate EntityTableXref for entity [" + persistentClass.getEntityName() + "]";
    tableXref.addSecondaryTable(logicalName, join);
    if (secondaryTable != null) {
        TableBinder.addIndexes(table, secondaryTable.indexes(), context);
    }
    //no check constraints available on joins
    join.setTable(table);
    //somehow keep joins() for later.
    //Has to do the work later because it needs persistentClass id!
    LOG.debugf("Adding secondary table to entity %s -> %s", persistentClass.getEntityName(), join.getTable().getName());
    org.hibernate.annotations.Table matchingTable = findMatchingComplimentTableAnnotation(join);
    if (matchingTable != null) {
        join.setSequentialSelect(FetchMode.JOIN != matchingTable.fetch());
        join.setInverse(matchingTable.inverse());
        join.setOptional(matchingTable.optional());
        if (!BinderHelper.isEmptyAnnotationValue(matchingTable.sqlInsert().sql())) {
            join.setCustomSQLInsert(matchingTable.sqlInsert().sql().trim(), matchingTable.sqlInsert().callable(), ExecuteUpdateResultCheckStyle.fromExternalName(matchingTable.sqlInsert().check().toString().toLowerCase(Locale.ROOT)));
        }
        if (!BinderHelper.isEmptyAnnotationValue(matchingTable.sqlUpdate().sql())) {
            join.setCustomSQLUpdate(matchingTable.sqlUpdate().sql().trim(), matchingTable.sqlUpdate().callable(), ExecuteUpdateResultCheckStyle.fromExternalName(matchingTable.sqlUpdate().check().toString().toLowerCase(Locale.ROOT)));
        }
        if (!BinderHelper.isEmptyAnnotationValue(matchingTable.sqlDelete().sql())) {
            join.setCustomSQLDelete(matchingTable.sqlDelete().sql().trim(), matchingTable.sqlDelete().callable(), ExecuteUpdateResultCheckStyle.fromExternalName(matchingTable.sqlDelete().check().toString().toLowerCase(Locale.ROOT)));
        }
    } else {
        //default
        join.setSequentialSelect(false);
        join.setInverse(false);
        //perhaps not quite per-spec, but a Good Thing anyway
        join.setOptional(true);
    }
    if (noDelayInPkColumnCreation) {
        createPrimaryColumnsToSecondaryTable(joinColumns, propertyHolder, join);
    } else {
        secondaryTables.put(table.getQuotedName(), join);
        secondaryTableJoins.put(table.getQuotedName(), joinColumns);
    }
    return join;
}
Also used : UniqueConstraintHolder(org.hibernate.cfg.UniqueConstraintHolder) AssertionFailure(org.hibernate.AssertionFailure) JoinTable(javax.persistence.JoinTable) SecondaryTable(javax.persistence.SecondaryTable) Table(org.hibernate.mapping.Table) Join(org.hibernate.mapping.Join) Identifier(org.hibernate.boot.model.naming.Identifier) InFlightMetadataCollector(org.hibernate.boot.spi.InFlightMetadataCollector)

Example 18 with Identifier

use of org.hibernate.boot.model.naming.Identifier in project hibernate-orm by hibernate.

the class MultipleHiLoPerTableGenerator method determineGeneratorTableName.

protected QualifiedName determineGeneratorTableName(Properties params, JdbcEnvironment jdbcEnvironment) {
    final String tableName = ConfigurationHelper.getString(ID_TABLE, params, DEFAULT_TABLE);
    if (tableName.contains(".")) {
        return QualifiedNameParser.INSTANCE.parse(tableName);
    } else {
        // todo : need to incorporate implicit catalog and schema names
        final Identifier catalog = jdbcEnvironment.getIdentifierHelper().toIdentifier(ConfigurationHelper.getString(CATALOG, params));
        final Identifier schema = jdbcEnvironment.getIdentifierHelper().toIdentifier(ConfigurationHelper.getString(SCHEMA, params));
        return new QualifiedNameParser.NameParts(catalog, schema, jdbcEnvironment.getIdentifierHelper().toIdentifier(tableName));
    }
}
Also used : Identifier(org.hibernate.boot.model.naming.Identifier)

Example 19 with Identifier

use of org.hibernate.boot.model.naming.Identifier in project hibernate-orm by hibernate.

the class SequenceStyleGenerator method determineSequenceName.

/**
	 * Determine the name of the sequence (or table if this resolves to a physical table)
	 * to use.
	 * <p/>
	 * Called during {@link #configure configuration}.
	 *
	 * @param params The params supplied in the generator config (plus some standard useful extras).
	 * @param dialect The dialect in effect
	 * @param jdbcEnv The JdbcEnvironment
	 * @return The sequence name
	 */
@SuppressWarnings("UnusedParameters")
protected QualifiedName determineSequenceName(Properties params, Dialect dialect, JdbcEnvironment jdbcEnv) {
    final String sequencePerEntitySuffix = ConfigurationHelper.getString(CONFIG_SEQUENCE_PER_ENTITY_SUFFIX, params, DEF_SEQUENCE_SUFFIX);
    // JPA_ENTITY_NAME value honors <class ... entity-name="..."> (HBM) and @Entity#name (JPA) overrides.
    final String defaultSequenceName = ConfigurationHelper.getBoolean(CONFIG_PREFER_SEQUENCE_PER_ENTITY, params, false) ? params.getProperty(JPA_ENTITY_NAME) + sequencePerEntitySuffix : DEF_SEQUENCE_NAME;
    final String sequenceName = ConfigurationHelper.getString(SEQUENCE_PARAM, params, defaultSequenceName);
    if (sequenceName.contains(".")) {
        return QualifiedNameParser.INSTANCE.parse(sequenceName);
    } else {
        // todo : need to incorporate implicit catalog and schema names
        final Identifier catalog = jdbcEnv.getIdentifierHelper().toIdentifier(ConfigurationHelper.getString(CATALOG, params));
        final Identifier schema = jdbcEnv.getIdentifierHelper().toIdentifier(ConfigurationHelper.getString(SCHEMA, params));
        return new QualifiedNameParser.NameParts(catalog, schema, jdbcEnv.getIdentifierHelper().toIdentifier(sequenceName));
    }
}
Also used : Identifier(org.hibernate.boot.model.naming.Identifier)

Example 20 with Identifier

use of org.hibernate.boot.model.naming.Identifier in project hibernate-orm by hibernate.

the class InformationExtractorJdbcDatabaseMetaDataImpl method locateTableInNamespace.

private TableInformation locateTableInNamespace(Identifier catalog, Identifier schema, Identifier tableName) {
    Identifier catalogToUse = null;
    Identifier schemaToUse = null;
    final String catalogFilter;
    final String schemaFilter;
    if (extractionContext.getJdbcEnvironment().getNameQualifierSupport().supportsCatalogs()) {
        if (catalog == null) {
            catalogFilter = "";
        } else {
            catalogToUse = catalog;
            catalogFilter = toMetaDataObjectName(catalog);
        }
    } else {
        catalogFilter = null;
    }
    if (extractionContext.getJdbcEnvironment().getNameQualifierSupport().supportsSchemas()) {
        if (schema == null) {
            schemaFilter = "";
        } else {
            schemaToUse = schema;
            schemaFilter = toMetaDataObjectName(schema);
        }
    } else {
        schemaFilter = null;
    }
    final String tableNameFilter = toMetaDataObjectName(tableName);
    try {
        ResultSet resultSet = extractionContext.getJdbcDatabaseMetaData().getTables(catalogFilter, schemaFilter, tableNameFilter, tableTypes);
        return processTableResults(catalogToUse, schemaToUse, tableName, resultSet);
    } catch (SQLException sqlException) {
        throw convertSQLException(sqlException, "Error accessing table metadata");
    }
}
Also used : DatabaseIdentifier(org.hibernate.boot.model.naming.DatabaseIdentifier) Identifier(org.hibernate.boot.model.naming.Identifier) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet)

Aggregations

Identifier (org.hibernate.boot.model.naming.Identifier)46 Table (org.hibernate.mapping.Table)15 LocalMetadataBuildingContext (org.hibernate.boot.model.source.spi.LocalMetadataBuildingContext)10 DenormalizedTable (org.hibernate.mapping.DenormalizedTable)9 SimpleValue (org.hibernate.mapping.SimpleValue)9 HashMap (java.util.HashMap)7 MappingException (org.hibernate.boot.MappingException)7 Namespace (org.hibernate.boot.model.relational.Namespace)7 Database (org.hibernate.boot.model.relational.Database)6 ResultSet (java.sql.ResultSet)5 SQLException (java.sql.SQLException)5 ArrayList (java.util.ArrayList)5 DatabaseIdentifier (org.hibernate.boot.model.naming.DatabaseIdentifier)5 Column (org.hibernate.mapping.Column)5 Property (org.hibernate.mapping.Property)5 HashSet (java.util.HashSet)4 DuplicateMappingException (org.hibernate.DuplicateMappingException)4 ImplicitNamingStrategy (org.hibernate.boot.model.naming.ImplicitNamingStrategy)4 JdbcEnvironment (org.hibernate.engine.jdbc.env.spi.JdbcEnvironment)4 SyntheticProperty (org.hibernate.mapping.SyntheticProperty)4