Search in sources :

Example 11 with AssertionFailure

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

the class TableBinder method bindFk.

public static void bindFk(PersistentClass referencedEntity, PersistentClass destinationEntity, Ejb3JoinColumn[] columns, SimpleValue value, boolean unique, MetadataBuildingContext buildingContext) {
    PersistentClass associatedClass;
    if (destinationEntity != null) {
        //overridden destination
        associatedClass = destinationEntity;
    } else {
        associatedClass = columns[0].getPropertyHolder() == null ? null : columns[0].getPropertyHolder().getPersistentClass();
    }
    final String mappedByProperty = columns[0].getMappedBy();
    if (StringHelper.isNotEmpty(mappedByProperty)) {
        /**
			 * Get the columns of the mapped-by property
			 * copy them and link the copy to the actual value
			 */
        LOG.debugf("Retrieving property %s.%s", associatedClass.getEntityName(), mappedByProperty);
        final Property property = associatedClass.getRecursiveProperty(columns[0].getMappedBy());
        Iterator mappedByColumns;
        if (property.getValue() instanceof Collection) {
            Collection collection = ((Collection) property.getValue());
            Value element = collection.getElement();
            if (element == null) {
                throw new AnnotationException("Illegal use of mappedBy on both sides of the relationship: " + associatedClass.getEntityName() + "." + mappedByProperty);
            }
            mappedByColumns = element.getColumnIterator();
        } else {
            mappedByColumns = property.getValue().getColumnIterator();
        }
        while (mappedByColumns.hasNext()) {
            Column column = (Column) mappedByColumns.next();
            columns[0].overrideFromReferencedColumnIfNecessary(column);
            columns[0].linkValueUsingAColumnCopy(column, value);
        }
    } else if (columns[0].isImplicit()) {
        /**
			 * if columns are implicit, then create the columns based on the
			 * referenced entity id columns
			 */
        Iterator idColumns;
        if (referencedEntity instanceof JoinedSubclass) {
            idColumns = referencedEntity.getKey().getColumnIterator();
        } else {
            idColumns = referencedEntity.getIdentifier().getColumnIterator();
        }
        while (idColumns.hasNext()) {
            Column column = (Column) idColumns.next();
            columns[0].linkValueUsingDefaultColumnNaming(column, referencedEntity, value);
            columns[0].overrideFromReferencedColumnIfNecessary(column);
        }
    } else {
        int fkEnum = Ejb3JoinColumn.checkReferencedColumnsType(columns, referencedEntity, buildingContext);
        if (Ejb3JoinColumn.NON_PK_REFERENCE == fkEnum) {
            String referencedPropertyName;
            if (value instanceof ToOne) {
                referencedPropertyName = ((ToOne) value).getReferencedPropertyName();
            } else if (value instanceof DependantValue) {
                String propertyName = columns[0].getPropertyName();
                if (propertyName != null) {
                    Collection collection = (Collection) referencedEntity.getRecursiveProperty(propertyName).getValue();
                    referencedPropertyName = collection.getReferencedPropertyName();
                } else {
                    throw new AnnotationException("SecondaryTable JoinColumn cannot reference a non primary key");
                }
            } else {
                throw new AssertionFailure("Do a property ref on an unexpected Value type: " + value.getClass().getName());
            }
            if (referencedPropertyName == null) {
                throw new AssertionFailure("No property ref found while expected");
            }
            Property synthProp = referencedEntity.getReferencedProperty(referencedPropertyName);
            if (synthProp == null) {
                throw new AssertionFailure("Cannot find synthProp: " + referencedEntity.getEntityName() + "." + referencedPropertyName);
            }
            linkJoinColumnWithValueOverridingNameIfImplicit(referencedEntity, synthProp.getColumnIterator(), columns, value);
        } else {
            if (Ejb3JoinColumn.NO_REFERENCE == fkEnum) {
                //implicit case, we hope PK and FK columns are in the same order
                if (columns.length != referencedEntity.getIdentifier().getColumnSpan()) {
                    throw new AnnotationException("A Foreign key refering " + referencedEntity.getEntityName() + " from " + associatedClass.getEntityName() + " has the wrong number of column. should be " + referencedEntity.getIdentifier().getColumnSpan());
                }
                linkJoinColumnWithValueOverridingNameIfImplicit(referencedEntity, referencedEntity.getIdentifier().getColumnIterator(), columns, value);
            } else {
                //explicit referencedColumnName
                Iterator idColItr = referencedEntity.getKey().getColumnIterator();
                org.hibernate.mapping.Column col;
                //works cause the pk has to be on the primary table
                Table table = referencedEntity.getTable();
                if (!idColItr.hasNext()) {
                    LOG.debug("No column in the identifier!");
                }
                while (idColItr.hasNext()) {
                    boolean match = false;
                    //for each PK column, find the associated FK column.
                    col = (org.hibernate.mapping.Column) idColItr.next();
                    for (Ejb3JoinColumn joinCol : columns) {
                        String referencedColumn = joinCol.getReferencedColumn();
                        referencedColumn = buildingContext.getMetadataCollector().getPhysicalColumnName(table, referencedColumn);
                        //In JPA 2 referencedColumnName is case insensitive
                        if (referencedColumn.equalsIgnoreCase(col.getQuotedName(buildingContext.getMetadataCollector().getDatabase().getJdbcEnvironment().getDialect()))) {
                            //proper join column
                            if (joinCol.isNameDeferred()) {
                                joinCol.linkValueUsingDefaultColumnNaming(col, referencedEntity, value);
                            } else {
                                joinCol.linkWithValue(value);
                            }
                            joinCol.overrideFromReferencedColumnIfNecessary(col);
                            match = true;
                            break;
                        }
                    }
                    if (!match) {
                        throw new AnnotationException("Column name " + col.getName() + " of " + referencedEntity.getEntityName() + " not found in JoinColumns.referencedColumnName");
                    }
                }
            }
        }
    }
    value.createForeignKey();
    if (unique) {
        createUniqueConstraint(value);
    }
}
Also used : AssertionFailure(org.hibernate.AssertionFailure) Table(org.hibernate.mapping.Table) DependantValue(org.hibernate.mapping.DependantValue) Column(org.hibernate.mapping.Column) Ejb3JoinColumn(org.hibernate.cfg.Ejb3JoinColumn) Iterator(java.util.Iterator) SimpleValue(org.hibernate.mapping.SimpleValue) DependantValue(org.hibernate.mapping.DependantValue) Value(org.hibernate.mapping.Value) ToOne(org.hibernate.mapping.ToOne) Collection(org.hibernate.mapping.Collection) AnnotationException(org.hibernate.AnnotationException) Ejb3JoinColumn(org.hibernate.cfg.Ejb3JoinColumn) JoinedSubclass(org.hibernate.mapping.JoinedSubclass) Property(org.hibernate.mapping.Property) PersistentClass(org.hibernate.mapping.PersistentClass)

