This is an automated email from the ASF dual-hosted git repository. borinquenkid pushed a commit to branch 9.0.x-h7-improvement-phase3 in repository https://gitbox.apache.org/repos/asf/grails-core.git
commit 17927c0faf3d4753b652d5c88dfbacfaea75476e Author: Walter Duque de Estrada <[email protected]> AuthorDate: Thu Oct 8 01:03:30 2026 -0500 feat: apply a custom collection type on a collection of entities in native domain binding The generator refused a UserCollectionType as the type of a hasMany of domain classes. Probed in the domain binder: it boots, with the same schema (a join table), and saves and reads the entities. It names the class to Hibernate in a way Hibernate never uses: the class is never instantiated and the collection stays Hibernate's own set. On a hasMany of basic values the same type does not boot (the binder gives the class to the element as its type), and stays refused by name with that reason. The generator now states the class with @CollectionType, so the collection is held by the type the mapping names. The schema is unchanged and the new spec compares it in both bindings and shows which mode uses the class. Dropping the annotation would reproduce the domain binder's behavior exactly, if applying a type the mapping names is not wanted. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> --- .../domainbinding/jpa/GrailsDomainGenerator.groovy | 20 ++- .../cfg/domainbinding/jpa/ToManyFacets.groovy | 6 +- ...tedDomainClassesCustomCollectionTypeSpec.groovy | 188 +++++++++++++++++++++ .../jpa/GrailsDomainGeneratorSpec.groovy | 59 ++++++- .../advancedGORMFeatures/nativeDomainBinding.adoc | 7 +- 5 files changed, 266 insertions(+), 14 deletions(-) diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGenerator.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGenerator.groovy index bdc2e5568b..dec8bee278 100644 --- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGenerator.groovy +++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGenerator.groovy @@ -81,6 +81,7 @@ import org.hibernate.annotations.BatchSize import org.hibernate.annotations.Cache import org.hibernate.annotations.CacheConcurrencyStrategy import org.hibernate.annotations.Cascade +import org.hibernate.annotations.CollectionType import org.hibernate.annotations.ColumnDefault import org.hibernate.annotations.ColumnTransformer import org.hibernate.annotations.Comment @@ -1451,14 +1452,14 @@ class GrailsDomainGenerator { /** * A {@code type} on a collection property that is neither a class nor {@code serializable}: the binder gives the name to the * element of the collection as a class name and fails to boot ({@code Could not load requested class: text}, probed for the - * registered names {@code string}, {@code text}, {@code materialized_clob} and {@code yes_no}), and a custom collection type is a - * class the generator does not describe yet. + * registered names {@code string}, {@code text}, {@code materialized_clob} and {@code yes_no}), and so does a custom collection + * type, which it gives to the element as its type. */ private static String mappedCollectionTypeProblem(HibernateBasicProperty property) { Class<?> userType = property.userType if (userType != null && UserCollectionType.isAssignableFrom(userType)) { - return 'a custom collection type (a UserCollectionType) is mapped on the collection property, which the generator does not ' + - 'support yet' + return 'a custom collection type (a UserCollectionType) is mapped on a collection of basic values: the binder gives the class to ' + + 'the element as its type and fails to boot (Named type did not implement BasicType nor UserType)' } return "the type [${property.hibernateMappedForm.typeName}] mapped on the collection property names neither a class nor " + "serializable: the binder gives the name to the element as a class name and fails to boot ('Could not load requested class')" @@ -1730,10 +1731,6 @@ class GrailsDomainGenerator { return 'a class is mapped as the type of the collection property, which the binder binds as one column of the owner\'s table ' + 'that holds the collection, and Hibernate fails to boot for a collection of entities' } - if (mapped.type != null && property.userType != null) { - return 'a custom collection type (a UserCollectionType) is mapped on the collection property, which the generator does not ' + - 'support yet' - } if (property instanceof HibernateManyToManyProperty) { HibernateAssociation other = property.hibernateInverseSide if (!(other instanceof HibernateManyToManyProperty)) { @@ -1891,7 +1888,8 @@ class GrailsDomainGenerator { keys != null ? keys : [key], keys != null ? collectionKeyReferencedColumns(property) : [], collectionIndexType(property, kind), - collectionTableIndexes(property, table, keys != null ? keys : [key], element)) + collectionTableIndexes(property, table, keys != null ? keys : [key], element), + mapped.type != null && property.userType != null && UserCollectionType.isAssignableFrom(property.userType) ? property.userType : null) } /** @@ -2777,6 +2775,10 @@ class GrailsDomainGenerator { // the binder marks the collection sorted and names no comparator: the elements' natural order annotations << AnnotationDescription.Builder.ofType(SortNatural).build() } + if (facets.collectionType() != null) { + annotations << AnnotationDescription.Builder.ofType(CollectionType) + .define('type', TypeDescription.ForLoadedType.of(facets.collectionType())).build() + } if (facets.orderProperty() != null) { annotations << AnnotationDescription.Builder.ofType(OrderBy).define('value', "${facets.orderProperty()} ${facets.orderDirection()}".toString()).build() } diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ToManyFacets.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ToManyFacets.groovy index a4a8b5fc62..29f2be2f79 100644 --- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ToManyFacets.groovy +++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ToManyFacets.groovy @@ -56,6 +56,9 @@ import org.hibernate.FetchMode * owner's table, which the table of the collection does not have. {@link GeneratedDomainClassBinder} creates the indexes on the bound * table, since the inverse side of a many-to-many has no table annotation of its own to state them on.</p> * + * <p>{@code collectionType} is the custom collection type ({@code UserCollectionType}) the mapping's {@code type} names for the collection, and + * {@code null} when it names none ({@code @CollectionType}).</p> + * * <p>{@code extraLazy} is an explicit {@code lazy: true}: the binder makes the collection extra-lazy, which Hibernate's annotation * binder cannot state, so {@code GeneratedDomainClassBinder} sets it on the collection after binding.</p> * @@ -85,5 +88,6 @@ record ToManyFacets( List<ColumnFacets> keys, List<String> referencedKeys, TypeFacets indexType, - List<IndexFacets> indexes) { + List<IndexFacets> indexes, + Class<?> collectionType = null) { } diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCustomCollectionTypeSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCustomCollectionTypeSpec.groovy new file mode 100644 index 0000000000..b30afd70e3 --- /dev/null +++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCustomCollectionTypeSpec.groovy @@ -0,0 +1,188 @@ +/* + * 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 grails.gorm.tests.generated + +import java.util.concurrent.atomic.AtomicInteger + +import grails.gorm.annotation.Entity +import org.hibernate.collection.spi.PersistentCollection +import org.hibernate.collection.spi.PersistentSet +import org.hibernate.engine.spi.SharedSessionContractImplementor +import org.hibernate.mapping.Table +import org.hibernate.metamodel.CollectionClassification +import org.hibernate.persister.collection.CollectionPersister +import org.hibernate.usertype.UserCollectionType +import spock.lang.AutoCleanup +import spock.lang.Specification + +import org.grails.orm.hibernate.HibernateDatastore + +/** + * A custom collection type ({@code UserCollectionType}) as the {@code type} of a {@code hasMany}. On a collection of domain classes both + * bindings boot with the same schema; the domain binder never uses the class, the generated mode applies it. On a collection of basic + * values the domain binder does not boot. + */ +class GeneratedDomainClassesCustomCollectionTypeSpec extends Specification { + + static final AtomicInteger BOOTS = new AtomicInteger() + + @AutoCleanup + HibernateDatastore datastore + + private HibernateDatastore boot(List<Class> group, boolean generated) { + datastore?.close() + datastore = new HibernateDatastore([ + 'dataSource.url' : "jdbc:h2:mem:tns${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(), + 'dataSource.dbCreate' : 'create-drop', + 'hibernate.generatedDomainClasses': generated, + ], group as Class[]) + return datastore + } + + /** The tables of the boot model as plain data: columns with SQL type and nullability, indexes, unique keys. */ + private Map<String, Map> schema(HibernateDatastore booted) { + Map<String, Map> result = new TreeMap<String, Map>() + for (Table table : booted.metadata.collectTableMappings()) { + if (table.physicalTable) { + result[table.name] = [ + columns : table.columns.collectEntries { org.hibernate.mapping.Column column -> + boolean nullable = column.nullable && !(table.primaryKey != null && table.primaryKey.columns*.name.contains(column.name)) + [(column.name): "${column.getSqlType(booted.metadata)}${nullable ? '' : ' not null'}${column.unique ? ' unique' : ''}".toString()] + }, + primaryKey: table.primaryKey?.columns*.name?.sort(), + indexes : table.indexes.values().collectEntries { [(it.name): it.columns*.name] }, + uniqueKeys: table.uniqueKeys.values().collect { it.columns*.name.sort() }.sort { it.toString() }, + ] + } + } + return result + } + + void "a custom collection type on a collection of entities is a table in both bindings, and only the generated mode puts the custom type to use"() { + when: + Map<Boolean, Map> observed = [false, true].collectEntries { boolean generated -> + TnSetCollectionType.CREATED.set(0) + TnSetCollectionType.WRAPS.set(0) + HibernateDatastore booted = boot([TnCollectionOwner, TnCollectionKid], generated) + Long id = TnCollectionOwner.withTransaction { + TnCollectionOwner owner = new TnCollectionOwner(name: 'o') + owner.addToKids(new TnCollectionKid(name: 'a')) + owner.addToKids(new TnCollectionKid(name: 'b')) + owner.save(failOnError: true, flush: true).id + } + Map result = TnCollectionOwner.withNewSession { + [kids: TnCollectionOwner.get(id).kids*.name.sort()] + } + result.schema = schema(booted) + result.customTypeUsed = TnSetCollectionType.CREATED.get() > 0 && TnSetCollectionType.WRAPS.get() > 0 + [(generated): result] + } + + then: "the schema and the data are the same" + observed[true].schema == observed[false].schema + observed[true].kids == ['a', 'b'] + observed[false].kids == ['a', 'b'] + observed[true].schema.keySet().containsAll(['tn_collection_owner', 'tn_collection_kid', 'tn_collection_owner_tn_collection_kid']) + + and: "the domain binder names the custom type to Hibernate in a way Hibernate never uses, so it silently keeps its own set; the generated mode applies the type the mapping names" + !observed[false].customTypeUsed + observed[true].customTypeUsed + } + + void "a custom collection type on a collection of basic values is not accepted by the domain binder, and the generated mode says why"() { + when: + boot([TnCollectionBasic], false) + + then: + thrown(Exception) + + when: + boot([TnCollectionBasic], true) + + then: + Exception e = thrown() + Throwable root = e + while (root.cause != null && root.cause != root) { + root = root.cause + } + root instanceof UnsupportedOperationException + root.message.contains('a custom collection type') + } +} + +class TnSetCollectionType implements UserCollectionType { + + static final AtomicInteger WRAPS = new AtomicInteger() + static final AtomicInteger CREATED = new AtomicInteger() + static final AtomicInteger INSTANTIATED = new AtomicInteger() + + TnSetCollectionType() { + CREATED.incrementAndGet() + } + + CollectionClassification getClassification() { CollectionClassification.SET } + + Class<?> getCollectionClass() { Set } + + PersistentCollection<?> instantiate(SharedSessionContractImplementor session, CollectionPersister persister) { + INSTANTIATED.incrementAndGet() + new PersistentSet(session) + } + + PersistentCollection<?> wrap(SharedSessionContractImplementor session, Object collection) { + WRAPS.incrementAndGet() + new PersistentSet(session, (Set) collection) + } + + Iterator<?> getElementsIterator(Object collection) { ((Set) collection).iterator() } + + boolean contains(Object collection, Object entity) { ((Set) collection).contains(entity) } + + Object indexOf(Object collection, Object entity) { null } + + Object replaceElements(Object original, Object target, CollectionPersister persister, Object owner, Map copyCache, + SharedSessionContractImplementor session) { + Set targetSet = (Set) target + targetSet.clear() + targetSet.addAll((Set) original) + targetSet + } + + Object instantiate(int anticipatedSize) { new HashSet() } +} + +@Entity +class TnCollectionKid { + String name +} + +@Entity +class TnCollectionOwner { + String name + Set<TnCollectionKid> kids + static hasMany = [kids: TnCollectionKid] + static mapping = { kids type: TnSetCollectionType } +} + +@Entity +class TnCollectionBasic { + Set<String> tags + static hasMany = [tags: String] + static mapping = { tags type: TnSetCollectionType } +} diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorSpec.groovy index 251d0801ab..f34e01b2e9 100644 --- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorSpec.groovy +++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorSpec.groovy @@ -67,6 +67,7 @@ import org.hibernate.annotations.BatchSize import org.hibernate.annotations.Cache import org.hibernate.annotations.CacheConcurrencyStrategy import org.hibernate.annotations.Cascade +import org.hibernate.annotations.CollectionType import org.hibernate.annotations.ColumnDefault import org.hibernate.annotations.Comment import org.hibernate.annotations.DiscriminatorFormula @@ -114,6 +115,7 @@ import org.hibernate.mapping.Property import org.hibernate.type.CustomType import org.hibernate.type.descriptor.WrapperOptions import org.hibernate.usertype.ParameterizedType +import org.hibernate.usertype.UserCollectionType import org.hibernate.usertype.UserType import java.sql.PreparedStatement import java.sql.ResultSet @@ -168,7 +170,7 @@ class GrailsDomainGeneratorSpec extends HibernateGormDatastoreSpec { GenOmParent, GenOmChild, GenOmListed, GenOmOrdered, GenOmOrphan, GenOmFetched, GenOmTag, GenOmStep, GenOmKept, GenOmSortedOwner, GenOmMapOwner, GenMapBidiOwner, GenMapBidiChild, GenEmbAssocOwner, GenMmStudent, GenMmCourse, GenMmPerson, GenParamsOnly, GenDecimal, GenUnversioned, GenUnversionedRoot, GenUnversionedChild, GenConverted, GenValueTyped, GenCollEmbeddedHolder, GenCollEmbeddedSibling, GenCollEmbeddedItem, GenCollEmbeddedEntityHolder, GenMapM2mLeft, GenMapM2mRight, - GenSerialized, GenTypeParams, GenConverterClass) + GenSerialized, GenTypeParams, GenConverterClass, GenCustomCollectionOwner, GenCustomCollectionKid) } List<StandardServiceRegistry> registries = [] @@ -421,6 +423,14 @@ class GrailsDomainGeneratorSpec extends HibernateGormDatastoreSpec { converted.getDeclaredField('data').type == Boolean } + void "a custom collection type on a collection of entities becomes @CollectionType"() { + given: + Map<GrailsHibernatePersistentEntity, Class<?>> classes = generateGroup(GenCustomCollectionOwner, GenCustomCollectionKid) + + expect: + classes[entity(GenCustomCollectionOwner)].getDeclaredField('kids').getAnnotation(CollectionType).type() == GenSetCollectionType + } + void "Hibernate's own annotation binder resolves a converted type like the domain binder"() { given: Map<GrailsHibernatePersistentEntity, Class<?>> classes = generateGroup(GenConverted) @@ -2871,6 +2881,53 @@ class GenConverterClass { } } +class GenSetCollectionType implements UserCollectionType { + + org.hibernate.metamodel.CollectionClassification getClassification() { org.hibernate.metamodel.CollectionClassification.SET } + + Class<?> getCollectionClass() { Set } + + org.hibernate.collection.spi.PersistentCollection<?> instantiate( + org.hibernate.engine.spi.SharedSessionContractImplementor session, org.hibernate.persister.collection.CollectionPersister persister) { + new org.hibernate.collection.spi.PersistentSet(session) + } + + org.hibernate.collection.spi.PersistentCollection<?> wrap(org.hibernate.engine.spi.SharedSessionContractImplementor session, Object collection) { + new org.hibernate.collection.spi.PersistentSet(session, (Set) collection) + } + + Iterator<?> getElementsIterator(Object collection) { ((Set) collection).iterator() } + + boolean contains(Object collection, Object entity) { ((Set) collection).contains(entity) } + + Object indexOf(Object collection, Object entity) { null } + + Object replaceElements(Object original, Object target, org.hibernate.persister.collection.CollectionPersister persister, Object owner, + Map copyCache, org.hibernate.engine.spi.SharedSessionContractImplementor session) { + target + } + + Object instantiate(int anticipatedSize) { new HashSet() } +} + +@Entity +class GenCustomCollectionKid { + + String name +} + +@Entity +class GenCustomCollectionOwner { + + Set<GenCustomCollectionKid> kids + + static hasMany = [kids: GenCustomCollectionKid] + + static mapping = { + kids type: GenSetCollectionType + } +} + class GenUpperType implements UserType<String>, ParameterizedType { @Override diff --git a/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc b/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc index 7c1478fdae..bfcc235495 100644 --- a/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc +++ b/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc @@ -65,6 +65,7 @@ For the domain classes in GORM's own test suites, both bindings produce the same * `type: 'serializable'` on a property that is not a collection (a `String`, a `byte[]` or any `Serializable`) is a binary column holding the Java serialization of the value, as with classic binding. * `params` on a registered type name such as `type: 'string'` are ignored, as with classic binding. They reach the type when it is a `UserType` that implements `ParameterizedType`. * A `type` that names an `AttributeConverter` class, for example `type: 'org.hibernate.type.YesNoConverter'`, converts the property with it, on a single property as well as on a `hasMany` stored in one column, as with classic binding. +* A custom collection type (a `UserCollectionType` class) as the `type` of a `hasMany` of domain classes is applied to the collection. Classic binding boots with the same schema but never uses the class: it keeps Hibernate's own collection. * Identifier generators, inheritance strategies (single table, joined and table-per-concrete-class), discriminators, natural ids, optimistic locking, lazy and eager fetching, cascades, sorting, batch size and `cache` usage are mapped as with classic binding. [[nativeDomainBinding-refused]] @@ -97,8 +98,8 @@ Nothing is ignored silently. A mapping that boots is bound the way it is written | Correct the name. Classic binding skips an unknown name without a message, so the entity has no natural id. | A `type` on a `hasMany` of basic values that is a registered Hibernate type name, for example `type: 'text'`, or a custom collection type. -| `Collection property [...]: the type [...] mapped on the collection property names neither a class nor serializable ...` or `... a custom collection type (a UserCollectionType) is mapped on the collection property ...` -| Remove the `type`, or use `'serializable'` or a `UserType` class to store the collection in one column. Classic binding does not boot with a registered type name (it fails with `Could not load requested class`); a custom collection type is not described yet. +| `Collection property [...]: the type [...] mapped on the collection property names neither a class nor serializable ...` or `... a custom collection type (a UserCollectionType) is mapped on a collection of basic values ...` +| Remove the `type`, or use `'serializable'` or a `UserType` class to store the collection in one column. Classic binding does not boot with a registered type name (it fails with `Could not load requested class`), and neither with a custom collection type on a collection of basic values. | A `type` that is a registered Hibernate type name for a different Java type than the property, where the type is not an interface the property implements, for example `type: 'string'` on an `Integer`. | `Type [string] of property [...] is registered for the Java type [java.lang.String], not the property's [java.lang.Integer] ...` @@ -160,7 +161,7 @@ Some bugs of classic binding are not copied by native binding. Native binding do [[nativeDomainBinding-schema]] === Differences in the Schema -The schema of 700 groups of related domain classes was created with both bindings on H2 and compared: tables, columns with type, nullability, default, length, precision and scale, primary keys with their column order, foreign keys, unique keys, indexes, check constraints and sequences. Apart from the 4 groups that native binding refuses, these are the differences. Other databases are not covered by this comparison, so verify against your own database as described below. +The schema of 702 groups of related domain classes was created with both bindings on H2 and compared: tables, columns with type, nullability, default, length, precision and scale, primary keys with their column order, foreign keys, unique keys, indexes, check constraints and sequences. Apart from the 4 groups that native binding refuses, these are the differences. Other databases are not covered by this comparison, so verify against your own database as described below. [cols="2,3,3", options="header"] |===
