Search in sources :

Example 6 with JoinTable

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

the class JPAXMLOverriddenAnnotationReader method overridesDefaultsInJoinTable.

private JoinTable overridesDefaultsInJoinTable(Annotation annotation, XMLContext.Default defaults) {
    // no element but might have some default or some annotation
    boolean defaultToJoinTable = !(isPhysicalAnnotationPresent(JoinColumn.class) || isPhysicalAnnotationPresent(JoinColumns.class));
    final Class<? extends Annotation> annotationClass = annotation.annotationType();
    defaultToJoinTable = defaultToJoinTable && ((annotationClass == ManyToMany.class && StringHelper.isEmpty(((ManyToMany) annotation).mappedBy())) || (annotationClass == OneToMany.class && StringHelper.isEmpty(((OneToMany) annotation).mappedBy())) || (annotationClass == ElementCollection.class));
    final Class<JoinTable> annotationType = JoinTable.class;
    if (defaultToJoinTable && (StringHelper.isNotEmpty(defaults.getCatalog()) || StringHelper.isNotEmpty(defaults.getSchema()))) {
        AnnotationDescriptor ad = new AnnotationDescriptor(annotationType);
        if (defaults.canUseJavaAnnotations()) {
            JoinTable table = getPhysicalAnnotation(annotationType);
            if (table != null) {
                ad.setValue("name", table.name());
                ad.setValue("schema", table.schema());
                ad.setValue("catalog", table.catalog());
                ad.setValue("uniqueConstraints", table.uniqueConstraints());
                ad.setValue("joinColumns", table.joinColumns());
                ad.setValue("inverseJoinColumns", table.inverseJoinColumns());
            }
        }
        if (StringHelper.isEmpty((String) ad.valueOf("schema")) && StringHelper.isNotEmpty(defaults.getSchema())) {
            ad.setValue("schema", defaults.getSchema());
        }
        if (StringHelper.isEmpty((String) ad.valueOf("catalog")) && StringHelper.isNotEmpty(defaults.getCatalog())) {
            ad.setValue("catalog", defaults.getCatalog());
        }
        return AnnotationFactory.create(ad);
    } else if (defaults.canUseJavaAnnotations()) {
        return getPhysicalAnnotation(annotationType);
    } else {
        return null;
    }
}
Also used : AnnotationDescriptor(org.hibernate.annotations.common.annotationfactory.AnnotationDescriptor) JaxbPrimaryKeyJoinColumn(org.hibernate.boot.jaxb.mapping.spi.JaxbPrimaryKeyJoinColumn) JaxbMapKeyJoinColumn(org.hibernate.boot.jaxb.mapping.spi.JaxbMapKeyJoinColumn) PrimaryKeyJoinColumn(jakarta.persistence.PrimaryKeyJoinColumn) MapKeyJoinColumn(jakarta.persistence.MapKeyJoinColumn) JoinColumn(jakarta.persistence.JoinColumn) JaxbJoinColumn(org.hibernate.boot.jaxb.mapping.spi.JaxbJoinColumn) PrimaryKeyJoinColumns(jakarta.persistence.PrimaryKeyJoinColumns) MapKeyJoinColumns(jakarta.persistence.MapKeyJoinColumns) JoinColumns(jakarta.persistence.JoinColumns) ManyToMany(jakarta.persistence.ManyToMany) JaxbManyToMany(org.hibernate.boot.jaxb.mapping.spi.JaxbManyToMany) ElementCollection(jakarta.persistence.ElementCollection) JaxbElementCollection(org.hibernate.boot.jaxb.mapping.spi.JaxbElementCollection) JaxbOneToMany(org.hibernate.boot.jaxb.mapping.spi.JaxbOneToMany) OneToMany(jakarta.persistence.OneToMany) JaxbJoinTable(org.hibernate.boot.jaxb.mapping.spi.JaxbJoinTable) JoinTable(jakarta.persistence.JoinTable)

Example 7 with JoinTable

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

the class CollectionBinder method handleCollectionOfEntities.

