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/04/06 19:16:57 UTC

(grails-core) 07/12: H7: rewrite CollectionBinder using fluent and modular method structure

This is an automated email from the ASF dual-hosted git repository.

borinquenkid pushed a commit to branch 8.0.x-hibernate7-dev
in repository https://gitbox.apache.org/repos/asf/grails-core.git

commit 6c7709c0b5c652de0856025ddd3dbd838b896ec8
Author: Walter Duque de Estrada <wb...@mac.com>
AuthorDate: Sun Apr 5 00:35:24 2026 -0500

    H7: rewrite CollectionBinder using fluent and modular method structure
---
 .../cfg/domainbinding/binder/CollectionBinder.java | 139 +++++++++------------
 .../collectionType/CollectionHolder.java           |   7 ++
 .../hibernate/HibernateOneToManyProperty.java      |   6 +
 .../hibernate/HibernatePersistentProperty.java     |  10 ++
 .../hibernate/HibernateToManyProperty.java         |  28 +++--
 5 files changed, 99 insertions(+), 91 deletions(-)

diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CollectionBinder.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CollectionBinder.java
index 2cfe6e43ca..4c73e84c82 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CollectionBinder.java
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CollectionBinder.java
@@ -18,23 +18,17 @@
  */
 package org.grails.orm.hibernate.cfg.domainbinding.binder;
 
-import org.hibernate.FetchMode;
 import org.hibernate.boot.spi.InFlightMetadataCollector;
 import org.hibernate.boot.spi.MetadataBuildingContext;
 import org.hibernate.mapping.Collection;
 import org.hibernate.mapping.OneToMany;
-import org.hibernate.mapping.PersistentClass;
-import org.hibernate.mapping.Table;
 
-import org.grails.orm.hibernate.cfg.GrailsHibernateUtil;
 import org.grails.orm.hibernate.cfg.JoinTable;
 import org.grails.orm.hibernate.cfg.PersistentEntityNamingStrategy;
 import org.grails.orm.hibernate.cfg.PropertyConfig;
-import org.grails.orm.hibernate.cfg.domainbinding.util.DefaultColumnNameFetcher;
 import org.grails.orm.hibernate.cfg.domainbinding.collectionType.CollectionHolder;
-import org.grails.orm.hibernate.cfg.domainbinding.collectionType.CollectionType;
+import org.grails.orm.hibernate.cfg.domainbinding.util.DefaultColumnNameFetcher;
 import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyEntityProperty;
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty;
 import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyProperty;
 import org.grails.orm.hibernate.cfg.domainbinding.secondpass.BasicCollectionElementBinder;
 import org.grails.orm.hibernate.cfg.domainbinding.secondpass.BidirectionalMapElementBinder;
@@ -55,13 +49,12 @@ import org.grails.orm.hibernate.cfg.domainbinding.secondpass.PrimaryKeyValueCrea
 import org.grails.orm.hibernate.cfg.domainbinding.secondpass.SetSecondPass;
 import org.grails.orm.hibernate.cfg.domainbinding.secondpass.UnidirectionalOneToManyBinder;
 import org.grails.orm.hibernate.cfg.domainbinding.secondpass.UnidirectionalOneToManyInverseValuesBinder;
-import org.grails.orm.hibernate.cfg.domainbinding.util.CascadeBehavior;
 import org.grails.orm.hibernate.cfg.domainbinding.util.GrailsPropertyResolver;
 import org.grails.orm.hibernate.cfg.domainbinding.util.NamespaceNameExtractor;
 import org.grails.orm.hibernate.cfg.domainbinding.util.SimpleValueColumnFetcher;
 import org.grails.orm.hibernate.cfg.domainbinding.util.TableForManyCalculator;
 
-import static org.grails.orm.hibernate.cfg.GrailsHibernateUtil.qualify;
+import static org.grails.orm.hibernate.cfg.domainbinding.util.CascadeBehavior.ALL_DELETE_ORPHAN;
 
 /** Handles the binding of collections to the Hibernate runtime meta model. */
 @SuppressWarnings("PMD.DataflowAnomalyAnalysis")
