Search in sources :

Example 1 with MetadataBuildingContext

use of org.hibernate.boot.spi.MetadataBuildingContext in project hibernate-orm by hibernate.

the class TableBinder method bind.

// only bind association table currently
public Table bind() {
    final Identifier ownerEntityTableNameIdentifier = toIdentifier(ownerEntityTable);
    final Identifier associatedEntityTableNameIdentifier = toIdentifier(associatedEntityTable);
    //logicalName only accurate for assoc table...
    final String unquotedOwnerTable = StringHelper.unquote(ownerEntityTable);
    final String unquotedAssocTable = StringHelper.unquote(associatedEntityTable);
    //@ElementCollection use ownerEntity_property instead of the cleaner ownerTableName_property
    // ownerEntity can be null when the table name is explicitly set; <== gb: doesn't seem to be true...
    final String ownerObjectName = isJPA2ElementCollection && ownerEntity != null ? StringHelper.unqualify(ownerEntity) : unquotedOwnerTable;
    final ObjectNameSource nameSource = buildNameContext(ownerObjectName, unquotedAssocTable);
    final boolean ownerEntityTableQuoted = StringHelper.isQuoted(ownerEntityTable);
    final boolean associatedEntityTableQuoted = StringHelper.isQuoted(associatedEntityTable);
    final NamingStrategyHelper namingStrategyHelper = new NamingStrategyHelper() {

        @Override
        public Identifier determineImplicitName(final MetadataBuildingContext buildingContext) {
            final ImplicitNamingStrategy namingStrategy = buildingContext.getBuildingOptions().getImplicitNamingStrategy();
            Identifier name;
            if (isJPA2ElementCollection) {
                name = namingStrategy.determineCollectionTableName(new ImplicitCollectionTableNameSource() {

                    private final EntityNaming entityNaming = new EntityNaming() {

                        @Override
                        public String getClassName() {
                            return ownerClassName;
                        }

                        @Override
                        public String getEntityName() {
                            return ownerEntity;
                        }

                        @Override
                        public String getJpaEntityName() {
                            return ownerJpaEntity;
                        }
                    };

                    @Override
                    public Identifier getOwningPhysicalTableName() {
                        return ownerEntityTableNameIdentifier;
                    }

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

                    @Override
                    public AttributePath getOwningAttributePath() {
                        return AttributePath.parse(propertyName);
                    }

                    @Override
                    public MetadataBuildingContext getBuildingContext() {
                        return buildingContext;
                    }
                });
            } else {
                name = namingStrategy.determineJoinTableName(new ImplicitJoinTableNameSource() {

                    private final EntityNaming owningEntityNaming = new EntityNaming() {

                        @Override
                        public String getClassName() {
                            return ownerClassName;
                        }

                        @Override
                        public String getEntityName() {
                            return ownerEntity;
                        }

                        @Override
                        public String getJpaEntityName() {
                            return ownerJpaEntity;
                        }
                    };

                    private final EntityNaming nonOwningEntityNaming = new EntityNaming() {

                        @Override
                        public String getClassName() {
                            return associatedClassName;
                        }

                        @Override
                        public String getEntityName() {
                            return associatedEntity;
                        }

                        @Override
                        public String getJpaEntityName() {
                            return associatedJpaEntity;
                        }
                    };

                    @Override
                    public String getOwningPhysicalTableName() {
                        return unquotedOwnerTable;
                    }

                    @Override
                    public EntityNaming getOwningEntityNaming() {
                        return owningEntityNaming;
                    }

                    @Override
                    public String getNonOwningPhysicalTableName() {
                        return unquotedAssocTable;
                    }

                    @Override
                    public EntityNaming getNonOwningEntityNaming() {
                        return nonOwningEntityNaming;
                    }

                    @Override
                    public AttributePath getAssociationOwningAttributePath() {
                        return AttributePath.parse(propertyName);
                    }

                    @Override
                    public MetadataBuildingContext getBuildingContext() {
                        return buildingContext;
                    }
                });
            }
            if (ownerEntityTableQuoted || associatedEntityTableQuoted) {
                name = Identifier.quote(name);
            }
            return name;
        }

        @Override
        public Identifier handleExplicitName(String explicitName, MetadataBuildingContext buildingContext) {
            return buildingContext.getMetadataCollector().getDatabase().toIdentifier(explicitName);
        }

        @Override
        public Identifier toPhysicalName(Identifier logicalName, MetadataBuildingContext buildingContext) {
            return buildingContext.getBuildingOptions().getPhysicalNamingStrategy().toPhysicalTableName(logicalName, buildingContext.getMetadataCollector().getDatabase().getJdbcEnvironment());
        }
    };
    return buildAndFillTable(schema, catalog, nameSource, namingStrategyHelper, isAbstract, uniqueConstraints, jpaIndexHolders, constraints, buildingContext, null, null);
}
Also used : NamingStrategyHelper(org.hibernate.boot.model.naming.NamingStrategyHelper) ImplicitCollectionTableNameSource(org.hibernate.boot.model.naming.ImplicitCollectionTableNameSource) Identifier(org.hibernate.boot.model.naming.Identifier) ObjectNameSource(org.hibernate.cfg.ObjectNameSource) ImplicitNamingStrategy(org.hibernate.boot.model.naming.ImplicitNamingStrategy) EntityNaming(org.hibernate.boot.model.naming.EntityNaming) ImplicitJoinTableNameSource(org.hibernate.boot.model.naming.ImplicitJoinTableNameSource) MetadataBuildingContext(org.hibernate.boot.spi.MetadataBuildingContext)