private ManyToOne handleCollectionOfEntities(Collection collValue, XClass collType, boolean ignoreNotFound, XProperty property, MetadataBuildingContext buildingContext, PersistentClass collectionEntity, String hqlOrderBy) {
    ManyToOne element;
    element = new ManyToOne(buildingContext, collValue.getCollectionTable());
    collValue.setElement(element);
    element.setReferencedEntityName(collType.getName());
    // element.setFetchMode( fetchMode );
    // element.setLazy( fetchMode != FetchMode.JOIN );
    // make the second join non lazy
    element.setFetchMode(FetchMode.JOIN);
    element.setLazy(false);
    element.setIgnoreNotFound(ignoreNotFound);
    // as per 11.1.38 of JPA 2.0 spec, default to primary key if no column is specified by @OrderBy.
    if (hqlOrderBy != null) {
        collValue.setManyToManyOrdering(buildOrderByClauseFromHql(hqlOrderBy, collectionEntity));
    }
    final ForeignKey fk = property.getAnnotation(ForeignKey.class);
    if (fk != null && !isEmptyAnnotationValue(fk.name())) {
        element.setForeignKeyName(fk.name());
    } else {
        final JoinTable joinTableAnn = property.getAnnotation(JoinTable.class);
        if (joinTableAnn != null) {
            String foreignKeyName = joinTableAnn.inverseForeignKey().name();
            String foreignKeyDefinition = joinTableAnn.inverseForeignKey().foreignKeyDefinition();
            if (joinTableAnn.inverseJoinColumns().length != 0) {
                final JoinColumn joinColumnAnn = joinTableAnn.inverseJoinColumns()[0];
                if (foreignKeyName != null && foreignKeyName.isEmpty()) {
                    foreignKeyName = joinColumnAnn.foreignKey().name();
                    foreignKeyDefinition = joinColumnAnn.foreignKey().foreignKeyDefinition();
                }
            }
            if (joinTableAnn.inverseForeignKey().value() == ConstraintMode.NO_CONSTRAINT || joinTableAnn.inverseForeignKey().value() == ConstraintMode.PROVIDER_DEFAULT && buildingContext.getBuildingOptions().isNoConstraintByDefault()) {
                element.disableForeignKey();
            } else {
                element.setForeignKeyName(StringHelper.nullIfEmpty(foreignKeyName));
                element.setForeignKeyDefinition(StringHelper.nullIfEmpty(foreignKeyDefinition));
            }
        }
    }
    return element;
}
Also used : JoinColumn(jakarta.persistence.JoinColumn) AnnotatedJoinColumn(org.hibernate.cfg.AnnotatedJoinColumn) ForeignKey(org.hibernate.annotations.ForeignKey) ManyToOne(org.hibernate.mapping.ManyToOne) JoinTable(jakarta.persistence.JoinTable) WhereJoinTable(org.hibernate.annotations.WhereJoinTable) FilterJoinTable(org.hibernate.annotations.FilterJoinTable)

Example 8 with JoinTable