@@ -140,100 +133,82 @@ public class CollectionBinder {
      * @return the result
      */
     public Collection bindCollection(HibernateToManyProperty property, String path) {
-        PersistentClass _persistentClass = property.getHibernateOwner().getPersistentClass();
-        CollectionType collectionType = collectionHolder.get(property.getType());
-        Collection collection = collectionType.create(property, _persistentClass);
-        property.setCollection(collection);
+        Collection collection = initializeCollection(property, path);
 
-        // set role
-        String propertyName = getNameForPropertyAndPath(property, path);
-        collection.setRole(qualify(property.getHibernateOwner().getName(), propertyName));
-
-        PropertyConfig pc = property.getHibernateMappedForm();
-        // configure eager fetching
-        final FetchMode fetchMode = pc.getFetchMode();
-        if (fetchMode == FetchMode.JOIN) {
-            collection.setFetchMode(FetchMode.JOIN);
-        } else if (pc.getFetchMode() != null) {
-            collection.setFetchMode(pc.getFetchMode());
-        } else {
-            collection.setFetchMode(FetchMode.DEFAULT);
-        }
+        configureCollectionMetadata(property, collection);
 
-        if (pc.getCascade() != null) {
-            collection.setOrphanDelete(pc.getCascade().equals(CascadeBehavior.ALL_DELETE_ORPHAN.getValue()));
-        }
-        // if it's a one-to-many mapping
         if (property.shouldBindWithForeignKey()) {
-            OneToMany oneToMany = new OneToMany(metadataBuildingContext, collection.getOwner());
-            collection.setElement(oneToMany);
-            bindOneToMany((HibernateToManyEntityProperty) property, oneToMany);
+            bindOneToManyElement((HibernateToManyEntityProperty) property, collection);
         } else {
-            bindCollectionTable(property, _persistentClass.getTable());
-
-            if (property.isBidirectional()) {
-                if (!property.isOwningSide()) {
-                    collection.setInverse(true);
-                }
-            } else {
-                collection.setInverse(false);
-            }
+            bindCollectionTable(property, collection);
         }
 
-        if (pc.getBatchSize() != null) {
-            collection.setBatchSize(pc.getBatchSize());
-        }
+        registerSecondPass(property, collection);
 
-        // set up second pass
-        if (collection instanceof org.hibernate.mapping.List) {
-            mappings.addSecondPass(new ListSecondPass(listSecondPassBinder, property));
-        } else if (collection instanceof org.hibernate.mapping.Map) {
-            mappings.addSecondPass(new MapSecondPass(mapSecondPassBinder, property));
-        } else { // Collection -> Bag
-            mappings.addSecondPass(new SetSecondPass(collectionSecondPassBinder, property));
-        }
         mappings.addCollectionBinding(collection);
+
         return collection;
     }
 
-    private String getNameForPropertyAndPath(HibernatePersistentProperty property, String path) {
-        if (GrailsHibernateUtil.isNotEmpty(path)) {
-            return qualify(path, property.getName());
-        }
-        return property.getName();
+    private Collection initializeCollection(HibernateToManyProperty property, String path) {
+        Collection collection = collectionHolder.create(property);
+        property.setCollection(collection);
+        collection.setRole(property.getRole(path));
+        return collection;
+    }
+
+    private void configureCollectionMetadata(HibernateToManyProperty property, Collection collection) {
+        collection.setFetchMode(property.getFetchMode());
+        collection.setOrphanDelete(ALL_DELETE_ORPHAN.getValue().equals(property.getCascade()));
+        collection.setBatchSize(property.getBatchSize());
     }
 
-    private void bindOneToMany(HibernateToManyEntityProperty currentGrailsProp, OneToMany one) {
-        one.setReferencedEntityName(
-                currentGrailsProp.getHibernateAssociatedEntity().getName());
-        one.setIgnoreNotFound(true);
+    private void bindOneToManyElement(HibernateToManyEntityProperty property, Collection collection) {
+        OneToMany oneToMany = new OneToMany(metadataBuildingContext, collection.getOwner());
+        oneToMany.setReferencedEntityName(property.getHibernateAssociatedEntity().getName());
+        oneToMany.setIgnoreNotFound(true);
+        collection.setElement(oneToMany);
     }
 
-    private void bindCollectionTable(HibernateToManyProperty property, Table ownerTable) {
-        Collection collection = property.getCollection();
-        String owningTableSchema = ownerTable.getSchema();
+    private void bindCollectionTable(HibernateToManyProperty property, Collection collection) {
+        String owningTableSchema = property.getTable().getSchema();
         PropertyConfig config = property.getHibernateMappedForm();
-        JoinTable jt = config.getJoinTable();
+        JoinTable joinTable = config.getJoinTable();
 
-        String s = new TableForManyCalculator(namingStrategy).calculateTableForMany(property);
-        String tableName = (jt != null && jt.getName() != null ? jt.getName() : namingStrategy.resolveTableName(s));
+        String logicalName = new TableForManyCalculator(namingStrategy).calculateTableForMany(property);
+        String tableName = (joinTable != null && joinTable.getName() != null) ?
+                joinTable.getName() : namingStrategy.resolveTableName(logicalName);
 
-        String schemaName = NamespaceNameExtractor.getSchemaName(mappings);
-        String catalogName = NamespaceNameExtractor.getCatalogName(mappings);
-        if (jt != null) {
-            if (jt.getSchema() != null) {
-                schemaName = jt.getSchema();
-            }
-            if (jt.getCatalog() != null) {
-                catalogName = jt.getCatalog();
-            }
+        String schemaName = getJoinTableSchema(joinTable, owningTableSchema);
+        String catalogName = getJoinTableCatalog(joinTable);
+
+        collection.setCollectionTable(
+                mappings.addTable(schemaName, catalogName, tableName, null, false, metadataBuildingContext));
+        collection.setInverse(property.isBidirectional() && !property.isOwningSide());
+    }
+
+    private String getJoinTableSchema(JoinTable joinTable, String owningTableSchema) {
+        if (joinTable != null && joinTable.getSchema() != null) {
+            return joinTable.getSchema();
         }
+        String schemaName = NamespaceNameExtractor.getSchemaName(mappings);
+        return (schemaName == null) ? owningTableSchema : schemaName;
+    }
 
-        if (schemaName == null && owningTableSchema != null) {
-            schemaName = owningTableSchema;
+    private String getJoinTableCatalog(JoinTable joinTable) {
+        if (joinTable != null && joinTable.getCatalog() != null) {
+            return joinTable.getCatalog();
         }
+        return NamespaceNameExtractor.getCatalogName(mappings);
+    }
 
-        collection.setCollectionTable(
-                mappings.addTable(schemaName, catalogName, tableName, null, false, metadataBuildingContext));
+    private void registerSecondPass(HibernateToManyProperty property, Collection collection) {
+        if (collection instanceof org.hibernate.mapping.List) {
+            mappings.addSecondPass(new ListSecondPass(listSecondPassBinder, property));
+        } else if (collection instanceof org.hibernate.mapping.Map) {
+            mappings.addSecondPass(new MapSecondPass(mapSecondPassBinder, property));
+        } else {
+            mappings.addSecondPass(new SetSecondPass(collectionSecondPassBinder, property));
+        }
     }
 }
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/collectionType/CollectionHolder.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/collectionType/CollectionHolder.java
index cab6f27be5..459f359fa8 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/collectionType/CollectionHolder.java
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/collectionType/CollectionHolder.java
@@ -25,6 +25,9 @@ import java.util.Set;
 import java.util.SortedSet;
 
 import org.hibernate.boot.spi.MetadataBuildingContext;
+import org.hibernate.mapping.PersistentClass;
+
+import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyProperty;
 
 /** Collection holder. */
 public record CollectionHolder(Map<Class<?>, CollectionType> map) {
@@ -43,4 +46,8 @@ public record CollectionHolder(Map<Class<?>, CollectionType> map) {
     public CollectionType get(Class<?> collectionClass) {
         return map.get(collectionClass);
     }
+
+    public org.hibernate.mapping.Collection create(HibernateToManyProperty property) {
+        return map.get(property.getType()).create(property, property.getPersistentClass());
+    }
 }
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateOneToManyProperty.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateOneToManyProperty.java
index fc8bda609a..02654871cb 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateOneToManyProperty.java
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateOneToManyProperty.java
@@ -19,6 +19,7 @@
 package org.grails.orm.hibernate.cfg.domainbinding.hibernate;
 
 import java.beans.PropertyDescriptor;
+import java.util.Map;
 
 import org.hibernate.MappingException;
 import org.hibernate.mapping.Collection;
@@ -70,4 +71,9 @@ public class HibernateOneToManyProperty extends OneToManyWithMapping<PropertyCon
         }
         return this;
     }
+
+    @Override
+    public boolean shouldBindWithForeignKey() {
+        return (isBidirectional() || !isUnidirectionalOneToMany()) && !Map.class.isAssignableFrom(getType());
+    }
 }
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernatePersistentProperty.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernatePersistentProperty.java
index dc31cdb3cf..314cc3f5d8 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernatePersistentProperty.java
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernatePersistentProperty.java
@@ -32,10 +32,13 @@ import org.grails.datastore.mapping.model.PersistentProperty;
 import org.grails.datastore.mapping.model.types.Association;
 import org.grails.datastore.mapping.model.types.Embedded;
 import org.grails.orm.hibernate.cfg.ColumnConfig;
+import org.grails.orm.hibernate.cfg.GrailsHibernateUtil;
 import org.grails.orm.hibernate.cfg.Mapping;
 import org.grails.orm.hibernate.cfg.PropertyConfig;
 
 import static java.util.Optional.ofNullable;
+import static org.grails.orm.hibernate.cfg.GrailsHibernateUtil.isNotEmpty;
+import static org.grails.orm.hibernate.cfg.GrailsHibernateUtil.qualify;
 
 /** Interface for Hibernate persistent properties */
 public interface HibernatePersistentProperty extends PersistentProperty<PropertyConfig> {
@@ -254,4 +257,11 @@ public interface HibernatePersistentProperty extends PersistentProperty<Property
     default HibernatePersistentProperty validateProperty() {
         return this;
     }
+
+    default String getNameForPropertyAndPath(String path) {
+        if (isNotEmpty(path)) {
+            return qualify(path, getName());
+        }
+        return getName();
+    }
 }
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateToManyProperty.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateToManyProperty.java
index 4976eb08d3..a4628ca94c 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateToManyProperty.java
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateToManyProperty.java
@@ -38,6 +38,8 @@ import org.grails.orm.hibernate.cfg.PropertyConfig;
 import org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsDomainBinder;
 import org.grails.orm.hibernate.cfg.domainbinding.util.BackticksRemover;
 
+import static java.util.Optional.ofNullable;
+import static org.grails.orm.hibernate.cfg.GrailsHibernateUtil.qualify;
 import static org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsDomainBinder.UNDERSCORE;
 
 /** Marker interface for Hibernate to-many associations */
@@ -68,7 +70,7 @@ public interface HibernateToManyProperty extends PropertyWithMapping<PropertyCon
     }
 
     default String getCacheUsage() {
-        return Optional.ofNullable(getHibernateMappedForm())
+        return ofNullable(getHibernateMappedForm())
                 .map(PropertyConfig::getCache)
                 .map(CacheConfig::getUsage)
                 .map(Object::toString)
@@ -99,11 +101,7 @@ public interface HibernateToManyProperty extends PropertyWithMapping<PropertyCon
      * @return Whether the collection should be bound with a foreign key
      */
     default boolean shouldBindWithForeignKey() {
-        return ((this instanceof HibernateOneToManyProperty) && isBidirectional() || !isUnidirectionalOneToMany()) &&
-                !Map.class.isAssignableFrom(getType()) &&
-                !(this instanceof HibernateManyToManyProperty) &&
-                !(this instanceof Basic) &&
-                !(this instanceof HibernateEmbeddedCollectionProperty);
+        return false;
     }
 
     default String getIndexColumnName(PersistentEntityNamingStrategy namingStrategy) {
@@ -189,7 +187,7 @@ public interface HibernateToManyProperty extends PropertyWithMapping<PropertyCon
     }
 
     default String getMapElementName(PersistentEntityNamingStrategy namingStrategy) {
-        return java.util.Optional.ofNullable(getHibernateMappedForm())
+        return ofNullable(getHibernateMappedForm())
                 .map(PropertyConfig::getJoinTable)
                 .map(JoinTable::getColumn)
                 .map(ColumnConfig::getName)
@@ -199,7 +197,7 @@ public interface HibernateToManyProperty extends PropertyWithMapping<PropertyCon
     }
 
     default String resolveJoinTableForeignKeyColumnName(PersistentEntityNamingStrategy namingStrategy) {
-        return java.util.Optional.ofNullable(getHibernateMappedForm())
+        return ofNullable(getHibernateMappedForm())
                 .map(PropertyConfig::getJoinTableColumnConfig)
                 .map(ColumnConfig::getName)
                 .orElseGet(() -> namingStrategy.resolveColumnName(getHibernateAssociatedEntity()
@@ -228,7 +226,7 @@ public interface HibernateToManyProperty extends PropertyWithMapping<PropertyCon
 
     @NonNull
     default Optional<ColumnConfig> getColumnConfigOptional() {
-        return Optional.ofNullable(getHibernateMappedForm()).map(PropertyConfig::getJoinTableColumnConfig);
+        return ofNullable(getHibernateMappedForm()).map(PropertyConfig::getJoinTableColumnConfig);
     }
 
     @Override
@@ -251,4 +249,16 @@ public interface HibernateToManyProperty extends PropertyWithMapping<PropertyCon
     Collection getCollection();
 
     void setCollection(Collection collection);
+
+    default String getCascade() {
+        return getHibernateMappedForm().getCascade();
+    }
+
+    default Integer getBatchSize() {
+        return ofNullable(getHibernateMappedForm()).map(PropertyConfig::getBatchSize).orElse(-1);
+    }
+
+    default String getRole(String path) {
+        return qualify(getHibernateOwner().getName(), getNameForPropertyAndPath(path));
+    }
 }