Example 12 with AssertionFailure

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

the class CopyIdentifierComponentSecondPass method doSecondPass.

@SuppressWarnings({ "unchecked" })
public void doSecondPass(Map persistentClasses) throws MappingException {
    PersistentClass referencedPersistentClass = (PersistentClass) persistentClasses.get(referencedEntityName);
    // TODO better error names
    if (referencedPersistentClass == null) {
        throw new AnnotationException("Unknown entity name: " + referencedEntityName);
    }
    if (!(referencedPersistentClass.getIdentifier() instanceof Component)) {
        throw new AssertionFailure("Unexpected identifier type on the referenced entity when mapping a @MapsId: " + referencedEntityName);
    }
    Component referencedComponent = (Component) referencedPersistentClass.getIdentifier();
    Iterator<Property> properties = referencedComponent.getPropertyIterator();
    //prepare column name structure
    boolean isExplicitReference = true;
    Map<String, Ejb3JoinColumn> columnByReferencedName = new HashMap<String, Ejb3JoinColumn>(joinColumns.length);
    for (Ejb3JoinColumn joinColumn : joinColumns) {
        final String referencedColumnName = joinColumn.getReferencedColumn();
        if (referencedColumnName == null || BinderHelper.isEmptyAnnotationValue(referencedColumnName)) {
            break;
        }
        //JPA 2 requires referencedColumnNames to be case insensitive
        columnByReferencedName.put(referencedColumnName.toLowerCase(Locale.ROOT), joinColumn);
    }
    //try default column orientation
    AtomicInteger index = new AtomicInteger(0);
    if (columnByReferencedName.isEmpty()) {
        isExplicitReference = false;
        for (Ejb3JoinColumn joinColumn : joinColumns) {
            columnByReferencedName.put("" + index.get(), joinColumn);
            index.getAndIncrement();
        }
        index.set(0);
    }
    while (properties.hasNext()) {
        Property referencedProperty = properties.next();
        if (referencedProperty.isComposite()) {
            Property property = createComponentProperty(referencedPersistentClass, isExplicitReference, columnByReferencedName, index, referencedProperty);
            component.addProperty(property);
        } else {
            Property property = createSimpleProperty(referencedPersistentClass, isExplicitReference, columnByReferencedName, index, referencedProperty);
            component.addProperty(property);
        }
    }
}
Also used : AssertionFailure(org.hibernate.AssertionFailure) HashMap(java.util.HashMap) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AnnotationException(org.hibernate.AnnotationException) Component(org.hibernate.mapping.Component) Property(org.hibernate.mapping.Property) PersistentClass(org.hibernate.mapping.PersistentClass)

