You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@grails.apache.org by bo...@apache.org on 2026/10/09 13:50:58 UTC
(grails-core) branch fix/hibernate7-composite-fk-column-types-8.0.x updated (2d921e99dd -> 0b0be81a04)
This is an automated email from the ASF dual-hosted git repository.
borinquenkid pushed a change to branch fix/hibernate7-composite-fk-column-types-8.0.x
in repository https://gitbox.apache.org/repos/asf/grails-core.git
from 2d921e99dd fix: permute the columns of a composite identifier by part, not by property
new 289e98ace8 test: reference a composite key whose multi-column part sits between two plain parts
new 0b0be81a04 fix: sort a composite foreign key once the identifier it references is bound
The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
.../CompositeIdentifierToManyToOneBinder.java | 91 ++++++++++++++-
.../domainbinding/binder/GrailsDomainBinder.java | 1 +
.../hibernate/GrailsHibernatePersistentEntity.java | 4 +-
.../secondpass/CompositeForeignKeySecondPass.java | 67 +++++++++++
.../util/PropertyFromValueCreator.java | 18 ++-
.../cfg/domainbinding/CollectionBinderSpec.groovy | 2 +-
...CompositeIdentifierToManyToOneBinderSpec.groovy | 83 ++++++++++++-
.../domainbinding/GrailsPropertyBinderSpec.groovy | 1 +
.../PropertyFromValueCreatorSpec.groovy | 32 ++++++
.../CompositeForeignKeyColumnTypesSpec.groovy | 77 +++++++------
...CompositeForeignKeyRegistrationOrderSpec.groovy | 128 +++++++++++++++++++++
.../domainbinding/binder/ForeignKeyPairs.groovy | 55 +++++++++
.../secondpass/CollectionKeyBinderSpec.groovy | 2 +-
.../secondpass/ListSecondPassBinderSpec.groovy | 2 +-
.../secondpass/MapSecondPassBinderSpec.groovy | 2 +-
15 files changed, 520 insertions(+), 45 deletions(-)
create mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CompositeForeignKeySecondPass.java
create mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeForeignKeyRegistrationOrderSpec.groovy
create mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ForeignKeyPairs.groovy
(grails-core) 01/02: test: reference a composite key whose multi-column part sits between two plain parts
Posted by bo...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
borinquenkid pushed a commit to branch fix/hibernate7-composite-fk-column-types-8.0.x
in repository https://gitbox.apache.org/repos/asf/grails-core.git
commit 289e98ace89d97e1778706ddf0cdb8d7b336daf2
Author: Walter Duque de Estrada <wb...@mac.com>
AuthorDate: Thu Oct 8 21:51:52 2026 -0500
test: reference a composite key whose multi-column part sits between two plain parts
The two PrbSpanLeaf features checked the same PrbLeaf -> PrbMiddle key as the
features before them: composite('zed', 'middle', 'ace') only laid out
PrbSpanLeaf's own primary key, which Hibernate orders itself and nothing
references, so the column-span permutation of a multi-column part between two
plain parts never ran. PrbHubRef and the join table of PrbHub's unidirectional
one-to-many now reference such a key, so both the many-to-one and the
collection paths assert the KEY_SEQ pairs, and a hub with a tag and a
reference is saved and reloaded. With the plain property permutation the
pairs come out crossed and the save fails.
Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
---
.../CompositeForeignKeyColumnTypesSpec.groovy | 59 +++++++++++++++-------
1 file changed, 42 insertions(+), 17 deletions(-)
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeForeignKeyColumnTypesSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeForeignKeyColumnTypesSpec.groovy
index c878e9ce16..fa7726717d 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeForeignKeyColumnTypesSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeForeignKeyColumnTypesSpec.groovy
@@ -47,7 +47,7 @@ class CompositeForeignKeyColumnTypesSpec extends Specification {
],
CfkParent, CfkChild, CfkGrandParent, CfkMiddle, CfkLeaf,
CfkOrdParent, CfkOrdChild, CfkOrdGrand, CfkOrdMiddle, CfkOrdLeaf,
- PrbGrand, PrbMiddle, PrbLeaf, PrbSpanLeaf)
+ PrbGrand, PrbMiddle, PrbLeaf, PrbHub, PrbHubTag, PrbHubRef)
private List<List> columns(String table) {
List<List> rows = []
@@ -219,28 +219,41 @@ class CompositeForeignKeyColumnTypesSpec extends Specification {
}
}
- void "a multi-column nested part between two plain parts keeps its columns together in key order"() {
- expect: 'the key is declared as zed, middle, ace, so the three column middle part sorts between the two plain parts'
- foreignKeyPairs('PRB_SPAN_LEAF') == [
- prb_middle: [
- ['prb_middle_grand_parent_alpha', 'prb_grand_alpha'],
- ['prb_middle_grand_parent_zeta', 'prb_grand_zeta'],
- ['prb_middle_name', 'name']]
+ void "the keys that reference a multi-column nested part between two plain parts move it with all of its columns"() {
+ expect: 'the hub key is declared as zed, grand, ace, so the two column grand part sorts between the two plain parts'
+ foreignKeyPairs('PRB_HUB_REF') == [
+ prb_hub: [
+ ['prb_hub_ace', 'ace'],
+ ['prb_hub_grand_alpha', 'prb_grand_alpha'],
+ ['prb_hub_grand_zeta', 'prb_grand_zeta'],
+ ['prb_hub_zed', 'zed']]
+ ]
+
+ and: 'the join table of the unidirectional one-to-many references the hub by the same key'
+ foreignKeyPairs('PRB_HUB_PRB_HUB_TAG') == [
+ prb_hub: [
+ ['prb_hub_ace', 'ace'],
+ ['prb_hub_grand_alpha', 'prb_grand_alpha'],
+ ['prb_hub_grand_zeta', 'prb_grand_zeta'],
+ ['prb_hub_zed', 'zed']],
+ prb_hub_tag: [['prb_hub_tag_id', 'id']]
]
}
- void "a leaf whose multi-column nested part sorts between two plain parts is saved and reloaded"() {
+ void "a hub whose multi-column nested part sorts between two plain parts is saved with a tag and a reference and reloaded"() {
when:
PrbGrand.withNewTransaction {
PrbGrand grand = new PrbGrand(zeta: 'z2', alpha: 'a2').save(failOnError: true)
- PrbMiddle middle = new PrbMiddle(name: 'm2', grandParent: grand).save(failOnError: true)
- new PrbSpanLeaf(zed: 'zz', ace: 'aa', middle: middle).save(failOnError: true, flush: true)
+ PrbHub hub = new PrbHub(zed: 'zz', ace: 'aa', grand: grand)
+ .addToTags(new PrbHubTag(label: 'tag'))
+ .save(failOnError: true)
+ new PrbHubRef(name: 'ref', hub: hub).save(failOnError: true, flush: true)
}
then:
- PrbSpanLeaf.withNewSession {
- PrbSpanLeaf leaf = PrbSpanLeaf.findByZed('zz')
- leaf.ace == 'aa' && leaf.middle.name == 'm2' && leaf.middle.grandParent.zeta == 'z2'
+ PrbHubRef.withNewSession {
+ PrbHubRef ref = PrbHubRef.findByName('ref')
+ ref.hub.zed == 'zz' && ref.hub.ace == 'aa' && ref.hub.grand.zeta == 'z2' && ref.hub.tags*.label == ['tag']
}
}
}
@@ -278,16 +291,28 @@ class PrbLeaf implements Serializable {
}
@Entity
-class PrbSpanLeaf implements Serializable {
+class PrbHub implements Serializable {
String zed
String ace
- PrbMiddle middle
+ PrbGrand grand
+ static hasMany = [tags: PrbHubTag]
static mapping = MappingBuilder.define {
- composite('zed', 'middle', 'ace')
+ composite('zed', 'grand', 'ace')
}
}
+@Entity
+class PrbHubTag {
+ String label
+}
+
+@Entity
+class PrbHubRef {
+ String name
+ PrbHub hub
+}
+
@Entity
class CfkParent implements Serializable {
String name
(grails-core) 02/02: fix: sort a composite foreign key once the identifier it references is bound
Posted by bo...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
borinquenkid pushed a commit to branch fix/hibernate7-composite-fk-column-types-8.0.x
in repository https://gitbox.apache.org/repos/asf/grails-core.git
commit 0b0be81a047af4126332c8b01b032794ec7219f1
Author: Walter Duque de Estrada <wb...@mac.com>
AuthorDate: Thu Oct 8 23:09:57 2026 -0500
fix: sort a composite foreign key once the identifier it references is bound
CompositeIdentifierToManyToOneBinder sorted a key against the referenced
composite identifier while binding the property. When the referenced entity
had not been bound yet, the columns kept their declared order, got sequential
type indexes and were marked sorted, so Hibernate's own ToOne.sortProperties()
skipped them too, and PropertyFromValueCreator created Hibernate's foreign key,
which pairs the columns by position. Whether a key came out right therefore
depended on the registration order of the entities, which an application does
not choose: PrbGrand, PrbLeaf, PrbMiddle left the leaf's key in declared order
while its values were bound in key order, and saving a leaf failed with a
referential integrity violation; a middle registered before its grand parent
crossed the alpha and zeta columns of every key referencing it.
The binder now aligns a key only once the referenced identifier is bound, down
to the identifiers its to-one parts reference. Otherwise it registers a
CompositeForeignKeySecondPass through InFlightMetadataCollector.addSecondPass,
the mechanism the binder already uses for collections, which Hibernate runs
before it compiles the foreign keys; this mirrors ToOne.sortProperties(), which
resolves the referenced identifier lazily from the second passes. The alignment
is idempotent and aligns the pending to-one parts of the referenced identifier
first, so a key referencing a middle whose own key is still pending sees the
middle's sorted columns; a key bound during the second passes is aligned at
once. PropertyFromValueCreator leaves the foreign key of a many-to-one to a
composite identifier to the composite binder, which pairs each column with the
identifier column it references; for a referenced entity registered first the
binder had already disabled Hibernate's key, so those keys are unchanged.
CompositeForeignKeyRegistrationOrderSpec boots the entities of
CompositeForeignKeyColumnTypesSpec in five registration orders and asserts the
KEY_SEQ pairs and a save and reload; four of them failed before this change.
Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
---
.../CompositeIdentifierToManyToOneBinder.java | 91 ++++++++++++++-
.../domainbinding/binder/GrailsDomainBinder.java | 1 +
.../hibernate/GrailsHibernatePersistentEntity.java | 4 +-
.../secondpass/CompositeForeignKeySecondPass.java | 67 +++++++++++
.../util/PropertyFromValueCreator.java | 18 ++-
.../cfg/domainbinding/CollectionBinderSpec.groovy | 2 +-
...CompositeIdentifierToManyToOneBinderSpec.groovy | 83 ++++++++++++-
.../domainbinding/GrailsPropertyBinderSpec.groovy | 1 +
.../PropertyFromValueCreatorSpec.groovy | 32 ++++++
.../CompositeForeignKeyColumnTypesSpec.groovy | 18 +--
...CompositeForeignKeyRegistrationOrderSpec.groovy | 128 +++++++++++++++++++++
.../domainbinding/binder/ForeignKeyPairs.groovy | 55 +++++++++
.../secondpass/CollectionKeyBinderSpec.groovy | 2 +-
.../secondpass/ListSecondPassBinderSpec.groovy | 2 +-
.../secondpass/MapSecondPassBinderSpec.groovy | 2 +-
15 files changed, 478 insertions(+), 28 deletions(-)
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeIdentifierToManyToOneBinder.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeIdentifierToManyToOneBinder.java
index 324c54d7be..fdb99f69cb 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeIdentifierToManyToOneBinder.java
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeIdentifierToManyToOneBinder.java
@@ -26,10 +26,14 @@ import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
+import org.hibernate.boot.spi.InFlightMetadataCollector;
import org.hibernate.boot.spi.MetadataBuildingContext;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.hibernate.mapping.Column;
+import org.hibernate.mapping.Component;
+import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.SimpleValue;
+import org.hibernate.mapping.ToOne;
import org.grails.orm.hibernate.cfg.ColumnConfig;
import org.grails.orm.hibernate.cfg.HibernateCompositeIdentity;
@@ -37,6 +41,7 @@ import org.grails.orm.hibernate.cfg.PersistentEntityNamingStrategy;
import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity;
import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty;
import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToOneProperty;
+import org.grails.orm.hibernate.cfg.domainbinding.secondpass.CompositeForeignKeySecondPass;
import org.grails.orm.hibernate.cfg.domainbinding.util.BackticksRemover;
import org.grails.orm.hibernate.cfg.domainbinding.util.DefaultColumnNameFetcher;
import org.grails.orm.hibernate.cfg.domainbinding.util.ForeignKeyColumnCountCalculator;
@@ -46,6 +51,7 @@ import static org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsDomainBind
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
public class CompositeIdentifierToManyToOneBinder {
+ private final InFlightMetadataCollector metadataCollector;
private final ForeignKeyColumnCountCalculator foreignKeyColumnCountCalculator;
private final PersistentEntityNamingStrategy namingStrategy;
private final DefaultColumnNameFetcher defaultColumnNameFetcher;
@@ -53,11 +59,13 @@ public class CompositeIdentifierToManyToOneBinder {
private final SimpleValueBinder simpleValueBinder;
public CompositeIdentifierToManyToOneBinder(
+ InFlightMetadataCollector metadataCollector,
ForeignKeyColumnCountCalculator foreignKeyColumnCountCalculator,
PersistentEntityNamingStrategy namingStrategy,
DefaultColumnNameFetcher defaultColumnNameFetcher,
BackticksRemover backticksRemover,
SimpleValueBinder simpleValueBinder) {
+ this.metadataCollector = metadataCollector;
this.foreignKeyColumnCountCalculator = foreignKeyColumnCountCalculator;
this.namingStrategy = namingStrategy;
this.defaultColumnNameFetcher = defaultColumnNameFetcher;
@@ -70,6 +78,7 @@ public class CompositeIdentifierToManyToOneBinder {
PersistentEntityNamingStrategy namingStrategy,
JdbcEnvironment jdbcEnvironment) {
this(
+ metadataBuildingContext.getMetadataCollector(),
new ForeignKeyColumnCountCalculator(),
namingStrategy,
new DefaultColumnNameFetcher(namingStrategy),
@@ -104,15 +113,91 @@ public class CompositeIdentifierToManyToOneBinder {
.forEach(columns::add);
}
simpleValueBinder.bindSimpleValue(property, null, value, path);
+ if (metadataCollector.isInSecondPass() || isIdentifierBound(refDomainClass)) {
+ alignWithReferencedIdentifier(property, value, compositeId, refDomainClass);
+ } else {
+ // The referenced identifier is bound later in this pass. Hibernate sorts a to-one against
+ // the identifier it references lazily, from its second passes, so do the same.
+ metadataCollector.addSecondPass(
+ new CompositeForeignKeySecondPass(this, property, value, compositeId, refDomainClass));
+ }
+ }
+
+ /**
+ * Aligns the columns of {@code value} with the composite identifier of {@code refDomainClass}:
+ * sorts them the way Hibernate sorts that identifier, creates the foreign key against the matching
+ * identifier columns and marks the value sorted. A to-one part of the referenced identifier that
+ * still awaits its own alignment is aligned first, because its columns are the columns this key
+ * references. Does nothing for a to-one that is sorted already.
+ *
+ * @param property the property the key belongs to
+ * @param value the foreign-key value bound for {@code property}
+ * @param compositeId the composite identity of the referenced entity
+ * @param refDomainClass the referenced entity
+ */
+ public void alignWithReferencedIdentifier(
+ HibernatePersistentProperty property,
+ SimpleValue value,
+ HibernateCompositeIdentity compositeId,
+ GrailsHibernatePersistentEntity refDomainClass) {
+ if (value instanceof ToOne toOne && toOne.isSorted()) {
+ return;
+ }
+ for (IdentifierPart part : compositeIdentifierParts(refDomainClass)) {
+ alignWithReferencedIdentifier(part.property(), part.value(), part.compositeId(), part.entity());
+ }
refDomainClass.sortOrIndexForeignKeyColumns(value);
- List<Column> referencedColumns = refDomainClass.getReferencedIdentifierColumns(propertyNames);
- if (!referencedColumns.isEmpty() &&
- value.createForeignKeyOfEntity(refDomainClass.getName(), referencedColumns) != null) {
+ List<Column> referencedColumns = refDomainClass.getReferencedIdentifierColumns(compositeId.getPropertyNames());
+ if (referencedColumns.isEmpty()) {
+ // no identifier columns to pair with, so Hibernate's own foreign key pairs the columns by position
+ value.createForeignKey();
+ } else if (value.createForeignKeyOfEntity(refDomainClass.getName(), referencedColumns) != null) {
value.disableForeignKey();
}
property.markValueSorted(value);
}
+ /**
+ * Whether the identifier of {@code entity} is bound, down to the identifiers that its to-one
+ * parts reference, so that a key referencing it can be aligned with it now.
+ */
+ private boolean isIdentifierBound(GrailsHibernatePersistentEntity entity) {
+ return entity.getPersistentClass() != null &&
+ compositeIdentifierParts(entity).stream()
+ .allMatch(part -> part.value().isSorted() || isIdentifierBound(part.entity()));
+ }
+
+ /**
+ * The to-one parts of the identifier of {@code entity} that reference a composite identifier
+ * themselves, each with the Hibernate value it is bound to. Empty while {@code entity} is unbound.
+ */
+ private static List<IdentifierPart> compositeIdentifierParts(GrailsHibernatePersistentEntity entity) {
+ PersistentClass pc = entity.getPersistentClass();
+ if (pc == null || !(pc.getIdentifier() instanceof Component component)) {
+ return List.of();
+ }
+ return component.getProperties().stream()
+ .filter(part -> part.getValue() instanceof ToOne)
+ .flatMap(part -> identifierPart(entity, part.getName(), (ToOne) part.getValue()).stream())
+ .toList();
+ }
+
+ private static Optional<IdentifierPart> identifierPart(
+ GrailsHibernatePersistentEntity entity, String name, ToOne value) {
+ if (!(entity.getHibernatePropertyByName(name) instanceof HibernateToOneProperty property)) {
+ return Optional.empty();
+ }
+ GrailsHibernatePersistentEntity associated = property.getHibernateAssociatedEntity();
+ return associated.getHibernateCompositeIdentity()
+ .map(compositeId -> new IdentifierPart(property, value, compositeId, associated));
+ }
+
+ private record IdentifierPart(
+ HibernateToOneProperty property,
+ ToOne value,
+ HibernateCompositeIdentity compositeId,
+ GrailsHibernatePersistentEntity entity) {}
+
/**
* If {@code ref} is a to-one whose associated entity has a composite identity, returns a stream
* of one named {@link ColumnConfig} per composite-identity property. Returns empty otherwise.
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/GrailsDomainBinder.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/GrailsDomainBinder.java
index 8eabbc5ca0..49fd8fb5dc 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/GrailsDomainBinder.java
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/GrailsDomainBinder.java
@@ -142,6 +142,7 @@ public class GrailsDomainBinder implements AdditionalMappingContributor, TypeCon
var simpleValueColumnFetcher = new SimpleValueColumnFetcher();
var compositeIdentifierToManyToOneBinder =
new CompositeIdentifierToManyToOneBinder(
+ metadataCollector,
new org.grails.orm.hibernate.cfg.domainbinding.util.ForeignKeyColumnCountCalculator(),
namingStrategy,
defaultColumnNameFetcher,
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/GrailsHibernatePersistentEntity.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/GrailsHibernatePersistentEntity.java
index 7d1fa1c5cc..d3a03df4d6 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/GrailsHibernatePersistentEntity.java
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/GrailsHibernatePersistentEntity.java
@@ -378,7 +378,9 @@ public interface GrailsHibernatePersistentEntity extends PersistentEntity {
* Sorts or indexes the columns of {@code value} to align with this entity's composite
* identifier order. When the identifier is a {@link Component} with an established sort order,
* delegates to {@link SimpleValue#sortColumns(int[])}. Otherwise assigns sequential
- * {@link Column#setTypeIndex(int)} values so Hibernate can correlate them.
+ * {@link Column#setTypeIndex(int)} values so Hibernate can correlate them. The binder calls this
+ * once the identifier is bound, deferring the call to a second pass when this entity is bound
+ * later than the entity holding the key.
*
* @param value the foreign-key {@link SimpleValue} whose columns should be aligned
*/
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CompositeForeignKeySecondPass.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CompositeForeignKeySecondPass.java
new file mode 100644
index 0000000000..a75fbd7e2a
--- /dev/null
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CompositeForeignKeySecondPass.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.grails.orm.hibernate.cfg.domainbinding.secondpass;
+
+import java.io.Serial;
+import java.util.Map;
+
+import org.hibernate.MappingException;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.mapping.SimpleValue;
+
+import org.grails.orm.hibernate.cfg.HibernateCompositeIdentity;
+import org.grails.orm.hibernate.cfg.domainbinding.binder.CompositeIdentifierToManyToOneBinder;
+import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity;
+import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty;
+
+/**
+ * Aligns a foreign key with the composite identifier it references once every persistent class is
+ * bound. The binder registers it when the referenced entity, or an entity nested in its identifier,
+ * is bound later in the first pass than the entity holding the key, so the sort could not run yet.
+ */
+@SuppressWarnings("PMD.NonSerializableClass")
+public class CompositeForeignKeySecondPass implements org.hibernate.boot.spi.SecondPass, java.io.Serializable {
+
+ @Serial
+ private static final long serialVersionUID = 4312279830117492651L;
+
+ private final CompositeIdentifierToManyToOneBinder binder;
+ private final HibernatePersistentProperty property;
+ private final SimpleValue value;
+ private final HibernateCompositeIdentity compositeId;
+ private final GrailsHibernatePersistentEntity refDomainClass;
+
+ public CompositeForeignKeySecondPass(
+ CompositeIdentifierToManyToOneBinder binder,
+ HibernatePersistentProperty property,
+ SimpleValue value,
+ HibernateCompositeIdentity compositeId,
+ GrailsHibernatePersistentEntity refDomainClass) {
+ this.binder = binder;
+ this.property = property;
+ this.value = value;
+ this.compositeId = compositeId;
+ this.refDomainClass = refDomainClass;
+ }
+
+ @Override
+ public void doSecondPass(Map<String, PersistentClass> persistentClasses) throws MappingException {
+ binder.alignWithReferencedIdentifier(property, value, compositeId, refDomainClass);
+ }
+}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/PropertyFromValueCreator.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/PropertyFromValueCreator.java
index 473f0a6919..49f4968eb0 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/PropertyFromValueCreator.java
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/PropertyFromValueCreator.java
@@ -18,12 +18,15 @@
*/
package org.grails.orm.hibernate.cfg.domainbinding.util;
+import org.hibernate.mapping.ManyToOne;
import org.hibernate.mapping.Property;
import org.hibernate.mapping.Value;
import org.grails.orm.hibernate.cfg.domainbinding.binder.PropertyBinder;
+import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity;
import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateEnumProperty;
import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty;
+import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToOneProperty;
public class PropertyFromValueCreator {
@@ -43,10 +46,23 @@ public class PropertyFromValueCreator {
value.setTypeUsingReflection(grailsProperty.getOwnerClassName(), grailsProperty.getName());
}
- if (value.getTable() != null) {
+ if (value.getTable() != null && !referencesCompositeIdentifier(value, grailsProperty)) {
value.createForeignKey();
}
return propertyBinder.bindProperty(grailsProperty, value);
}
+
+ /**
+ * A many-to-one to a composite identifier gets its foreign key from the composite identifier
+ * binder, which pairs each column with the identifier column it references once that identifier
+ * is bound. Hibernate's own foreign key would pair the columns by position instead.
+ */
+ private static boolean referencesCompositeIdentifier(Value value, HibernatePersistentProperty grailsProperty) {
+ if (!(value instanceof ManyToOne) || !(grailsProperty instanceof HibernateToOneProperty toOne)) {
+ return false;
+ }
+ GrailsHibernatePersistentEntity associatedEntity = toOne.getHibernateAssociatedEntity();
+ return associatedEntity != null && associatedEntity.getHibernateCompositeIdentity().isPresent();
+ }
}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CollectionBinderSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CollectionBinderSpec.groovy
index 656c1d0fb4..791aba51ce 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CollectionBinderSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CollectionBinderSpec.groovy
@@ -69,7 +69,7 @@ class CollectionBinderSpec extends HibernateGormDatastoreSpec {
def dcnf = new DefaultColumnNameFetcher(ns, backticksRemover)
def cnfpapf = new ColumnNameForPropertyAndPathFetcher(ns, dcnf, backticksRemover)
def etb = new EnumTypeBinder(mbc, cnfpapf, ns)
- def citmto = new CompositeIdentifierToManyToOneBinder(new org.grails.orm.hibernate.cfg.domainbinding.util.ForeignKeyColumnCountCalculator(), ns, dcnf, backticksRemover, svb)
+ def citmto = new CompositeIdentifierToManyToOneBinder(mockCollector, new org.grails.orm.hibernate.cfg.domainbinding.util.ForeignKeyColumnCountCalculator(), ns, dcnf, backticksRemover, svb)
def mtob = new ManyToOneBinder(mbc, ns, svb, new ManyToOneValuesBinder(), citmto)
def ch = new CollectionHolder(mbc)
mockCalculator = Mock(TableForManyCalculator)
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CompositeIdentifierToManyToOneBinderSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CompositeIdentifierToManyToOneBinderSpec.groovy
index d65a95fcbe..ae378f5769 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CompositeIdentifierToManyToOneBinderSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CompositeIdentifierToManyToOneBinderSpec.groovy
@@ -27,6 +27,7 @@ import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersi
import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty
import org.grails.orm.hibernate.cfg.PersistentEntityNamingStrategy
import org.grails.orm.hibernate.cfg.PropertyConfig
+import org.hibernate.boot.spi.InFlightMetadataCollector
import org.hibernate.mapping.Column
import org.hibernate.mapping.KeyValue
import org.hibernate.mapping.RootClass
@@ -35,6 +36,7 @@ import spock.lang.Specification
import org.grails.orm.hibernate.cfg.domainbinding.binder.CompositeIdentifierToManyToOneBinder
import org.grails.orm.hibernate.cfg.domainbinding.binder.SimpleValueBinder
+import org.grails.orm.hibernate.cfg.domainbinding.secondpass.CompositeForeignKeySecondPass
import org.grails.orm.hibernate.cfg.domainbinding.util.BackticksRemover
import org.grails.orm.hibernate.cfg.domainbinding.util.DefaultColumnNameFetcher
import org.grails.orm.hibernate.cfg.domainbinding.util.ForeignKeyColumnCountCalculator
@@ -44,6 +46,7 @@ class CompositeIdentifierToManyToOneBinderSpec extends Specification {
def "Test bindCompositeIdentifierToManyToOne with nested composite ID"() {
given:
// 1. Stub all dependencies for the protected constructor
+ def metadataCollector = Mock(InFlightMetadataCollector)
def calculator = Stub(ForeignKeyColumnCountCalculator)
def namingStrategy = Stub(PersistentEntityNamingStrategy)
def columnNameFetcher = Stub(DefaultColumnNameFetcher)
@@ -52,7 +55,7 @@ class CompositeIdentifierToManyToOneBinderSpec extends Specification {
def metadataBuildingContext = Mock(org.hibernate.boot.spi.MetadataBuildingContext)
// Instantiate the binder with stubs
- def binder = new CompositeIdentifierToManyToOneBinder(calculator, namingStrategy, columnNameFetcher, backticksRemover, simpleValueBinder)
+ def binder = new CompositeIdentifierToManyToOneBinder(metadataCollector, calculator, namingStrategy, columnNameFetcher, backticksRemover, simpleValueBinder)
// 2. Set up stubs for the method arguments
def association = Mock(HibernatePersistentProperty)
@@ -120,11 +123,17 @@ class CompositeIdentifierToManyToOneBinderSpec extends Specification {
and: // 6. Verify the call to the simple value binder
1 * simpleValueBinder.bindSimpleValue(_ as HibernatePersistentProperty, null, value, path)
+
+ and: 'the referenced entity is bound, so the key is aligned with its identifier in this pass'
+ 1 * refDomainClass.sortOrIndexForeignKeyColumns(value)
+ 1 * association.markValueSorted(value)
+ 0 * metadataCollector.addSecondPass(_)
}
def "Test bindCompositeIdentifierToManyToOne when column count matches"() {
given:
// 1. Use Mocks for dependencies that require interaction verification
+ def metadataCollector = Mock(InFlightMetadataCollector)
def calculator = Stub(ForeignKeyColumnCountCalculator)
def namingStrategy = Mock(PersistentEntityNamingStrategy)
def columnNameFetcher = Mock(DefaultColumnNameFetcher)
@@ -132,7 +141,7 @@ class CompositeIdentifierToManyToOneBinderSpec extends Specification {
def simpleValueBinder = Mock(SimpleValueBinder)
def metadataBuildingContext = Mock(org.hibernate.boot.spi.MetadataBuildingContext)
- def binder = new CompositeIdentifierToManyToOneBinder(calculator, namingStrategy, columnNameFetcher, backticksRemover, simpleValueBinder)
+ def binder = new CompositeIdentifierToManyToOneBinder(metadataCollector, calculator, namingStrategy, columnNameFetcher, backticksRemover, simpleValueBinder)
// 2. Set up arguments
def association = Mock(HibernatePersistentProperty)
@@ -176,4 +185,74 @@ class CompositeIdentifierToManyToOneBinderSpec extends Specification {
and: // 5. Verify the simple value binder is still called
1 * simpleValueBinder.bindSimpleValue(_ as HibernatePersistentProperty, null, value, path)
}
+
+ def "the alignment with a referenced entity that is not bound yet is deferred to a second pass"() {
+ given:
+ def metadataCollector = Mock(InFlightMetadataCollector)
+ def calculator = Stub(ForeignKeyColumnCountCalculator)
+ def simpleValueBinder = Mock(SimpleValueBinder)
+ def binder = new CompositeIdentifierToManyToOneBinder(metadataCollector, calculator,
+ Stub(PersistentEntityNamingStrategy), Stub(DefaultColumnNameFetcher), Stub(BackticksRemover), simpleValueBinder)
+
+ def association = Mock(HibernatePersistentProperty)
+ def value = Mock(SimpleValue)
+ def refDomainClass = Mock(GrailsHibernatePersistentEntity)
+ def propertyNames = ['prop1', 'prop2'] as String[]
+ def compositeId = new HibernateCompositeIdentity()
+ compositeId.setPropertyNames(propertyNames)
+ def propertyConfig = new PropertyConfig()
+ propertyConfig.getColumns().add(new ColumnConfig())
+ propertyConfig.getColumns().add(new ColumnConfig())
+ association.getHibernateMappedForm() >> propertyConfig
+ calculator.calculateForeignKeyColumnCount(refDomainClass, _ as String[]) >> 2
+ refDomainClass.getName() >> 'RefDomain'
+ CompositeForeignKeySecondPass secondPass = null
+
+ when: 'the key is bound while the referenced entity has no persistent class yet'
+ binder.bindCompositeIdentifierToManyToOne(association, value, compositeId, refDomainClass, '/test')
+
+ then: 'the columns are bound, but neither sorted nor marked sorted'
+ 1 * simpleValueBinder.bindSimpleValue(association, null, value, '/test')
+ 1 * metadataCollector.addSecondPass(_ as CompositeForeignKeySecondPass) >> { args -> secondPass = args[0] }
+ 0 * refDomainClass.sortOrIndexForeignKeyColumns(_)
+ 0 * association.markValueSorted(_)
+
+ when: 'Hibernate runs the second pass'
+ secondPass.doSecondPass([:])
+
+ then: 'the key is sorted against the referenced identifier, its foreign key created, and marked sorted'
+ 1 * refDomainClass.sortOrIndexForeignKeyColumns(value)
+ 1 * refDomainClass.getReferencedIdentifierColumns(propertyNames) >> [new Column('prop1'), new Column('prop2')]
+ 1 * value.createForeignKeyOfEntity('RefDomain', _ as List<Column>) >> null
+ 1 * association.markValueSorted(value)
+ }
+
+ def "a key bound during the second passes is aligned at once even when the referenced entity has no persistent class"() {
+ given:
+ def metadataCollector = Mock(InFlightMetadataCollector)
+ def calculator = Stub(ForeignKeyColumnCountCalculator)
+ def binder = new CompositeIdentifierToManyToOneBinder(metadataCollector, calculator,
+ Stub(PersistentEntityNamingStrategy), Stub(DefaultColumnNameFetcher), Stub(BackticksRemover), Mock(SimpleValueBinder))
+
+ def association = Mock(HibernatePersistentProperty)
+ def value = Mock(SimpleValue)
+ def refDomainClass = Mock(GrailsHibernatePersistentEntity)
+ def compositeId = new HibernateCompositeIdentity()
+ compositeId.setPropertyNames(['prop1', 'prop2'] as String[])
+ def propertyConfig = new PropertyConfig()
+ propertyConfig.getColumns().add(new ColumnConfig())
+ propertyConfig.getColumns().add(new ColumnConfig())
+ association.getHibernateMappedForm() >> propertyConfig
+ calculator.calculateForeignKeyColumnCount(refDomainClass, _ as String[]) >> 2
+ metadataCollector.isInSecondPass() >> true
+
+ when:
+ binder.bindCompositeIdentifierToManyToOne(association, value, compositeId, refDomainClass, '/test')
+
+ then:
+ 0 * metadataCollector.addSecondPass(_)
+ 1 * refDomainClass.sortOrIndexForeignKeyColumns(value)
+ 1 * refDomainClass.getReferencedIdentifierColumns(_ as String[]) >> []
+ 1 * association.markValueSorted(value)
+ }
}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/GrailsPropertyBinderSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/GrailsPropertyBinderSpec.groovy
index ff6b859c18..330eac3ada 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/GrailsPropertyBinderSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/GrailsPropertyBinderSpec.groovy
@@ -67,6 +67,7 @@ class GrailsPropertyBinderSpec extends HibernateGormDatastoreSpec {
EnumTypeBinder enumTypeBinderToUse = new EnumTypeBinder(metadataBuildingContext, columnNameForPropertyAndPathFetcher, namingStrategy)
SimpleValueColumnFetcher simpleValueColumnFetcher = new SimpleValueColumnFetcher()
CompositeIdentifierToManyToOneBinder compositeIdentifierToManyToOneBinder = new CompositeIdentifierToManyToOneBinder(
+ collector,
new org.grails.orm.hibernate.cfg.domainbinding.util.ForeignKeyColumnCountCalculator(),
namingStrategy,
defaultColumnNameFetcher,
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/PropertyFromValueCreatorSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/PropertyFromValueCreatorSpec.groovy
index 21da453aa9..5317f8c97a 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/PropertyFromValueCreatorSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/PropertyFromValueCreatorSpec.groovy
@@ -19,12 +19,16 @@
package org.grails.orm.hibernate.cfg.domainbinding
+import org.hibernate.mapping.ManyToOne
import org.hibernate.mapping.Property
import org.hibernate.mapping.Table
import org.hibernate.mapping.Value
import spock.lang.Specification
+import org.grails.orm.hibernate.cfg.HibernateCompositeIdentity
+import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity
import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty
+import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToOneProperty
import org.grails.orm.hibernate.cfg.domainbinding.binder.PropertyBinder
import org.grails.orm.hibernate.cfg.domainbinding.util.PropertyFromValueCreator
@@ -82,4 +86,32 @@ class PropertyFromValueCreatorSpec extends Specification {
0 * value.createForeignKey()
prop.getValue() == value
}
+
+ def "a many-to-one to a #identifier identifier #outcome Hibernate's foreign key, which pairs the columns by position"() {
+ given:
+ def propertyBinder = Mock(PropertyBinder)
+ def creator = new PropertyFromValueCreator(propertyBinder)
+
+ def value = Mock(ManyToOne)
+ def grailsProperty = Mock(HibernateToOneProperty)
+ def associatedEntity = Mock(GrailsHibernatePersistentEntity)
+
+ grailsProperty.getOwnerClassName() >> "com.example.MyEntity"
+ grailsProperty.getName() >> "parent"
+ grailsProperty.getHibernateAssociatedEntity() >> associatedEntity
+ associatedEntity.getHibernateCompositeIdentity() >> compositeIdentity
+ value.getTable() >> new Table("my_table")
+ propertyBinder.bindProperty(grailsProperty, value) >> new Property()
+
+ when:
+ creator.createProperty(value, grailsProperty)
+
+ then: 'the composite identifier binder pairs the columns of a composite key with the identifier columns itself'
+ foreignKeys * value.createForeignKey()
+
+ where:
+ identifier | compositeIdentity || foreignKeys | outcome
+ 'simple' | Optional.empty() || 1 | 'gets'
+ 'composite' | Optional.of(new HibernateCompositeIdentity()) || 0 | 'does not get'
+ }
}
\ No newline at end of file
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeForeignKeyColumnTypesSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeForeignKeyColumnTypesSpec.groovy
index fa7726717d..6ef8ed8e55 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeForeignKeyColumnTypesSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeForeignKeyColumnTypesSpec.groovy
@@ -73,23 +73,7 @@ class CompositeForeignKeyColumnTypesSpec extends Specification {
* {@code KEY_SEQ} order, which is the order the database matches the columns of a key by.
*/
private Map<String, List<List<String>>> foreignKeyPairs(String table) {
- Map<String, List<List<String>>> keys = [:]
- datastore.sessionFactory.openSession().withCloseable { session ->
- session.doWork { Connection c ->
- c.metaData.getImportedKeys(null, null, table).withCloseable { rs ->
- List<List> rows = []
- while (rs.next()) {
- rows << [rs.getString('FK_NAME'), rs.getInt('KEY_SEQ'),
- rs.getString('PKTABLE_NAME').toLowerCase(),
- rs.getString('FKCOLUMN_NAME').toLowerCase(), rs.getString('PKCOLUMN_NAME').toLowerCase()]
- }
- rows.sort { it[1] }.each { List row ->
- keys.get(row[0] + ' -> ' + row[2], []) << [row[3], row[4]]
- }
- }
- }
- }
- keys.collectEntries { String name, List<List<String>> pairs -> [(name.substring(name.indexOf(' -> ') + 4)): pairs] }
+ ForeignKeyPairs.of(datastore, table)
}
void "a foreign key to a composite parent pairs its columns with the referenced key columns in key order"() {
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeForeignKeyRegistrationOrderSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeForeignKeyRegistrationOrderSpec.groovy
new file mode 100644
index 0000000000..8dd3a06839
--- /dev/null
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeForeignKeyRegistrationOrderSpec.groovy
@@ -0,0 +1,128 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.grails.orm.hibernate.cfg.domainbinding.binder
+
+import org.grails.orm.hibernate.HibernateDatastore
+import org.hibernate.dialect.H2Dialect
+import spock.lang.Specification
+import spock.lang.Unroll
+
+/**
+ * An application registers its entities in class-path scan order, so an entity is often bound before
+ * the entity its composite foreign key references. The key must still be aligned with the referenced
+ * identifier once that identifier is bound, exactly as when the referenced entity is registered first.
+ * The entities are the ones of {@link CompositeForeignKeyColumnTypesSpec}, which registers every
+ * referenced entity first.
+ */
+class CompositeForeignKeyRegistrationOrderSpec extends Specification {
+
+ private static final List<List<String>> LEAF_KEY = [
+ ['prb_middle_grand_parent_alpha', 'prb_grand_alpha'],
+ ['prb_middle_grand_parent_zeta', 'prb_grand_zeta'],
+ ['prb_middle_name', 'name']]
+
+ private static final List<List<String>> HUB_KEY = [
+ ['prb_hub_ace', 'ace'],
+ ['prb_hub_grand_alpha', 'prb_grand_alpha'],
+ ['prb_hub_grand_zeta', 'prb_grand_zeta'],
+ ['prb_hub_zed', 'zed']]
+
+ private static Map<String, Object> config(List<Class> classes) {
+ [
+ 'dataSource.url' : "jdbc:h2:mem:compositeFkOrder${classes*.simpleName.join('')};LOCK_TIMEOUT=10000".toString(),
+ 'dataSource.dbCreate' : 'create-drop',
+ 'dataSource.dialect' : H2Dialect.name,
+ 'hibernate.hbm2ddl.auto': 'create',
+ ]
+ }
+
+ @Unroll
+ void "the keys of a three level composite chain registered as #order are aligned with the keys they reference"() {
+ given:
+ HibernateDatastore datastore = new HibernateDatastore(config(classes), classes as Class[])
+
+ when:
+ Map<String, List<List<String>>> middleKeys = ForeignKeyPairs.of(datastore, 'PRB_MIDDLE')
+ Map<String, List<List<String>>> leafKeys = ForeignKeyPairs.of(datastore, 'PRB_LEAF')
+
+ then:
+ middleKeys == [prb_grand: [['prb_grand_alpha', 'alpha'], ['prb_grand_zeta', 'zeta']]]
+ leafKeys == [prb_middle: LEAF_KEY]
+
+ when:
+ PrbGrand.withNewTransaction {
+ PrbGrand grand = new PrbGrand(zeta: 'z', alpha: 'a').save(failOnError: true)
+ PrbMiddle middle = new PrbMiddle(name: 'm', grandParent: grand).save(failOnError: true)
+ new PrbLeaf(name: 'l', middle: middle).save(failOnError: true, flush: true)
+ }
+
+ then:
+ PrbLeaf.withNewSession {
+ PrbLeaf leaf = PrbLeaf.findByName('l')
+ leaf.middle.name == 'm' && leaf.middle.grandParent.alpha == 'a' && leaf.middle.grandParent.zeta == 'z'
+ }
+
+ cleanup:
+ datastore?.close()
+
+ where:
+ order | classes
+ 'grand, leaf, middle' | [PrbGrand, PrbLeaf, PrbMiddle]
+ 'middle, grand, leaf' | [PrbMiddle, PrbGrand, PrbLeaf]
+ 'leaf, middle, grand' | [PrbLeaf, PrbMiddle, PrbGrand]
+ }
+
+ @Unroll
+ void "the keys that reference a hub registered as #order are aligned with the hub key"() {
+ given:
+ HibernateDatastore datastore = new HibernateDatastore(config(classes), classes as Class[])
+
+ when:
+ Map<String, List<List<String>>> refKeys = ForeignKeyPairs.of(datastore, 'PRB_HUB_REF')
+ Map<String, List<List<String>>> joinTableKeys = ForeignKeyPairs.of(datastore, 'PRB_HUB_PRB_HUB_TAG')
+
+ then:
+ refKeys == [prb_hub: HUB_KEY]
+ joinTableKeys == [prb_hub: HUB_KEY, prb_hub_tag: [['prb_hub_tag_id', 'id']]]
+
+ when:
+ PrbGrand.withNewTransaction {
+ PrbGrand grand = new PrbGrand(zeta: 'z', alpha: 'a').save(failOnError: true)
+ PrbHub hub = new PrbHub(zed: 'zz', ace: 'aa', grand: grand)
+ .addToTags(new PrbHubTag(label: 'tag'))
+ .save(failOnError: true)
+ new PrbHubRef(name: 'ref', hub: hub).save(failOnError: true, flush: true)
+ }
+
+ then:
+ PrbHubRef.withNewSession {
+ PrbHubRef ref = PrbHubRef.findByName('ref')
+ ref.hub.zed == 'zz' && ref.hub.ace == 'aa' && ref.hub.grand.zeta == 'z' && ref.hub.tags*.label == ['tag']
+ }
+
+ cleanup:
+ datastore?.close()
+
+ where:
+ order | classes
+ 'grand, hub, ref, tag' | [PrbGrand, PrbHub, PrbHubRef, PrbHubTag]
+ 'ref, tag, hub, grand' | [PrbHubRef, PrbHubTag, PrbHub, PrbGrand]
+ }
+}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ForeignKeyPairs.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ForeignKeyPairs.groovy
new file mode 100644
index 0000000000..f9bba51b5b
--- /dev/null
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ForeignKeyPairs.groovy
@@ -0,0 +1,55 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.grails.orm.hibernate.cfg.domainbinding.binder
+
+import java.sql.Connection
+
+import org.grails.orm.hibernate.HibernateDatastore
+
+/**
+ * Reads the foreign keys of a table back from the database, as the column pairs the key is matched by.
+ */
+class ForeignKeyPairs {
+
+ /**
+ * The foreign keys of a table, keyed by the referenced table, each as its column pairs
+ * [foreign key column, referenced column] in {@code KEY_SEQ} order, which is the order the
+ * database matches the columns of a key by.
+ */
+ static Map<String, List<List<String>>> of(HibernateDatastore datastore, String table) {
+ Map<String, List<List<String>>> keys = [:]
+ datastore.sessionFactory.openSession().withCloseable { session ->
+ session.doWork { Connection c ->
+ c.metaData.getImportedKeys(null, null, table).withCloseable { rs ->
+ List<List> rows = []
+ while (rs.next()) {
+ rows << [rs.getString('FK_NAME'), rs.getInt('KEY_SEQ'),
+ rs.getString('PKTABLE_NAME').toLowerCase(),
+ rs.getString('FKCOLUMN_NAME').toLowerCase(), rs.getString('PKCOLUMN_NAME').toLowerCase()]
+ }
+ rows.sort { it[1] }.each { List row ->
+ keys.get(row[0] + ' -> ' + row[2], []) << [row[3], row[4]]
+ }
+ }
+ }
+ }
+ keys.collectEntries { String name, List<List<String>> pairs -> [(name.substring(name.indexOf(' -> ') + 4)): pairs] }
+ }
+}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionKeyBinderSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionKeyBinderSpec.groovy
index 902da54354..a789d1b668 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionKeyBinderSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionKeyBinderSpec.groovy
@@ -61,7 +61,7 @@ class CollectionKeyBinderSpec extends HibernateGormDatastoreSpec {
def ns = gdb.getNamingStrategy()
def je = gdb.getJdbcEnvironment()
def svb = new SimpleValueBinder(mbc, ns, je)
- def citmto = new CompositeIdentifierToManyToOneBinder(new org.grails.orm.hibernate.cfg.domainbinding.util.ForeignKeyColumnCountCalculator(), ns, new org.grails.orm.hibernate.cfg.domainbinding.util.DefaultColumnNameFetcher(ns), new org.grails.orm.hibernate.cfg.domainbinding.util.BackticksRemover(), svb)
+ def citmto = new CompositeIdentifierToManyToOneBinder(mbc.getMetadataCollector(), new org.grails.orm.hibernate.cfg.domainbinding.util.ForeignKeyColumnCountCalculator(), ns, new org.grails.orm.hibernate.cfg.domainbinding.util.DefaultColumnNameFetcher(ns), new org.grails.orm.hibernate.cfg.domainbinding.util.BackticksRemover(), svb)
def botml = new BidirectionalOneToManyLinker(new GrailsPropertyResolver())
def dkvb = new DependentKeyValueBinder(svb, citmto)
def svcb = new SimpleValueColumnBinder()
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/ListSecondPassBinderSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/ListSecondPassBinderSpec.groovy
index da3622456f..5bbb1ad086 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/ListSecondPassBinderSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/ListSecondPassBinderSpec.groovy
@@ -47,7 +47,7 @@ class ListSecondPassBinderSpec extends HibernateGormDatastoreSpec {
EnumTypeBinder etb = new EnumTypeBinder(mbc, cnfpapf, ns)
SimpleValueColumnFetcher svcf = new SimpleValueColumnFetcher()
CompositeIdentifierToManyToOneBinder citmto = new CompositeIdentifierToManyToOneBinder(
- new ForeignKeyColumnCountCalculator(), ns, dcnf, br, svb)
+ collector, new ForeignKeyColumnCountCalculator(), ns, dcnf, br, svb)
OneToOneBinder otob = new OneToOneBinder(mbc, svb)
ManyToOneBinder mtob = new ManyToOneBinder(mbc, ns, svb, new ManyToOneValuesBinder(), citmto)
ForeignKeyOneToOneBinder fkotob = new ForeignKeyOneToOneBinder(mtob, svcf)
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/MapSecondPassBinderSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/MapSecondPassBinderSpec.groovy
index 7f5ea717b8..0e3408cbf4 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/MapSecondPassBinderSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/MapSecondPassBinderSpec.groovy
@@ -85,7 +85,7 @@ class MapSecondPassBinderSpec extends HibernateGormDatastoreSpec {
EnumTypeBinder enumTypeBinderToUse = new EnumTypeBinder(metadataBuildingContext, columnNameForPropertyAndPathFetcher, namingStrategy)
SimpleValueColumnFetcher simpleValueColumnFetcher = new SimpleValueColumnFetcher()
CompositeIdentifierToManyToOneBinder compositeIdentifierToManyToOneBinder = new CompositeIdentifierToManyToOneBinder(
-
+ collector,
new org.grails.orm.hibernate.cfg.domainbinding.util.ForeignKeyColumnCountCalculator(),
namingStrategy,
defaultColumnNameFetcher,