use of jakarta.persistence.JoinTable 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 Object joinColumns;
    final List<UniqueConstraintHolder> uniqueConstraintHolders;
    final QualifiedTableName logicalName;
    if (secondaryTable != null) {
        schema = secondaryTable.schema();
        catalog = secondaryTable.catalog();
        logicalName = new QualifiedTableName(Identifier.toIdentifier(catalog), Identifier.toIdentifier(schema), 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 = new QualifiedTableName(Identifier.toIdentifier(catalog), Identifier.toIdentifier(schema), 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.getTableName(), 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 : QualifiedTableName(org.hibernate.boot.model.relational.QualifiedTableName) UniqueConstraintHolder(org.hibernate.cfg.UniqueConstraintHolder) AssertionFailure(org.hibernate.AssertionFailure) SecondaryTable(jakarta.persistence.SecondaryTable) JoinTable(jakarta.persistence.JoinTable) Table(org.hibernate.mapping.Table) Join(org.hibernate.mapping.Join) InFlightMetadataCollector(org.hibernate.boot.spi.InFlightMetadataCollector)

Example 9 with JoinTable

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

the class CollectionBinder method handleUnownedManyToMany.

private void handleUnownedManyToMany(Collection collValue, AnnotatedJoinColumn[] joinColumns, XClass collType, PersistentClass collectionEntity, boolean isCollectionOfEntities) {
    if (!isCollectionOfEntities) {
        throw new AnnotationException("Collection of elements must not have mappedBy or association reference an unmapped entity: " + collValue.getOwnerEntityName() + "." + joinColumns[0].getPropertyName());
    }
    Property otherSideProperty;
    try {
        otherSideProperty = collectionEntity.getRecursiveProperty(joinColumns[0].getMappedBy());
    } catch (MappingException e) {
        throw new AnnotationException("mappedBy references an unknown target entity property: " + collType + "." + joinColumns[0].getMappedBy() + " in " + collValue.getOwnerEntityName() + "." + joinColumns[0].getPropertyName());
    }
    Table table;
    if (otherSideProperty.getValue() instanceof Collection) {
        // this is a collection on the other side
        table = ((Collection) otherSideProperty.getValue()).getCollectionTable();
    } else {
        // This is a ToOne with a @JoinTable or a regular property
        table = otherSideProperty.getValue().getTable();
    }
    collValue.setCollectionTable(table);
    String entityName = collectionEntity.getEntityName();
    for (AnnotatedJoinColumn column : joinColumns) {
        // column.setDefaultColumnHeader( joinColumns[0].getMappedBy() ); //seems not to be used, make sense
        column.setManyToManyOwnerSideEntityName(entityName);
    }
}
Also used : CollectionTable(jakarta.persistence.CollectionTable) JoinTable(jakarta.persistence.JoinTable) WhereJoinTable(org.hibernate.annotations.WhereJoinTable) Table(org.hibernate.mapping.Table) FilterJoinTable(org.hibernate.annotations.FilterJoinTable) AnnotationException(org.hibernate.AnnotationException) LazyCollection(org.hibernate.annotations.LazyCollection) ElementCollection(jakarta.persistence.ElementCollection) Collection(org.hibernate.mapping.Collection) AnnotatedJoinColumn(org.hibernate.cfg.AnnotatedJoinColumn) Property(org.hibernate.mapping.Property) XProperty(org.hibernate.annotations.common.reflection.XProperty) MappingException(org.hibernate.MappingException)

Example 10 with JoinTable

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

the class Ejb3XmlOneToOneTest method testJoinTableAllChildren.

@Test
public void testJoinTableAllChildren() throws Exception {
    reader = getReader(Entity1.class, "field1", "one-to-one.orm7.xml");
    assertAnnotationPresent(OneToOne.class);
    assertAnnotationNotPresent(PrimaryKeyJoinColumn.class);
    assertAnnotationNotPresent(PrimaryKeyJoinColumns.class);
    assertAnnotationPresent(JoinTable.class);
    assertAnnotationNotPresent(JoinColumns.class);
    assertAnnotationNotPresent(JoinColumn.class);
    JoinTable joinTableAnno = reader.getAnnotation(JoinTable.class);
    assertEquals("cat1", joinTableAnno.catalog());
    assertEquals("table1", joinTableAnno.name());
    assertEquals("schema1", joinTableAnno.schema());
    // JoinColumns
    JoinColumn[] joinColumns = joinTableAnno.joinColumns();
    assertEquals(2, joinColumns.length);
    assertEquals("", joinColumns[0].name());
    assertEquals("", joinColumns[0].referencedColumnName());
    assertEquals("", joinColumns[0].table());
    assertEquals("", joinColumns[0].columnDefinition());
    assertTrue(joinColumns[0].insertable());
    assertTrue(joinColumns[0].updatable());
    assertTrue(joinColumns[0].nullable());
    assertFalse(joinColumns[0].unique());
    assertEquals("col1", joinColumns[1].name());
    assertEquals("col2", joinColumns[1].referencedColumnName());
    assertEquals("table2", joinColumns[1].table());
    assertEquals("int", joinColumns[1].columnDefinition());
    assertFalse(joinColumns[1].insertable());
    assertFalse(joinColumns[1].updatable());
    assertFalse(joinColumns[1].nullable());
    assertTrue(joinColumns[1].unique());
    // InverseJoinColumns
    JoinColumn[] inverseJoinColumns = joinTableAnno.inverseJoinColumns();
    assertEquals(2, inverseJoinColumns.length);
    assertEquals("", inverseJoinColumns[0].name());
    assertEquals("", inverseJoinColumns[0].referencedColumnName());
    assertEquals("", inverseJoinColumns[0].table());
    assertEquals("", inverseJoinColumns[0].columnDefinition());
    assertTrue(inverseJoinColumns[0].insertable());
    assertTrue(inverseJoinColumns[0].updatable());
    assertTrue(inverseJoinColumns[0].nullable());
    assertFalse(inverseJoinColumns[0].unique());
    assertEquals("col3", inverseJoinColumns[1].name());
    assertEquals("col4", inverseJoinColumns[1].referencedColumnName());
    assertEquals("table3", inverseJoinColumns[1].table());
    assertEquals("int", inverseJoinColumns[1].columnDefinition());
    assertFalse(inverseJoinColumns[1].insertable());
    assertFalse(inverseJoinColumns[1].updatable());
    assertFalse(inverseJoinColumns[1].nullable());
    assertTrue(inverseJoinColumns[1].unique());
    // UniqueConstraints
    UniqueConstraint[] uniqueConstraints = joinTableAnno.uniqueConstraints();
    assertEquals(2, uniqueConstraints.length);
    assertEquals("", uniqueConstraints[0].name());
    assertEquals(1, uniqueConstraints[0].columnNames().length);
    assertEquals("col5", uniqueConstraints[0].columnNames()[0]);
    assertEquals("uq1", uniqueConstraints[1].name());
    assertEquals(2, uniqueConstraints[1].columnNames().length);
    assertEquals("col6", uniqueConstraints[1].columnNames()[0]);
    assertEquals("col7", uniqueConstraints[1].columnNames()[1]);
}
Also used : JoinColumn(jakarta.persistence.JoinColumn) PrimaryKeyJoinColumn(jakarta.persistence.PrimaryKeyJoinColumn) UniqueConstraint(jakarta.persistence.UniqueConstraint) JoinTable(jakarta.persistence.JoinTable) Test(org.junit.Test)

Aggregations

JoinTable (jakarta.persistence.JoinTable)23 JoinColumn (jakarta.persistence.JoinColumn)11 Test (org.junit.Test)9 MapKeyJoinColumn (jakarta.persistence.MapKeyJoinColumn)7 UniqueConstraint (jakarta.persistence.UniqueConstraint)6 PrimaryKeyJoinColumn (jakarta.persistence.PrimaryKeyJoinColumn)5 AnnotationException (org.hibernate.AnnotationException)5 OnDelete (org.hibernate.annotations.OnDelete)4 Join (org.hibernate.mapping.Join)4 AssociationOverride (jakarta.persistence.AssociationOverride)3 CollectionTable (jakarta.persistence.CollectionTable)3 JoinColumns (jakarta.persistence.JoinColumns)3 MapKeyJoinColumns (jakarta.persistence.MapKeyJoinColumns)3 PrimaryKeyJoinColumns (jakarta.persistence.PrimaryKeyJoinColumns)3 Cascade (org.hibernate.annotations.Cascade)3 FilterJoinTable (org.hibernate.annotations.FilterJoinTable)3 WhereJoinTable (org.hibernate.annotations.WhereJoinTable)3 AnnotatedJoinColumn (org.hibernate.cfg.AnnotatedJoinColumn)3 Column (jakarta.persistence.Column)2 DiscriminatorColumn (jakarta.persistence.DiscriminatorColumn)2