Example 2 with MetadataBuildingContext

use of org.hibernate.boot.spi.MetadataBuildingContext 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 3 with MetadataBuildingContext

use of org.hibernate.boot.spi.MetadataBuildingContext in project hibernate-orm by hibernate.

the class CollectionBinderTest method testAssociatedClassException.

@Test
@TestForIssue(jiraKey = "HHH-10106")
public void testAssociatedClassException() throws SQLException {
    final Collection collection = mock(Collection.class);
    final Map persistentClasses = mock(Map.class);
    final XClass collectionType = mock(XClass.class);
    final MetadataBuildingContext buildingContext = mock(MetadataBuildingContext.class);
    final InFlightMetadataCollector inFly = mock(InFlightMetadataCollector.class);
    final PersistentClass persistentClass = mock(PersistentClass.class);
    final Table table = mock(Table.class);
    when(buildingContext.getMetadataCollector()).thenReturn(inFly);
    when(persistentClasses.get(null)).thenReturn(null);
    when(collection.getOwner()).thenReturn(persistentClass);
    when(collectionType.getName()).thenReturn("List");
    when(persistentClass.getTable()).thenReturn(table);
    when(table.getName()).thenReturn("Hibernate");
    CollectionBinder collectionBinder = new CollectionBinder(false) {

        @Override
        protected Collection createCollection(PersistentClass persistentClass) {
            return null;
        }

        {
            final PropertyHolder propertyHolder = Mockito.mock(PropertyHolder.class);
            when(propertyHolder.getClassName()).thenReturn(CollectionBinderTest.class.getSimpleName());
            this.propertyName = "abc";
            this.propertyHolder = propertyHolder;
        }
    };
    String expectMessage = "Association [abc] for entity [CollectionBinderTest] references unmapped class [List]";
    try {
        collectionBinder.bindOneToManySecondPass(collection, persistentClasses, null, collectionType, false, false, buildingContext, null);
    } catch (MappingException e) {
        assertEquals(expectMessage, e.getMessage());
    }
}
Also used : InFlightMetadataCollector(org.hibernate.boot.spi.InFlightMetadataCollector) Table(org.hibernate.mapping.Table) PropertyHolder(org.hibernate.cfg.PropertyHolder) Collection(org.hibernate.mapping.Collection) MetadataBuildingContext(org.hibernate.boot.spi.MetadataBuildingContext) Map(java.util.Map) XClass(org.hibernate.annotations.common.reflection.XClass) PersistentClass(org.hibernate.mapping.PersistentClass) MappingException(org.hibernate.MappingException) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 4 with MetadataBuildingContext

use of org.hibernate.boot.spi.MetadataBuildingContext in project hibernate-orm by hibernate.

the class SequenceHiLoGeneratorNoIncrementTest method setUp.