Example 13 with AssertionFailure

use of org.hibernate.AssertionFailure 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 14 with AssertionFailure

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

the class TypeSafeActivator method applyRelationalConstraints.

@SuppressWarnings({ "UnusedDeclaration" })
public static void applyRelationalConstraints(ValidatorFactory factory, Collection<PersistentClass> persistentClasses, Map settings, Dialect dialect, ClassLoaderAccess classLoaderAccess) {
    Class<?>[] groupsArray = GroupsPerOperation.buildGroupsForOperation(GroupsPerOperation.Operation.DDL, settings, classLoaderAccess);
    Set<Class<?>> groups = new HashSet<Class<?>>(Arrays.asList(groupsArray));
    for (PersistentClass persistentClass : persistentClasses) {
        final String className = persistentClass.getClassName();
        if (className == null || className.length() == 0) {
            continue;
        }
        Class<?> clazz;
        try {
            clazz = classLoaderAccess.classForName(className);
        } catch (ClassLoadingException e) {
            throw new AssertionFailure("Entity class not found", e);
        }
        try {
            applyDDL("", persistentClass, clazz, factory, groups, true, dialect);
        } catch (Exception e) {
            LOG.unableToApplyConstraints(className, e);
        }
    }
}
Also used : AssertionFailure(org.hibernate.AssertionFailure) ClassLoadingException(org.hibernate.boot.registry.classloading.spi.ClassLoadingException) PersistentClass(org.hibernate.mapping.PersistentClass) MappingException(org.hibernate.MappingException) ClassLoadingException(org.hibernate.boot.registry.classloading.spi.ClassLoadingException) HashSet(java.util.HashSet) PersistentClass(org.hibernate.mapping.PersistentClass)

Example 15 with AssertionFailure

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

the class JoinSequence method toJoinFragment.

