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/10 19:00:55 UTC
(grails-core) branch 8.0.x updated: Hibernate 7: name nested composite foreign key columns in the referenced key's order (#16539)
This is an automated email from the ASF dual-hosted git repository.
borinquenkid pushed a commit to branch 8.0.x
in repository https://gitbox.apache.org/repos/asf/grails-core.git
The following commit(s) were added to refs/heads/8.0.x by this push:
new bfa709384d Hibernate 7: name nested composite foreign key columns in the referenced key's order (#16539)
bfa709384d is described below
commit bfa709384d5e03de3a4bd77c3e12e9b80d37e4e2
Author: Walter B Duque de Estrada <wb...@mac.com>
AuthorDate: Sat Oct 10 14:00:50 2026 -0500
Hibernate 7: name nested composite foreign key columns in the referenced key's order (#16539)
* fix: name the foreign key columns of a nested composite identifier in the referenced key's order
A foreign key to an entity whose composite identifier contains a to-one to another composite
entity (leaf -> middle(grandParent, name) -> grandParent(name String, luckyNumber Integer))
named the expanded columns in the mapped order of the nested parts, while Hibernate types them
positionally from the referenced key, whose nested parts are sorted by property name. The leaf
table got cfk_middle_grand_parent_name INTEGER and cfk_middle_grand_parent_lucky_number
VARCHAR. Data round-trips (the order is consistent positionally) but the columns are
mislabelled for schema tooling and native SQL. The nested parts are now sorted by name.
Co-Authored-By: Claude Sonnet 5.5 <no...@anthropic.com>
* test: prove the composite foreign key column order against a real mapping
The earlier assertions checked each column's name and type, which an
integer paired with a string would break but two same-typed parts written in
the wrong order would not. The Hibernate-backed spec now reads the imported
keys from JDBC metadata in KEY_SEQ order and asserts each foreign key
column against the referenced primary key column, including cfk_middle_name,
for parts declared out of name order and for the nested chain. It fails when
the sort in CompositeIdentifierToManyToOneBinder is removed. The mock-based
binder spec no longer claims the ordering.
Co-Authored-By: Claude Sonnet 5.5 <no...@anthropic.com>
* fix: permute the columns of a composite identifier by part, not by property
A foreign key into an entity whose composite identifier has a part that
spans several columns (a to-one to another composite entity) was sorted
with Hibernate's property permutation applied to the column list. That only
lines up when every part has one column, so a nested part declared after a
plain part that sorts before it left the foreign key columns pointing at the
wrong primary key columns and the row failed to save. The permutation is now
expanded to move each part with its whole column span, in both
sortOrIndexForeignKeyColumns and getReferencedIdentifierColumns.
Also drops the unused Transactional import from the spec.
Co-Authored-By: Claude Sonnet 5.5 <no...@anthropic.com>
* 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>
* 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>
* fix: leave the foreign key of a bidirectional one-to-many to its to-one side
The inverse collection's key added a second foreign key for the same
association. Collection.createAllKeys(), run from the collection's second
pass, creates a positional key for the key columns under the same implicit
name as the explicit key the composite binder creates for the to-one side:
the name is hashed from the two tables and the column names, not from the
referenced columns or their order. Both keys were in the metadata in every
registration order; the schema export created the first one registered and
logged "Constraint already exists" for the other. Registered as PrbMiddle,
PrbLeaf, PrbGrand, the collection's second pass ran before the to-one's
deferred alignment, so the positional key reached the database, paired the
wrong columns and saving a leaf failed with a referential integrity
violation. A bidirectional hasMany into the PrbHub layout failed the same
way registered as hub, child, grand.
BidirectionalOneToManyLinker.link now disables the key's foreign key, so
the to-one side's key is the only key of the association. The to-one side
always creates one: ToOne.createForeignKey(), called from
PropertyFromValueCreator, for a simple identifier, and the composite binder,
with the referenced identifier columns, for a composite one. This applies
to every inverse one-to-many rather than only to composite owners because
for a simple identifier the two keys were one and the same ForeignKey,
deduplicated by Table.createForeignKey, so the key that remains keeps the
implicit name and columns an existing schema has.
CompositeForeignKeyRegistrationOrderSpec now runs every registration order
(6 of the chain, 24 of the hub set, 6 of grand, hub and the new bidirectional
PrbHubChild) and asserts that no foreign key name appears twice in the
Hibernate metadata; a simple-identifier pair pins the unchanged implicit
name and columns of its single key. Before the fix the two orders above
failed with the integrity violation and every other composite order failed
the duplicate-name assertion.
Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
* test: pin the empty inverse hasMany of a composite identifier declared out of name order
An inverse hasMany on an entity whose composite identifier is not declared
in name order loads no elements: BidirectionalOneToManyLinker.link copies
the to-one's columns, which are already in key order, and key.sortProperties()
applies the owner identifier's permutation a second time, so the collection
is loaded with the identifier values bound to the wrong columns. Declared in
name order, the permutation is the identity and the collection loads.
This predates the composite foreign key fixes and does not need a nested
composite, so it is left to a follow-up issue. The spec records the repro as
a @PendingFeature next to the name-order variant that passes, so the fix
will surface as "passes unexpectedly" and the annotation is removed with it.
Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
---------
Co-authored-by: Claude Sonnet 5.5 <no...@anthropic.com>
---
.../CompositeIdentifierToManyToOneBinder.java | 95 ++++-
.../domainbinding/binder/GrailsDomainBinder.java | 1 +
.../hibernate/GrailsHibernatePersistentEntity.java | 59 ++-
.../secondpass/BidirectionalOneToManyLinker.java | 11 +-
.../secondpass/CompositeForeignKeySecondPass.java | 67 ++++
.../util/PropertyFromValueCreator.java | 18 +-
.../cfg/domainbinding/CollectionBinderSpec.groovy | 2 +-
...CompositeIdentifierToManyToOneBinderSpec.groovy | 86 ++++-
.../domainbinding/GrailsPropertyBinderSpec.groovy | 1 +
.../PropertyFromValueCreatorSpec.groovy | 32 ++
.../CompositeForeignKeyColumnTypesSpec.groovy | 422 +++++++++++++++++++++
...CompositeForeignKeyRegistrationOrderSpec.groovy | 225 +++++++++++
.../domainbinding/binder/ForeignKeyPairs.groovy | 55 +++
...verseHasManyCompositeIdentifierOrderSpec.groovy | 109 ++++++
.../BidirectionalOneToManyLinkerSpec.groovy | 4 +
.../secondpass/CollectionKeyBinderSpec.groovy | 2 +-
.../secondpass/ListSecondPassBinderSpec.groovy | 2 +-
.../secondpass/MapSecondPassBinderSpec.groovy | 2 +-
18 files changed, 1178 insertions(+), 15 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 5b2ed19d4b..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
@@ -19,16 +19,21 @@
package org.grails.orm.hibernate.cfg.domainbinding.binder;
import java.util.Arrays;
+import java.util.Comparator;
import java.util.List;
import java.util.Optional;
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;
@@ -36,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;
@@ -45,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;
@@ -52,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;
@@ -69,6 +78,7 @@ public class CompositeIdentifierToManyToOneBinder {
PersistentEntityNamingStrategy namingStrategy,
JdbcEnvironment jdbcEnvironment) {
this(
+ metadataBuildingContext.getMetadataCollector(),
new ForeignKeyColumnCountCalculator(),
namingStrategy,
new DefaultColumnNameFetcher(namingStrategy),
@@ -103,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.
@@ -126,7 +212,10 @@ public class CompositeIdentifierToManyToOneBinder {
if (nestedComposite == null) {
return Optional.empty();
}
+ // Hibernate sorts the properties of a composite identifier by name, and the columns this key
+ // references follow that order, so the foreign key columns are named in the same order
return Optional.of(Arrays.stream(nestedComposite)
+ .sorted(Comparator.comparing(HibernatePersistentProperty::getName))
.map(cip -> namedColumn(join(
prefix,
namingStrategy.resolveColumnName(propertyName),
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 355687954f..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
@@ -36,6 +36,7 @@ import org.hibernate.mapping.Column;
import org.hibernate.mapping.Component;
import org.hibernate.mapping.KeyValue;
import org.hibernate.mapping.PersistentClass;
+import org.hibernate.mapping.Property;
import org.hibernate.mapping.SimpleValue;
import org.grails.datastore.mapping.model.PersistentEntity;
@@ -377,16 +378,19 @@ 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
*/
default void sortOrIndexForeignKeyColumns(SimpleValue value) {
PersistentClass pc = getPersistentClass();
KeyValue identifier = pc != null ? pc.getIdentifier() : null;
- int[] originalOrder = identifier instanceof Component c ? c.sortProperties() : null;
+ Component component = identifier instanceof Component c ? c : null;
+ int[] originalOrder = component != null ? component.sortProperties() : null;
if (originalOrder != null) {
- value.sortColumns(originalOrder);
+ value.sortColumns(toColumnPermutation(originalOrder, partColumnSpans(component, originalOrder)));
} else {
List<Column> cols = value.getColumns();
for (int i = 0; i < cols.size(); i++) {
@@ -420,7 +424,13 @@ public interface GrailsHibernatePersistentEntity extends PersistentEntity {
List<Column> referencedColumns = Arrays.stream(propertyNames)
.flatMap(name -> component.getProperty(name).getValue().getColumns().stream())
.collect(Collectors.toCollection(ArrayList::new));
- return originalOrder != null ? sortedByPermutation(referencedColumns, originalOrder) : referencedColumns;
+ if (originalOrder == null) {
+ return referencedColumns;
+ }
+ int[] spans = Arrays.stream(propertyNames)
+ .mapToInt(name -> component.getProperty(name).getValue().getColumnSpan())
+ .toArray();
+ return sortedByPermutation(referencedColumns, toColumnPermutation(originalOrder, spans));
}
private static List<Column> sortedByPermutation(List<Column> columns, int[] permutation) {
@@ -430,4 +440,45 @@ public interface GrailsHibernatePersistentEntity extends PersistentEntity {
}
return result;
}
+
+ /**
+ * Returns the number of columns each part of the composite identifier spans, in declared order.
+ * {@code propertyPermutation[i]} is the position of declared part {@code i} in the sorted property list.
+ */
+ private static int[] partColumnSpans(Component component, int[] propertyPermutation) {
+ List<Property> sorted = component.getProperties();
+ int[] spans = new int[propertyPermutation.length];
+ for (int i = 0; i < spans.length; i++) {
+ spans[i] = sorted.get(propertyPermutation[i]).getValue().getColumnSpan();
+ }
+ return spans;
+ }
+
+ /**
+ * Expands a permutation of identifier parts into a permutation of columns. A to-one part that
+ * references a composite identifier spans several columns, so moving it to its sorted position
+ * has to move its whole column span. {@code result[c]} is the sorted position of declared column
+ * {@code c}. With one column per part the result equals {@code propertyPermutation}.
+ */
+ private static int[] toColumnPermutation(int[] propertyPermutation, int[] spans) {
+ int[] sortedStart = new int[propertyPermutation.length];
+ int[] declaredAtSortedPosition = new int[propertyPermutation.length];
+ for (int i = 0; i < propertyPermutation.length; i++) {
+ declaredAtSortedPosition[propertyPermutation[i]] = i;
+ }
+ int offset = 0;
+ for (int position : declaredAtSortedPosition) {
+ sortedStart[position] = offset;
+ offset += spans[position];
+ }
+ int[] result = new int[offset];
+ int declaredStart = 0;
+ for (int i = 0; i < spans.length; i++) {
+ for (int k = 0; k < spans[i]; k++) {
+ result[declaredStart + k] = sortedStart[i] + k;
+ }
+ declaredStart += spans[i];
+ }
+ return result;
+ }
}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/BidirectionalOneToManyLinker.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/BidirectionalOneToManyLinker.java
index c929e04e5c..c5a03e6cf6 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/BidirectionalOneToManyLinker.java
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/BidirectionalOneToManyLinker.java
@@ -26,7 +26,15 @@ import org.hibernate.mapping.PersistentClass;
import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty;
import org.grails.orm.hibernate.cfg.domainbinding.util.GrailsPropertyResolver;
-/** Links bidirectional one-to-many associations by copying columns. */
+/**
+ * Links bidirectional one-to-many associations by copying columns. The foreign key of the
+ * association belongs to the to-one side, which always creates it: Hibernate's
+ * {@link org.hibernate.mapping.ToOne#createForeignKey()} for a simple identifier, the composite
+ * identifier binder, with the referenced identifier columns, for a composite one. The inverse
+ * collection key therefore creates no positional key of its own. For a simple identifier the two
+ * keys were the same key already; for a composite identifier they differ, share the implicit name,
+ * and only the first one registered reached the schema.
+ */
public class BidirectionalOneToManyLinker {
private final GrailsPropertyResolver grailsPropertyResolver;
@@ -43,6 +51,7 @@ public class BidirectionalOneToManyLinker {
DependantValue key,
HibernatePersistentProperty otherSide) {
collection.setInverse(true);
+ key.disableForeignKey();
for (Column column : grailsPropertyResolver
.getProperty(associatedClass, otherSide.getName())
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 8fefa23fe1..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)
@@ -83,6 +86,9 @@ class CompositeIdentifierToManyToOneBinderSpec extends Specification {
def nestedPartA = Mock(HibernatePersistentProperty)
def nestedPartB = Mock(HibernatePersistentProperty)
+ nestedPartA.name >> "partA"
+ nestedPartB.name >> "partB"
+ // the order of the columns against a real mapping is covered by CompositeForeignKeyColumnTypesSpec
def perArray = [nestedPartA, nestedPartB] as HibernatePersistentProperty[]
nestedAssociatedEntity.getCompositeIdentity() >> perArray
@@ -117,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)
@@ -129,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)
@@ -173,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
new file mode 100644
index 0000000000..74b96c226a
--- /dev/null
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeForeignKeyColumnTypesSpec.groovy
@@ -0,0 +1,422 @@
+/*
+ * 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 grails.gorm.annotation.Entity
+import grails.gorm.hibernate.mapping.MappingBuilder
+import org.grails.orm.hibernate.HibernateDatastore
+import org.hibernate.dialect.H2Dialect
+import spock.lang.AutoCleanup
+import spock.lang.Shared
+import spock.lang.Specification
+
+/**
+ * A foreign key to an entity whose composite identifier has parts of different types must name
+ * and type each column after the referenced primary key column it points at.
+ */
+class CompositeForeignKeyColumnTypesSpec extends Specification {
+
+ @Shared
+ @AutoCleanup
+ HibernateDatastore datastore = new HibernateDatastore(
+ [
+ 'dataSource.url' : 'jdbc:h2:mem:compositeFkTypesDB;LOCK_TIMEOUT=10000',
+ 'dataSource.dbCreate' : 'create-drop',
+ 'dataSource.dialect' : H2Dialect.name,
+ 'hibernate.hbm2ddl.auto': 'create',
+ ],
+ CfkParent, CfkChild, CfkGrandParent, CfkMiddle, CfkLeaf,
+ CfkOrdParent, CfkOrdChild, CfkOrdGrand, CfkOrdMiddle, CfkOrdLeaf,
+ PrbGrand, PrbMiddle, PrbLeaf, PrbHub, PrbHubTag, PrbHubRef, PrbHubChild)
+
+ private List<List> columns(String table) {
+ List<List> rows = []
+ datastore.sessionFactory.openSession().withCloseable { session ->
+ session.doWork { Connection c ->
+ c.createStatement().withCloseable { st ->
+ st.executeQuery(
+ "select column_name, data_type from information_schema.columns where table_name = '${table}' order by ordinal_position".toString())
+ .withCloseable { rs ->
+ while (rs.next()) {
+ rows << [rs.getString(1).toLowerCase(), rs.getString(2).toUpperCase()]
+ }
+ }
+ }
+ }
+ }
+ rows
+ }
+
+
+ /**
+ * The foreign keys of a 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.
+ */
+ private Map<String, List<List<String>>> foreignKeyPairs(String table) {
+ ForeignKeyPairs.of(datastore, table)
+ }
+
+ void "a foreign key to a composite parent pairs its columns with the referenced key columns in key order"() {
+ expect:
+ foreignKeyPairs('CFK_CHILD') == [
+ cfk_parent: [['cfk_parent_lucky_number', 'lucky_number'], ['cfk_parent_name', 'name']]
+ ]
+ }
+
+ void "a foreign key to a composite parent whose parts are declared out of name order pairs the same-typed parts in key order"() {
+ expect: 'the parts are declared as zeta, alpha, and the primary key and the foreign key both follow the name order'
+ foreignKeyPairs('CFK_ORD_CHILD') == [
+ cfk_ord_parent: [['cfk_ord_parent_alpha', 'alpha'], ['cfk_ord_parent_zeta', 'zeta']]
+ ]
+ }
+
+ void "the foreign keys of a three level composite chain pair their columns with the referenced key columns in key order"() {
+ expect:
+ foreignKeyPairs('CFK_MIDDLE') == [
+ cfk_grand_parent: [['cfk_grand_parent_lucky_number', 'lucky_number'], ['cfk_grand_parent_name', 'name']]
+ ]
+ foreignKeyPairs('CFK_LEAF') == [
+ cfk_middle: [
+ ['cfk_middle_grand_parent_lucky_number', 'cfk_grand_parent_lucky_number'],
+ ['cfk_middle_grand_parent_name', 'cfk_grand_parent_name'],
+ ['cfk_middle_name', 'name']]
+ ]
+ }
+
+ void "the foreign keys of a three level chain with out of order, same-typed parts pair them in key order"() {
+ expect: 'the nested composite is declared as zeta, alpha, so only its order tells the columns apart'
+ foreignKeyPairs('CFK_ORD_MIDDLE') == [
+ cfk_ord_grand: [['cfk_ord_grand_alpha', 'alpha'], ['cfk_ord_grand_zeta', 'zeta']]
+ ]
+ foreignKeyPairs('CFK_ORD_LEAF') == [
+ cfk_ord_middle: [
+ ['cfk_ord_middle_grand_parent_alpha', 'cfk_ord_grand_alpha'],
+ ['cfk_ord_middle_grand_parent_zeta', 'cfk_ord_grand_zeta'],
+ ['cfk_ord_middle_name', 'name']]
+ ]
+ }
+
+ void "foreign key columns carry the type of the primary key column they are named after"() {
+ when:
+ Map<String, String> parent = columns('CFK_PARENT').collectEntries { [(it[0]): it[1]] }
+ Map<String, String> child = columns('CFK_CHILD').collectEntries { [(it[0]): it[1]] }
+
+ then:
+ parent.name == 'CHARACTER VARYING'
+ parent.lucky_number == 'INTEGER'
+ child.cfk_parent_name == parent.name
+ child.cfk_parent_lucky_number == parent.lucky_number
+ }
+
+ void "foreign key columns of a three level composite chain are named and typed after the referenced key"() {
+ when:
+ Map<String, String> grand = columns('CFK_GRAND_PARENT').collectEntries { [(it[0]): it[1]] }
+ Map<String, String> middle = columns('CFK_MIDDLE').collectEntries { [(it[0]): it[1]] }
+
+ Map<String, String> leaf = columns('CFK_LEAF').collectEntries { [(it[0]): it[1]] }
+
+ then:
+ grand.name
+ middle.cfk_grand_parent_name == grand.name
+ middle.cfk_grand_parent_lucky_number == grand.lucky_number
+ leaf.cfk_middle_grand_parent_name == grand.name
+ leaf.cfk_middle_grand_parent_lucky_number == grand.lucky_number
+ }
+
+ void "a leaf of a three level composite chain is saved, reloaded and found through the association"() {
+ when:
+ CfkGrandParent.withNewTransaction {
+ CfkGrandParent grand = new CfkGrandParent(name: 'Fred', luckyNumber: 7).save(failOnError: true)
+ CfkMiddle middle = new CfkMiddle(name: 'Bob', grandParent: grand).save(failOnError: true)
+ new CfkLeaf(name: 'Chuck', middle: middle).save(failOnError: true, flush: true)
+ }
+
+ then:
+ CfkLeaf.withNewSession {
+ CfkLeaf leaf = CfkLeaf.findByName('Chuck')
+ leaf.middle.name == 'Bob' && leaf.middle.grandParent.luckyNumber == 7
+ }
+ }
+
+ void "a child referencing a composite parent is saved, reloaded and found through the association"() {
+ when:
+ CfkParent.withNewTransaction {
+ CfkParent parent = new CfkParent(name: 'Fred', luckyNumber: 7).save(failOnError: true)
+ new CfkChild(label: 'kid', parent: parent).save(failOnError: true, flush: true)
+ }
+
+ then:
+ CfkChild.withNewSession {
+ CfkChild child = CfkChild.findByLabel('kid')
+ child.parent.name == 'Fred' && child.parent.luckyNumber == 7
+ }
+ CfkChild.withNewSession {
+ CfkChild.where { parent.name == 'Fred' && parent.luckyNumber == 7 }.count() == 1
+ }
+ }
+
+ void "a nested composite part that sorts after a plain part moves with all of its columns"() {
+ expect: 'the middle key is declared as name, grandParent, so grandParent spans the columns that sort before and after name'
+ foreignKeyPairs('PRB_MIDDLE') == [
+ prb_grand: [['prb_grand_alpha', 'alpha'], ['prb_grand_zeta', 'zeta']]
+ ]
+ foreignKeyPairs('PRB_LEAF') == [
+ prb_middle: [
+ ['prb_middle_grand_parent_alpha', 'prb_grand_alpha'],
+ ['prb_middle_grand_parent_zeta', 'prb_grand_zeta'],
+ ['prb_middle_name', 'name']]
+ ]
+ }
+
+ void "a leaf whose composite key nests a part declared after a plain part is saved and reloaded"() {
+ 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'
+ }
+ }
+
+ 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']]
+ ]
+
+ and: 'the child of the bidirectional one-to-many references the hub by the same key, and by that key only'
+ foreignKeyPairs('PRB_HUB_CHILD') == [
+ prb_hub: [
+ ['prb_hub_ace', 'ace'],
+ ['prb_hub_grand_alpha', 'prb_grand_alpha'],
+ ['prb_hub_grand_zeta', 'prb_grand_zeta'],
+ ['prb_hub_zed', 'zed']]
+ ]
+ }
+
+ void "a hub whose multi-column nested part sorts between two plain parts is saved with a tag, a child and a reference and reloaded"() {
+ when:
+ PrbGrand.withNewTransaction {
+ PrbGrand grand = new PrbGrand(zeta: 'z2', alpha: 'a2').save(failOnError: true)
+ PrbHub hub = new PrbHub(zed: 'zz', ace: 'aa', grand: grand)
+ .addToTags(new PrbHubTag(label: 'tag'))
+ .addToChildren(new PrbHubChild(name: 'kid'))
+ .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 == 'z2' && ref.hub.tags*.label == ['tag']
+ }
+ PrbHubChild.withNewSession {
+ PrbHubChild child = PrbHubChild.findByName('kid')
+ child.hub.zed == 'zz' && child.hub.ace == 'aa' && child.hub.grand.alpha == 'a2'
+ }
+ }
+}
+
+@Entity
+class PrbGrand implements Serializable {
+ String zeta
+ String alpha
+ static hasMany = [middles: PrbMiddle]
+
+ static mapping = MappingBuilder.define {
+ composite('zeta', 'alpha')
+ }
+}
+
+@Entity
+class PrbMiddle implements Serializable {
+ String name
+ static belongsTo = [grandParent: PrbGrand]
+ static hasMany = [leaves: PrbLeaf]
+
+ static mapping = MappingBuilder.define {
+ composite('name', 'grandParent')
+ }
+}
+
+@Entity
+class PrbLeaf implements Serializable {
+ String name
+ static belongsTo = [middle: PrbMiddle]
+
+ static mapping = MappingBuilder.define {
+ composite('middle', 'name')
+ }
+}
+
+@Entity
+class PrbHub implements Serializable {
+ String zed
+ String ace
+ PrbGrand grand
+ static hasMany = [tags: PrbHubTag, children: PrbHubChild]
+
+ static mapping = MappingBuilder.define {
+ composite('zed', 'grand', 'ace')
+ }
+}
+
+@Entity
+class PrbHubTag {
+ String label
+}
+
+@Entity
+class PrbHubChild {
+ String name
+ static belongsTo = [hub: PrbHub]
+}
+
+@Entity
+class PrbHubRef {
+ String name
+ PrbHub hub
+}
+
+@Entity
+class CfkParent implements Serializable {
+ String name
+ Integer luckyNumber
+
+ static mapping = MappingBuilder.define {
+ composite('name', 'luckyNumber')
+ }
+}
+
+@Entity
+class CfkChild implements Serializable {
+ String label
+ CfkParent parent
+
+ static mapping = MappingBuilder.define {
+ composite('parent', 'label')
+ }
+}
+
+@Entity
+class CfkLeaf implements Serializable {
+ String name
+ static belongsTo = [middle: CfkMiddle]
+
+ static mapping = MappingBuilder.define {
+ composite('middle', 'name')
+ }
+}
+
+@Entity
+class CfkMiddle implements Serializable {
+ String name
+ static belongsTo = [grandParent: CfkGrandParent]
+ static hasMany = [leaves: CfkLeaf]
+
+ static mapping = MappingBuilder.define {
+ composite('grandParent', 'name')
+ }
+}
+
+@Entity
+class CfkGrandParent implements Serializable {
+ String name
+ Integer luckyNumber
+ static hasMany = [middles: CfkMiddle]
+
+ static mapping = MappingBuilder.define {
+ composite('name', 'luckyNumber')
+ }
+}
+
+@Entity
+class CfkOrdParent implements Serializable {
+ String zeta
+ String alpha
+
+ static mapping = MappingBuilder.define {
+ composite('zeta', 'alpha')
+ }
+}
+
+@Entity
+class CfkOrdChild implements Serializable {
+ String label
+ CfkOrdParent parent
+
+ static mapping = MappingBuilder.define {
+ composite('parent', 'label')
+ }
+}
+
+@Entity
+class CfkOrdLeaf implements Serializable {
+ String name
+ static belongsTo = [middle: CfkOrdMiddle]
+
+ static mapping = MappingBuilder.define {
+ composite('middle', 'name')
+ }
+}
+
+@Entity
+class CfkOrdMiddle implements Serializable {
+ String name
+ static belongsTo = [grandParent: CfkOrdGrand]
+ static hasMany = [leaves: CfkOrdLeaf]
+
+ static mapping = MappingBuilder.define {
+ composite('grandParent', 'name')
+ }
+}
+
+@Entity
+class CfkOrdGrand implements Serializable {
+ String zeta
+ String alpha
+ static hasMany = [middles: CfkOrdMiddle]
+
+ static mapping = MappingBuilder.define {
+ composite('zeta', 'alpha')
+ }
+}
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..a73931548f
--- /dev/null
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeForeignKeyRegistrationOrderSpec.groovy
@@ -0,0 +1,225 @@
+/*
+ * 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 grails.gorm.annotation.Entity
+import org.grails.orm.hibernate.HibernateDatastore
+import org.hibernate.boot.model.naming.Identifier
+import org.hibernate.boot.model.naming.NamingHelper
+import org.hibernate.dialect.H2Dialect
+import org.hibernate.mapping.Table
+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.
+ * <p>
+ * Each foreign key must also reach the metadata once. The inverse side of a bidirectional one-to-many
+ * must not add a positional key of its own under the name of the key the to-one side creates: only the
+ * first key of a name is created in the schema, and which one that is depends on the registration order.
+ */
+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',
+ ]
+ }
+
+ /**
+ * The foreign key names that appear more than once in the Hibernate metadata, with their counts.
+ * The schema export creates only the first key of a name and logs the others as failed commands.
+ */
+ private static Map<String, Integer> duplicateForeignKeyNames(HibernateDatastore datastore) {
+ List<String> names = datastore.metadata.collectTableMappings().collectMany { Table table ->
+ table.foreignKeyCollection*.name
+ }
+ names.countBy { it }.findAll { it.value > 1 }
+ }
+
+ @Unroll
+ void "a leaf of a three level composite chain registered as #order is saved, reloaded and keyed by the referenced keys"() {
+ given:
+ HibernateDatastore datastore = new HibernateDatastore(config(classes), classes as Class[])
+
+ 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'
+ }
+
+ 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]
+
+ and: 'the inverse collections add no key of their own under the names of these keys'
+ duplicateForeignKeyNames(datastore) == [:]
+
+ cleanup:
+ datastore?.close()
+
+ where:
+ classes << [PrbGrand, PrbMiddle, PrbLeaf].permutations()
+ order = classes*.simpleName.join(', ')
+ }
+
+ @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:
+ 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']
+ }
+
+ 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']]]
+ duplicateForeignKeyNames(datastore) == [:]
+
+ cleanup:
+ datastore?.close()
+
+ where:
+ classes << [PrbGrand, PrbHub, PrbHubRef, PrbHubTag].permutations()
+ order = classes*.simpleName.join(', ')
+ }
+
+ @Unroll
+ void "the child of a bidirectional one-to-many into a hub registered as #order is saved, reloaded and keyed by the hub key"() {
+ given:
+ HibernateDatastore datastore = new HibernateDatastore(config(classes), classes as Class[])
+
+ when:
+ PrbGrand.withNewTransaction {
+ PrbGrand grand = new PrbGrand(zeta: 'z', alpha: 'a').save(failOnError: true)
+ new PrbHub(zed: 'zz', ace: 'aa', grand: grand)
+ .addToChildren(new PrbHubChild(name: 'kid'))
+ .save(failOnError: true, flush: true)
+ }
+
+ then:
+ PrbHubChild.withNewSession {
+ PrbHubChild child = PrbHubChild.findByName('kid')
+ child.hub.zed == 'zz' && child.hub.ace == 'aa' && child.hub.grand.alpha == 'a'
+ }
+
+ when:
+ Map<String, List<List<String>>> childKeys = ForeignKeyPairs.of(datastore, 'PRB_HUB_CHILD')
+
+ then:
+ childKeys == [prb_hub: HUB_KEY]
+
+ and: 'the inverse collection adds no key of its own under the name of the child key'
+ duplicateForeignKeyNames(datastore) == [:]
+
+ cleanup:
+ datastore?.close()
+
+ where:
+ classes << [PrbGrand, PrbHub, PrbHubChild].permutations()
+ order = classes*.simpleName.join(', ')
+ }
+
+ void "the inverse one-to-many of an entity with a simple identifier keeps the one implicitly named key of its to-one side"() {
+ given:
+ List<Class> classes = [PrbPlainKid, PrbPlainParent]
+ HibernateDatastore datastore = new HibernateDatastore(config(classes), classes as Class[])
+
+ when:
+ PrbPlainParent.withNewTransaction {
+ new PrbPlainParent(name: 'p').addToKids(new PrbPlainKid(name: 'k')).save(failOnError: true, flush: true)
+ }
+
+ then:
+ PrbPlainParent.withNewSession {
+ PrbPlainParent.findByName('p').kids*.name == ['k']
+ }
+
+ when:
+ Table kidTable = datastore.metadata.collectTableMappings().find { Table table -> table.name == 'prb_plain_kid' }
+
+ then: 'the key keeps the columns and the implicit name an existing schema has for it'
+ ForeignKeyPairs.of(datastore, 'PRB_PLAIN_KID') == [prb_plain_parent: [['parent_id', 'id']]]
+ kidTable.foreignKeyCollection*.name == [NamingHelper.INSTANCE.generateHashedFkName(
+ 'FK', Identifier.toIdentifier('prb_plain_kid'), Identifier.toIdentifier('prb_plain_parent'),
+ Identifier.toIdentifier('parent_id'))]
+ duplicateForeignKeyNames(datastore) == [:]
+
+ cleanup:
+ datastore?.close()
+ }
+}
+
+@Entity
+class PrbPlainParent {
+ String name
+ static hasMany = [kids: PrbPlainKid]
+}
+
+@Entity
+class PrbPlainKid {
+ String name
+ static belongsTo = [parent: PrbPlainParent]
+}
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/binder/InverseHasManyCompositeIdentifierOrderSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/InverseHasManyCompositeIdentifierOrderSpec.groovy
new file mode 100644
index 0000000000..99652b8505
--- /dev/null
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/InverseHasManyCompositeIdentifierOrderSpec.groovy
@@ -0,0 +1,109 @@
+/*
+ * 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 grails.gorm.annotation.Entity
+import grails.gorm.hibernate.mapping.MappingBuilder
+import org.grails.orm.hibernate.HibernateDatastore
+import org.hibernate.dialect.H2Dialect
+import spock.lang.AutoCleanup
+import spock.lang.PendingFeature
+import spock.lang.Shared
+import spock.lang.Specification
+
+/**
+ * An inverse {@code hasMany} on an entity with a composite identifier must load its elements whatever
+ * order the identifier is declared in. The collection key copies the columns of the to-one side, which
+ * are already in key order, and then sorts them by the owner identifier's permutation a second time,
+ * so the collection is loaded with the identifier values bound to the wrong columns unless the
+ * identifier is declared in name order already.
+ */
+class InverseHasManyCompositeIdentifierOrderSpec extends Specification {
+
+ @Shared
+ @AutoCleanup
+ HibernateDatastore datastore = new HibernateDatastore(
+ [
+ 'dataSource.url' : 'jdbc:h2:mem:inverseHasManyCompositeIdOrder;LOCK_TIMEOUT=10000',
+ 'dataSource.dbCreate' : 'create-drop',
+ 'dataSource.dialect' : H2Dialect.name,
+ 'hibernate.hbm2ddl.auto': 'create',
+ ],
+ IhmSortedParent, IhmSortedKid, IhmParent, IhmKid)
+
+ void "an inverse hasMany on a parent whose composite identifier is declared in name order loads its kids"() {
+ when:
+ IhmSortedParent.withNewTransaction {
+ new IhmSortedParent(alpha: 'a', zeta: 'z').addToKids(new IhmSortedKid(name: 'kid')).save(failOnError: true, flush: true)
+ }
+
+ then:
+ IhmSortedParent.withNewSession {
+ IhmSortedParent.findByAlphaAndZeta('a', 'z').kids*.name == ['kid']
+ }
+ }
+
+ @PendingFeature(reason = 'the collection key re-sorts the copied to-one columns by the identifier permutation, see the follow-up issue')
+ void "an inverse hasMany on a parent whose composite identifier is declared out of name order loads its kids"() {
+ when:
+ IhmParent.withNewTransaction {
+ new IhmParent(zeta: 'z', alpha: 'a').addToKids(new IhmKid(name: 'kid')).save(failOnError: true, flush: true)
+ }
+
+ then:
+ IhmParent.withNewSession {
+ IhmParent.findByZetaAndAlpha('z', 'a').kids*.name == ['kid']
+ }
+ }
+}
+
+@Entity
+class IhmParent implements Serializable {
+ String zeta
+ String alpha
+ static hasMany = [kids: IhmKid]
+
+ static mapping = MappingBuilder.define {
+ composite('zeta', 'alpha')
+ }
+}
+
+@Entity
+class IhmKid {
+ String name
+ static belongsTo = [parent: IhmParent]
+}
+
+@Entity
+class IhmSortedParent implements Serializable {
+ String alpha
+ String zeta
+ static hasMany = [kids: IhmSortedKid]
+
+ static mapping = MappingBuilder.define {
+ composite('alpha', 'zeta')
+ }
+}
+
+@Entity
+class IhmSortedKid {
+ String name
+ static belongsTo = [parent: IhmSortedParent]
+}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/BidirectionalOneToManyLinkerSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/BidirectionalOneToManyLinkerSpec.groovy
index 4e5c95eec8..5a0a5fb45e 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/BidirectionalOneToManyLinkerSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/BidirectionalOneToManyLinkerSpec.groovy
@@ -75,5 +75,9 @@ class BidirectionalOneToManyLinkerSpec extends HibernateGormDatastoreSpec {
key.getColumns().first().getLength() == 10
key.getColumns().first().getSqlType() == "bigint"
key.getColumns().first().isNullable()
+
+ and: 'the key creates no foreign key of its own, the to-one side creates the one key of the association'
+ !key.isForeignKeyEnabled()
+ !key.isConstrained()
}
}
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,