@Before
public void setUp() throws Exception {
    serviceRegistry = new StandardServiceRegistryBuilder().enableAutoClose().applySetting(AvailableSettings.HBM2DDL_AUTO, "create-drop").build();
    generator = new SequenceStyleGenerator();
    // Build the properties used to configure the id generator
    Properties properties = new Properties();
    properties.setProperty(SequenceStyleGenerator.SEQUENCE_PARAM, TEST_SEQUENCE);
    properties.setProperty(SequenceStyleGenerator.OPT_PARAM, "legacy-hilo");
    // JPA allocationSize of 1
    properties.setProperty(SequenceStyleGenerator.INCREMENT_PARAM, "0");
    properties.put(PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER, new ObjectNameNormalizer() {

        @Override
        protected MetadataBuildingContext getBuildingContext() {
            return new MetadataBuildingContextTestingImpl(serviceRegistry);
        }
    });
    generator.configure(StandardBasicTypes.LONG, properties, serviceRegistry);
    final Metadata metadata = new MetadataSources(serviceRegistry).buildMetadata();
    generator.registerExportables(metadata.getDatabase());
    sessionFactory = (SessionFactoryImplementor) metadata.buildSessionFactory();
    sequenceValueExtractor = new SequenceValueExtractor(sessionFactory.getDialect(), TEST_SEQUENCE);
}
Also used : MetadataBuildingContextTestingImpl(org.hibernate.testing.boot.MetadataBuildingContextTestingImpl) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) Metadata(org.hibernate.boot.Metadata) MetadataSources(org.hibernate.boot.MetadataSources) MetadataBuildingContext(org.hibernate.boot.spi.MetadataBuildingContext) ObjectNameNormalizer(org.hibernate.boot.model.naming.ObjectNameNormalizer) SequenceStyleGenerator(org.hibernate.id.enhanced.SequenceStyleGenerator) Properties(java.util.Properties) Before(org.junit.Before)

Example 5 with MetadataBuildingContext

use of org.hibernate.boot.spi.MetadataBuildingContext in project hibernate-orm by hibernate.

the class SequenceHiLoGeneratorTest method setUp.

@Before
public void setUp() throws Exception {
    serviceRegistry = new StandardServiceRegistryBuilder().enableAutoClose().applySetting(AvailableSettings.HBM2DDL_AUTO, "create-drop").build();
    MetadataBuildingContext buildingContext = new MetadataBuildingContextTestingImpl(serviceRegistry);
    Properties properties = new Properties();
    properties.setProperty(SequenceGenerator.SEQUENCE, TEST_SEQUENCE);
    properties.setProperty(SequenceHiLoGenerator.MAX_LO, "3");
    properties.put(PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER, buildingContext.getObjectNameNormalizer());
    generator = new SequenceHiLoGenerator();
    generator.configure(StandardBasicTypes.LONG, properties, serviceRegistry);
    Metadata metadata = new MetadataSources(serviceRegistry).buildMetadata();
    generator.registerExportables(metadata.getDatabase());
    sessionFactory = (SessionFactoryImplementor) metadata.buildSessionFactory();
    sequenceValueExtractor = new SequenceValueExtractor(sessionFactory.getDialect(), TEST_SEQUENCE);
}
Also used : MetadataBuildingContextTestingImpl(org.hibernate.testing.boot.MetadataBuildingContextTestingImpl) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) Metadata(org.hibernate.boot.Metadata) MetadataSources(org.hibernate.boot.MetadataSources) MetadataBuildingContext(org.hibernate.boot.spi.MetadataBuildingContext) Properties(java.util.Properties) Before(org.junit.Before)

Aggregations

MetadataBuildingContext (org.hibernate.boot.spi.MetadataBuildingContext)6 Identifier (org.hibernate.boot.model.naming.Identifier)3 Properties (java.util.Properties)2 AnnotationException (org.hibernate.AnnotationException)2 MappingException (org.hibernate.MappingException)2 Metadata (org.hibernate.boot.Metadata)2 MetadataSources (org.hibernate.boot.MetadataSources)2 EntityNaming (org.hibernate.boot.model.naming.EntityNaming)2 ImplicitNamingStrategy (org.hibernate.boot.model.naming.ImplicitNamingStrategy)2 StandardServiceRegistryBuilder (org.hibernate.boot.registry.StandardServiceRegistryBuilder)2 Column (org.hibernate.mapping.Column)2 PersistentClass (org.hibernate.mapping.PersistentClass)2 MetadataBuildingContextTestingImpl (org.hibernate.testing.boot.MetadataBuildingContextTestingImpl)2 Before (org.junit.Before)2 ArrayList (java.util.ArrayList)1 HashSet (java.util.HashSet)1 List (java.util.List)1 Map (java.util.Map)1 JoinColumn (javax.persistence.JoinColumn)1 PrimaryKeyJoinColumn (javax.persistence.PrimaryKeyJoinColumn)1