public JoinFragment toJoinFragment(Map enabledFilters, boolean includeAllSubclassJoins, boolean renderSubclassJoins, String withClauseFragment) throws MappingException {
    final QueryJoinFragment joinFragment = new QueryJoinFragment(factory.getDialect(), useThetaStyle);
    Iterator<Join> iter;
    Join first;
    Joinable last;
    if (rootJoinable != null) {
        joinFragment.addCrossJoin(rootJoinable.getTableName(), rootAlias);
        final String filterCondition = rootJoinable.filterFragment(rootAlias, enabledFilters, treatAsDeclarations);
        // JoinProcessor needs to know if the where clause fragment came from a dynamic filter or not so it
        // can put the where clause fragment in the right place in the SQL AST.   'hasFilterCondition' keeps track
        // of that fact.
        joinFragment.setHasFilterCondition(joinFragment.addCondition(filterCondition));
        addSubclassJoins(joinFragment, rootAlias, rootJoinable, true, includeAllSubclassJoins, treatAsDeclarations);
        last = rootJoinable;
    } else if (needsTableGroupJoin(joins, withClauseFragment)) {
        iter = joins.iterator();
        first = iter.next();
        final String joinString;
        switch(first.joinType) {
            case INNER_JOIN:
                joinString = " inner join ";
                break;
            case LEFT_OUTER_JOIN:
                joinString = " left outer join ";
                break;
            case RIGHT_OUTER_JOIN:
                joinString = " right outer join ";
                break;
            case FULL_JOIN:
                joinString = " full outer join ";
                break;
            default:
                throw new AssertionFailure("undefined join type");
        }
        joinFragment.addFromFragmentString(joinString);
        joinFragment.addFromFragmentString(" (");
        joinFragment.addFromFragmentString(first.joinable.getTableName());
        joinFragment.addFromFragmentString(" ");
        joinFragment.addFromFragmentString(first.getAlias());
        for (Join join : joins) {
            // Skip joining the first join node as it is contained in the subquery
            if (join != first) {
                joinFragment.addJoin(join.getJoinable().getTableName(), join.getAlias(), join.getLHSColumns(), JoinHelper.getRHSColumnNames(join.getAssociationType(), factory), join.joinType, "");
            }
            addSubclassJoins(joinFragment, join.getAlias(), join.getJoinable(), // TODO: Think about if this could be made always true
            join.joinType == JoinType.INNER_JOIN, includeAllSubclassJoins, // builds the JoinSequence for HQL joins
            treatAsDeclarations);
        }
        joinFragment.addFromFragmentString(")");
        joinFragment.addFromFragmentString(" on ");
        final String rhsAlias = first.getAlias();
        final String[] lhsColumns = first.getLHSColumns();
        final String[] rhsColumns = JoinHelper.getRHSColumnNames(first.getAssociationType(), factory);
        for (int j = 0; j < lhsColumns.length; j++) {
            joinFragment.addFromFragmentString(lhsColumns[j]);
            joinFragment.addFromFragmentString("=");
            joinFragment.addFromFragmentString(rhsAlias);
            joinFragment.addFromFragmentString(".");
            joinFragment.addFromFragmentString(rhsColumns[j]);
            if (j < lhsColumns.length - 1) {
                joinFragment.addFromFragmentString(" and ");
            }
        }
        joinFragment.addFromFragmentString(" and ");
        joinFragment.addFromFragmentString(withClauseFragment);
        return joinFragment;
    } else {
        last = null;
    }
    for (Join join : joins) {
        // technically the treatAsDeclarations should only apply to rootJoinable or to a single Join,
        // but that is not possible atm given how these JoinSequence and Join objects are built.
        // However, it is generally ok given how the HQL parser builds these JoinSequences (a HQL join
        // results in a JoinSequence with an empty rootJoinable and a single Join).  So we use that here
        // as an assumption
        final String on = join.getAssociationType().getOnCondition(join.getAlias(), factory, enabledFilters, treatAsDeclarations);
        String condition;
        if (last != null && isManyToManyRoot(last) && ((QueryableCollection) last).getElementType() == join.getAssociationType()) {
            // the current join represents the join between a many-to-many association table
            // and its "target" table.  Here we need to apply any additional filters
            // defined specifically on the many-to-many
            final String manyToManyFilter = ((QueryableCollection) last).getManyToManyFilterFragment(join.getAlias(), enabledFilters);
            condition = "".equals(manyToManyFilter) ? on : "".equals(on) ? manyToManyFilter : on + " and " + manyToManyFilter;
        } else {
            condition = on;
        }
        if (withClauseFragment != null && !isManyToManyRoot(join.joinable)) {
            condition += " and " + withClauseFragment;
        }
        joinFragment.addJoin(join.getJoinable().getTableName(), join.getAlias(), join.getLHSColumns(), JoinHelper.getRHSColumnNames(join.getAssociationType(), factory), join.joinType, condition);
        if (renderSubclassJoins) {
            addSubclassJoins(joinFragment, join.getAlias(), join.getJoinable(), join.joinType == JoinType.INNER_JOIN, includeAllSubclassJoins, // builds the JoinSequence for HQL joins
            treatAsDeclarations);
        }
        last = join.getJoinable();
    }
    if (next != null) {
        joinFragment.addFragment(next.toJoinFragment(enabledFilters, includeAllSubclassJoins));
    }
    joinFragment.addCondition(conditions.toString());
    if (isFromPart) {
        joinFragment.clearWherePart();
    }
    return joinFragment;
}
Also used : AssertionFailure(org.hibernate.AssertionFailure) QueryJoinFragment(org.hibernate.sql.QueryJoinFragment) Joinable(org.hibernate.persister.entity.Joinable) QueryableCollection(org.hibernate.persister.collection.QueryableCollection)

Aggregations

AssertionFailure (org.hibernate.AssertionFailure)54 EntityEntry (org.hibernate.engine.spi.EntityEntry)11 Serializable (java.io.Serializable)10 Property (org.hibernate.mapping.Property)10 AnnotationException (org.hibernate.AnnotationException)8 PersistentClass (org.hibernate.mapping.PersistentClass)7 EntityPersister (org.hibernate.persister.entity.EntityPersister)7 SQLException (java.sql.SQLException)6 HibernateException (org.hibernate.HibernateException)6 SimpleValue (org.hibernate.mapping.SimpleValue)6 PreparedStatement (java.sql.PreparedStatement)5 HashMap (java.util.HashMap)5 Component (org.hibernate.mapping.Component)5 Join (org.hibernate.mapping.Join)5 SyntheticProperty (org.hibernate.mapping.SyntheticProperty)5 Iterator (java.util.Iterator)4 EntityRegionAccessStrategy (org.hibernate.cache.spi.access.EntityRegionAccessStrategy)4 PersistenceContext (org.hibernate.engine.spi.PersistenceContext)4 SharedSessionContractImplementor (org.hibernate.engine.spi.SharedSessionContractImplementor)4 ManyToOne (org.hibernate.mapping.ManyToOne)4