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 ce5c58e2e6797fae94f05abb387a7524329c50f8 Author: Walter Duque de Estrada <[email protected]> AuthorDate: Wed Oct 7 21:03:22 2026 -0500 feat: accept a type mapped on a collection property in native domain binding The generator refused every hasMany property with a type. The domain binder binds such a property as a collection only for a type that is neither a class nor serializable. A UserType class (or any class that is not a collection type) and serializable make the property one column of the owner's table, typed with the user type or serialized, with the index, the unique group and the column settings of any other column. A registered type name (text, string, yes_no) makes the binder fail to boot, probed for four names, and on a collection of entities the type changes nothing. The generator describes the column-bound collection like a simple property, declares the generated field with the element type Hibernate needs to take it for a basic value (a field with a collection type and no element type fails to bind), or as Serializable for the serialized one, and states the index and the unique group on the owner's table. It refuses, with the reason, a registered type name, a class on a collection of entities and a custom collection type, none of which the binder accepts or the generator describes. The unique group of such a column keeps its key, as the 8.0.x fix does for a serializable or user-typed collection. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> --- .../domainbinding/jpa/GrailsDomainGenerator.groovy | 113 ++++++- ...GeneratedDomainClassesCollectionTypeSpec.groovy | 337 +++++++++++++++++++++ ...eneratedDomainClassesDdlDifferentialSpec.groovy | 1 - .../GrailsDomainGeneratorDifferentialSpec.groovy | 11 +- .../jpa/GrailsDomainGeneratorSpec.groovy | 4 +- .../advancedGORMFeatures/nativeDomainBinding.adoc | 10 +- 6 files changed, 455 insertions(+), 21 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 f095766b4c..c9442c0e33 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 @@ -21,6 +21,7 @@ package org.grails.orm.hibernate.cfg.domainbinding.jpa import java.lang.annotation.Annotation import java.lang.reflect.Method import java.lang.reflect.Modifier +import java.sql.Types import groovy.transform.CompileStatic import jakarta.persistence.AssociationOverride @@ -68,6 +69,7 @@ import net.bytebuddy.description.annotation.AnnotationDescription import net.bytebuddy.description.method.MethodDescription import net.bytebuddy.description.modifier.TypeManifestation import net.bytebuddy.description.modifier.Visibility +import net.bytebuddy.description.type.TypeDefinition import net.bytebuddy.description.type.TypeDescription import net.bytebuddy.description.type.TypeList import net.bytebuddy.dynamic.DynamicType @@ -113,6 +115,7 @@ import org.hibernate.generator.Assigned import org.hibernate.generator.Generator import org.hibernate.type.BasicType import org.hibernate.type.spi.TypeConfiguration +import org.hibernate.usertype.UserCollectionType import org.hibernate.usertype.UserType import org.springframework.util.ClassUtils @@ -807,12 +810,12 @@ class GrailsDomainGenerator { for (HibernatePersistentProperty peer : embeddedPeers(embedded)) { collectConstraintSites(peer, current, sites) } - } else if (property instanceof HibernateBasicProperty || property instanceof HibernateToManyEntityProperty || + } else if ((property instanceof HibernateBasicProperty && !boundAsColumn(property)) || property instanceof HibernateToManyEntityProperty || isDerived(property) || (property instanceof HibernateToOneProperty && boundAsOneToOne((HibernateToOneProperty) property))) { return } else { ColumnConfig columnConfig = firstColumnConfig(property.hibernateMappedForm) - boolean enumeration = property instanceof HibernateEnumProperty + boolean enumeration = property instanceof HibernateEnumProperty && !boundAsColumn(property) String name = enumeration ? ((HibernateEnumProperty) property).resolveEnumColumnName(namingStrategy, columnNames, path) : columnNames.getColumnNameForPropertyAndPath(property, path, columnConfig) @@ -1014,9 +1017,11 @@ class GrailsDomainGenerator { } private TypeDecision decideType(HibernatePersistentProperty property) { - boolean isEnum = property instanceof HibernateEnumProperty + // a collection stored in one column is typed as a column of its own Java type, which is the collection + boolean column = boundAsColumn(property) + boolean isEnum = property instanceof HibernateEnumProperty && !column // the type of a collection property is the collection's; the binder types the element with the component type - boolean element = property instanceof HibernateBasicProperty + boolean element = property instanceof HibernateBasicProperty && !column Class<?> type = isEnum ? ((HibernateEnumProperty) property).enumType : (element ? ((HibernateBasicProperty) property).componentType : property.type) String name = property.getTypeName(type) @@ -1039,6 +1044,9 @@ class GrailsDomainGenerator { // type parameters with no type to give them to: the binder hands them to a built-in type, which ignores them return new TypeDecision(true, name, null) } + if (column && property.isSerializableType()) { + return serializedCollectionType(parameters) + } Class<?> named = loadClass(name, property) if (named != null) { return UserType.isAssignableFrom(named) ? @@ -1077,6 +1085,18 @@ class GrailsDomainGenerator { return new TypeDecision(false, name, null, problem) } + /** + * {@code serializable} on a collection stored in one column: the collection is serialized to bytes, the type Hibernate registers + * under that name for {@code Serializable}. A field declared {@code Serializable} (the property of the real class is read and + * written by its own accessors, whatever the field says) has that Java type, and the JDBC type is the binary one. + */ + private static TypeDecision serializedCollectionType(Map<String, String> parameters) { + if (!parameters.isEmpty()) { + return new TypeDecision(false, 'serializable', null, 'is a registered type with type parameters, which no annotation states') + } + return new TypeDecision(true, 'serializable', new TypeFacets(null, Types.VARBINARY, parameters, Serializable)) + } + private static Class<?> loadClass(String name, HibernatePersistentProperty property) { for (ClassLoader loader : [property.hibernateOwner.javaClass.classLoader, Thread.currentThread().contextClassLoader]) { try { @@ -1175,6 +1195,9 @@ class GrailsDomainGenerator { */ private String collectionProblem(HibernateBasicProperty property) { PropertyConfig mapped = property.hibernateMappedForm + if (boundAsColumn(property)) { + return columnCollectionProblem(property) + } String writeProblem = writeRestrictionProblem(mapped) if (writeProblem != null) { return writeProblem @@ -1188,7 +1211,7 @@ class GrailsDomainGenerator { 'the only ones the binder creates a collection for' } if (mapped.type != null) { - return 'a type is mapped on the collection property itself, which the binder applies to the collection and its element alike' + return mappedCollectionTypeProblem(property) } Class<?> elementType = property.componentType if (elementType == null || elementType == Object) { @@ -1324,6 +1347,49 @@ class GrailsDomainGenerator { !property.hibernateMappedForm.hasJoinKeyMapping() } + /** + * The binder binds a collection property as one column of the owner's table, typed with the mapping's {@code type}, when the type + * is a class that is not a collection type (a {@code UserType}, for example) or {@code serializable} + * ({@code GrailsPropertyBinder}): it is no collection then, and has the index, the unique group and the column settings of any + * other column. Any other {@code type} stays a type of the collection, which no collection of values accepts (see + * {@link #mappedCollectionTypeProblem}). + */ + private static boolean boundAsColumn(HibernatePersistentProperty property) { + return property instanceof HibernateBasicProperty && (property.isUserButNotCollectionType() || property.isSerializableType()) + } + + /** + * @return why the generator cannot describe the collection of values stored in one column ({@link #boundAsColumn}), or {@code null} + * when it can: it is described like the column of a simple property, typed with the mapping's type + */ + private String columnCollectionProblem(HibernateBasicProperty property) { + PropertyConfig mapped = property.hibernateMappedForm + if (mapped.columns != null && mapped.columns.size() > 1) { + return 'the mapping states several columns for a collection stored in one column' + } + TypeDecision type = decideType(property) + if (!type.supported) { + return "the type [${type.name}] ${type.problem}" + } + return null + } + + /** + * 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. + */ + 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 "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')" + } + /** * Decides how the binder binds a collection of basic values or enums: its table, the key column pointing at the * owner, the element column, the index (list) or key (map) column, and the fetching. @@ -1580,8 +1646,13 @@ class GrailsDomainGenerator { return compositeProblem } } - if (mapped.type != null) { - return 'a type is mapped on the collection property itself, which the binder applies to the collection and its element alike' + if (property.isUserButNotCollectionType()) { + 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 @@ -2033,6 +2104,9 @@ class GrailsDomainGenerator { * {@link Column}, in the order the binder applies them. */ ColumnFacets columnFacets(HibernatePersistentProperty property) { + if (boundAsColumn(property)) { + return basicColumnFacets(property, null, null) + } if (property instanceof HibernateBasicProperty) { throw new IllegalArgumentException( "Property [${property.name}] is a collection: it has a key, an element and perhaps an index column, see collectionFacets") @@ -2412,7 +2486,7 @@ class GrailsDomainGenerator { if (property instanceof HibernateEmbeddedProperty) { return defineEmbeddedField(builder, (HibernateEmbeddedProperty) property, embeddables, true) } - if (property instanceof HibernateBasicProperty) { + if (property instanceof HibernateBasicProperty && !boundAsColumn(property)) { return defineCollectionField(builder, (HibernateBasicProperty) property) } if (property instanceof HibernateToOneProperty) { @@ -2445,10 +2519,31 @@ class GrailsDomainGenerator { for (Annotation constraint : carriedAnnotations(property)) { annotations << AnnotationDescription.ForLoadedAnnotation.of(constraint) } - return builder.defineField(property.name, type?.javaType() ?: columnFieldType(property), Visibility.PRIVATE) + return builder.defineField(property.name, fieldType(property, type), Visibility.PRIVATE) .annotateField(annotations as AnnotationDescription[]) } + /** + * The type of the field of a column: the Java type the type facets name, else the property's. Hibernate's annotation binder takes a + * field of a collection type with no element type for a basic collection and fails to bind it, so a collection stored in one column + * is declared with its element type (and the {@code String} key of a map), and a serialized one with {@code Serializable}. + */ + private TypeDefinition fieldType(HibernatePersistentProperty property, TypeFacets type) { + if (type?.javaType() != null) { + return TypeDescription.ForLoadedType.of(type.javaType()) + } + if (boundAsColumn(property)) { + HibernateBasicProperty collection = (HibernateBasicProperty) property + Class<?> element = property instanceof HibernateEnumProperty ? ((HibernateEnumProperty) property).enumType : collection.componentType + if (element != null && element != Object) { + return CollectionKind.MAP.javaType.isAssignableFrom(property.type) ? + TypeDescription.Generic.Builder.parameterizedType(property.type, String, element).build() : + TypeDescription.Generic.Builder.parameterizedType(property.type, element).build() + } + } + return TypeDescription.ForLoadedType.of(columnFieldType(property)) + } + /** * The type of the field of a basic property. Hibernate treats a primitive field as not optional and, for every property of a * single-table hierarchy with subclasses (the properties the root declares as well as those of the subclasses), adds a table diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCollectionTypeSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCollectionTypeSpec.groovy new file mode 100644 index 0000000000..3e1114f7d1 --- /dev/null +++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCollectionTypeSpec.groovy @@ -0,0 +1,337 @@ +/* + * 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.sql.PreparedStatement +import java.sql.ResultSet +import java.sql.Types +import java.util.concurrent.atomic.AtomicInteger + +import grails.gorm.annotation.Entity +import org.hibernate.engine.spi.SharedSessionContractImplementor +import org.hibernate.mapping.Table +import org.hibernate.usertype.UserType +import spock.lang.AutoCleanup +import spock.lang.Specification +import spock.lang.Unroll + +import org.grails.orm.hibernate.HibernateDatastore + +/** + * A {@code type} mapped on a collection property. The domain binder keeps the collection a collection only when the type is + * neither a class that is not a collection type nor {@code serializable}: those two make the property one column of the owner's + * table, typed with the user type or serialized, with the index, the unique group and the column settings of any other column. A + * type name Hibernate knows ({@code text}) makes the binder fail to boot, and on a collection of entities it changes nothing. + */ +class GeneratedDomainClassesCollectionTypeSpec 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:cts${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(List<Class> group, boolean generated) { + HibernateDatastore booted = boot(group, generated) + 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 + } + + @Unroll + void "#label is one column of the owner's table, as the domain binder binds it"() { + when: + Map<String, Map> binder = schema(group, false) + Map<String, Map> generated = schema(group, true) + + then: + generated == binder + generated.keySet() == tables as Set + generated[table].columns[column] == type + + where: + label | group | tables | table | column | type + 'a set with a user type' | [CtsUserTypeSet] | ['cts_user_type_set'] | 'cts_user_type_set' | 'tags' | 'varchar(255)' + 'a list with a user type' | [CtsUserTypeList] | ['cts_user_type_list'] | 'cts_user_type_list' | 'items' | 'varchar(255)' + 'a serializable set' | [CtsSerializableSet] | ['cts_serializable_set'] | 'cts_serializable_set' | 'tags' | 'varbinary(255)' + 'a serializable list' | [CtsSerializableList] | ['cts_serializable_list'] | 'cts_serializable_list' | 'items' | 'varbinary(255)' + 'a serializable map' | [CtsSerializableMap] | ['cts_serializable_map'] | 'cts_serializable_map' | 'items' | 'varbinary(255)' + 'a serializable set of enums' | [CtsSerializableEnums] | ['cts_serializable_enums'] | 'cts_serializable_enums' | 'colors' | 'varbinary(255)' + 'a serializable set with a column config' | [CtsSerializableColumn] | ['cts_serializable_column'] | 'cts_serializable_column' | 'ser_col' | 'varbinary(100)' + 'a serializable set that is not null' | [CtsSerializableNotNull] | ['cts_serializable_not_null'] | 'cts_serializable_not_null' | 'tags' | 'varbinary(255) not null' + 'a serializable set with an index and a unique group' | [CtsSerializableKeys] | ['cts_serializable_keys'] | 'cts_serializable_keys' | 'tags' | 'varbinary(255)' + 'a set with a user type, an index and a unique group' | [CtsUserTypeKeys] | ['cts_user_type_keys'] | 'cts_user_type_keys' | 'tags' | 'varchar(255)' + } + + void "the index and the unique group of a collection stored in one column are on the owner's table, where the binder creates them"() { + when: + Map<String, Map> generated = schema([CtsSerializableKeys, CtsUserTypeKeys], true) + + then: + generated['cts_serializable_keys'].indexes == [cts_ser_idx: ['tags']] + generated['cts_serializable_keys'].uniqueKeys == [['tags', 'x']] + generated['cts_user_type_keys'].indexes == [cts_ut_idx: ['tags']] + generated['cts_user_type_keys'].uniqueKeys == [['tags', 'x']] + } + + void "a collection with a user type is stored with the user type and read back"() { + given: + boot([CtsUserTypeSet, CtsUserTypeList], true) + + when: + Long setId = CtsUserTypeSet.withTransaction { new CtsUserTypeSet(tags: ['a', 'b'] as Set).save(failOnError: true, flush: true).id } + Long listId = CtsUserTypeList.withTransaction { new CtsUserTypeList(items: ['x', 'y', 'x']).save(failOnError: true, flush: true).id } + + then: + CtsUserTypeSet.withNewSession { CtsUserTypeSet.get(setId).tags } == ['a', 'b'] as Set + CtsUserTypeList.withNewSession { CtsUserTypeList.get(listId).items } == ['x', 'y', 'x'] + datastore.connectionSources.defaultConnectionSource.dataSource.connection.withCloseable { java.sql.Connection connection -> + connection.createStatement().executeQuery('select tags from cts_user_type_set').with { ResultSet rows -> rows.next(); rows.getString(1) } + } in ['a,b', 'b,a'] + } + + @Unroll + void "a serializable #label is stored in one column, read back and updated"() { + given: + boot(group, true) + + when: + Long id = type.withTransaction { type.newInstance("${property}": initial).save(failOnError: true, flush: true).id } + type.withTransaction { type.get(id)."${property}" = changed; type.get(id).save(failOnError: true, flush: true) } + + then: + type.withNewSession { type.get(id)."${property}" } == changed + + where: + label | group | type | property | initial | changed + 'set' | [CtsSerializableSet] | CtsSerializableSet | 'tags' | ['a', 'b'] as Set | ['a', 'c'] as Set + 'list' | [CtsSerializableList] | CtsSerializableList | 'items' | ['a', 'b'] | ['b', 'a', 'z'] + 'map' | [CtsSerializableMap] | CtsSerializableMap | 'items' | [one: 'a'] | [two: 'b'] + 'enums' | [CtsSerializableEnums] | CtsSerializableEnums | 'colors' | [CtsTypeColor.RED] as Set | [CtsTypeColor.GREEN] as Set + } + + void "a type mapped on a collection of entities changes nothing in both bindings"() { + when: + Map<String, Map> binder = schema([CtsEntityTyped, CtsKid], false) + Map<String, Map> generated = schema([CtsEntityTyped, CtsKid], true) + Long id = CtsEntityTyped.withTransaction { + CtsEntityTyped owner = new CtsEntityTyped() + owner.addToKids(new CtsKid(name: 'k')) + owner.save(failOnError: true, flush: true).id + } + + then: "the collection stays a join table" + generated == binder + generated.keySet().contains('cts_entity_typed_cts_kid') + CtsEntityTyped.withNewSession { CtsEntityTyped.get(id).kids*.name } == ['k'] + } + + @Unroll + void "a #label cannot be bound by the domain binder, and the generated mode says why instead of binding something else"() { + when: + boot(group, false) + + then: "the binder fails to boot" + thrown(Exception) + + when: + boot(group, true) + + then: + Exception e = thrown() + Throwable root = e + while (root.cause != null && root.cause != root) { + root = root.cause + } + root instanceof UnsupportedOperationException + root.message.contains(message) + + where: + label | group | message + 'registered type name on the property of a collection' | [CtsNamedType] | 'names neither a class nor serializable' + 'user type class on the property of a collection of entities' | [CtsEntityUserType, CtsKid] | 'binds as one column of the owner' + } +} + +enum CtsTypeColor { RED, GREEN } + +class CtsSetType implements UserType<Set> { + int getSqlType() { Types.VARCHAR } + Class<Set> returnedClass() { Set } + boolean equals(Set x, Set y) { x == y } + int hashCode(Set x) { x.hashCode() } + Set nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) { + String text = rs.getString(position) + text == null ? null : new HashSet(text.split(',').toList()) + } + void nullSafeSet(PreparedStatement st, Set value, int index, SharedSessionContractImplementor session) { + if (value == null) { + st.setNull(index, Types.VARCHAR) + } else { + st.setString(index, value.join(',')) + } + } + Set deepCopy(Set value) { value == null ? null : new HashSet(value) } + boolean isMutable() { true } + Serializable disassemble(Set value) { value == null ? null : new HashSet(value) } + Set assemble(Serializable cached, Object owner) { cached as Set } +} + +class CtsListType implements UserType<List> { + int getSqlType() { Types.VARCHAR } + Class<List> returnedClass() { List } + boolean equals(List x, List y) { x == y } + int hashCode(List x) { x.hashCode() } + List nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) { + String text = rs.getString(position) + text == null ? null : new ArrayList(text.split(',').toList()) + } + void nullSafeSet(PreparedStatement st, List value, int index, SharedSessionContractImplementor session) { + if (value == null) { + st.setNull(index, Types.VARCHAR) + } else { + st.setString(index, value.join(',')) + } + } + List deepCopy(List value) { value == null ? null : new ArrayList(value) } + boolean isMutable() { true } + Serializable disassemble(List value) { value == null ? null : new ArrayList(value) } + List assemble(Serializable cached, Object owner) { cached as List } +} + +@Entity +class CtsUserTypeSet { + Set<String> tags + static hasMany = [tags: String] + static mapping = { tags type: CtsSetType } +} + +@Entity +class CtsUserTypeList { + List<String> items + static hasMany = [items: String] + static mapping = { items type: CtsListType } +} + +@Entity +class CtsSerializableSet { + Set<String> tags + static hasMany = [tags: String] + static mapping = { tags type: 'serializable' } +} + +@Entity +class CtsSerializableList { + List<String> items + static hasMany = [items: String] + static mapping = { items type: 'serializable' } +} + +@Entity +class CtsSerializableMap { + Map<String, String> items + static hasMany = [items: String] + static mapping = { items type: 'serializable' } +} + +@Entity +class CtsSerializableEnums { + Set<CtsTypeColor> colors + static hasMany = [colors: CtsTypeColor] + static mapping = { colors type: 'serializable' } +} + +@Entity +class CtsSerializableColumn { + Set<String> tags + static hasMany = [tags: String] + static mapping = { tags type: 'serializable', column: 'ser_col', length: 100 } +} + +@Entity +class CtsSerializableNotNull { + Set<String> tags + static hasMany = [tags: String] + static mapping = { tags type: 'serializable' } + static constraints = { tags nullable: false } +} + +@Entity +class CtsSerializableKeys { + String x + Set<String> tags + static hasMany = [tags: String] + static mapping = { tags type: 'serializable', index: 'cts_ser_idx', unique: 'x' } +} + +@Entity +class CtsUserTypeKeys { + String x + Set<String> tags + static hasMany = [tags: String] + static mapping = { tags type: CtsSetType, index: 'cts_ut_idx', unique: 'x' } +} + +@Entity +class CtsKid { + String name +} + +@Entity +class CtsEntityTyped { + Set<CtsKid> kids + static hasMany = [kids: CtsKid] + static mapping = { kids type: 'serializable' } +} + +@Entity +class CtsNamedType { + Set<String> tags + static hasMany = [tags: String] + static mapping = { tags type: 'text' } +} + +@Entity +class CtsEntityUserType { + Set<CtsKid> kids + static hasMany = [kids: CtsKid] + static mapping = { kids type: CtsSetType } +} diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassesDdlDifferentialSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassesDdlDifferentialSpec.groovy index efc61e1de2..2c5e1cc0d7 100644 --- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassesDdlDifferentialSpec.groovy +++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassesDdlDifferentialSpec.groovy @@ -83,7 +83,6 @@ class GeneratedDomainClassesDdlDifferentialSpec extends Specification { 'neither side of the many-to-many owns it', 'is registered for the Java type', 'names a class that is not a UserType', - 'a type is mapped on the collection property itself', 'is a collection inside an embedded type', 'declares a natural id but is a subclass', 'which is HibernateEmbeddedProperty', diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorDifferentialSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorDifferentialSpec.groovy index 5960b29c46..621b97914c 100644 --- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorDifferentialSpec.groovy +++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorDifferentialSpec.groovy @@ -228,7 +228,8 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { } continue } - if (property instanceof HibernateBasicProperty) { + // a collection the mapping types with a class or serializable is one column of the owner's table, compared like any column + if (property instanceof HibernateBasicProperty && !(bound?.value instanceof BasicValue)) { if (!generator.validationAnnotations(property).isEmpty()) { skipped['bean validation constraints (applied by Hibernate after binding)']++ } else if (bound == null || !(bound.value instanceof HibernateCollection)) { @@ -286,7 +287,7 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { mismatches.addAll(compareEnum(where, (HibernateEnumProperty) property, generator, bound)) } if (!(property instanceof HibernateSimpleIdentityProperty)) { - mismatches.addAll(compareType(where, property, generator, bound, explicitTypes)) + mismatches.addAll(compareType(where, property, generator, bound, explicitTypes, property instanceof HibernateBasicProperty)) } } } @@ -1066,11 +1067,11 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { */ private List<String> compareType( String where, HibernatePersistentProperty property, GrailsDomainGenerator generator, - Property bound, Map<String, Integer> explicitTypes) { + Property bound, Map<String, Integer> explicitTypes, boolean wholeCollection = false) { BasicValue value = (BasicValue) bound.value TypeFacets facets = generator.typeFacets(property) - // a collection property is typed with its element's class - Class<?> type = property instanceof HibernateBasicProperty ? ((HibernateBasicProperty) property).componentType : property.type + // a collection property is typed with its element's class, unless the whole collection is one column + Class<?> type = property instanceof HibernateBasicProperty && !wholeCollection ? ((HibernateBasicProperty) property).componentType : property.type List<String> found = [] Map<String, String> actualParameters = [:] value.typeParameters?.stringPropertyNames()?.each { String key -> actualParameters[key] = value.typeParameters.getProperty(key) } 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 2d609c3c36..59ca4f2e65 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 @@ -1296,14 +1296,14 @@ class GrailsDomainGeneratorSpec extends HibernateGormDatastoreSpec { newGenerator().unsupportedReason(entity, property).contains('SortedSet') } - void "a type mapped on the collection property itself is rejected by name"() { + void "a type name mapped on the collection property is rejected by name, because the binder gives it to the element as a class name and cannot boot"() { given: GrailsHibernatePersistentEntity entity = unbound(GenCollTyped) HibernateBasicProperty property = (HibernateBasicProperty) entity.getHibernatePropertyByName('notes') expect: !newGenerator().supports(property) - newGenerator().unsupportedReason(entity, property).contains('a type is mapped on the collection property itself') + newGenerator().unsupportedReason(entity, property).contains('names neither a class nor serializable') } void "a collection of embedded objects is rejected by name, because the binder cannot bind one"() { 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 a2af6f4c77..41a8ca0019 100644 --- a/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc +++ b/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc @@ -58,6 +58,8 @@ For the domain classes in GORM's own test suites, both bindings produce the same * All multi-tenancy modes (`DISCRIMINATOR`, `SCHEMA`, `DATABASE`) and multiple data sources work. An association still cannot refer to an entity of another data source. * Composite identifiers use the same primary key column order. * Properties mapped with a `UserType` class, and with the registered converter types `yes_no`, `true_false` and `numeric_boolean`, are stored as before. +* A `hasMany` of basic values whose `type` is `'serializable'` or a `UserType` class is stored in one column of the owner's table, as before, with the `index`, `unique` group and column settings of the property. A `type` on a `hasMany` of domain classes changes nothing in both bindings. +* An `index` on the property of a `hasMany` is created over the key column of the collection table (and over the element column of a collection of enums), and `indexColumn` may give the index of a list or the key of a map a `type` other than integer or string. * 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]] @@ -89,9 +91,9 @@ Nothing is ignored silently. A mapping that boots is bound the way it is written | `The natural id of [...] names [...], which is not a persistent property of the entity ...` | Correct the name. Classic binding skips an unknown name without a message, so the entity has no natural id. -| A `type` on the property of a collection (`hasMany`). -| `Collection property [...]: a type is mapped on the collection property itself ...` -| Remove the `type`. Classic binding applies it to the collection and to its elements alike. +| 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. | A `Map` on a many-to-many. | `Association property [...]: a map on a many-to-many ...` @@ -134,7 +136,7 @@ Nothing is ignored silently. A mapping that boots is bound the way it is written | Remove the `type` from the tenant id. |=== -A few mappings fail to boot with classic binding too, so they are not a difference between the two: a `SortedSet` of basic values, a `Map` of enums, a hierarchy that mixes inheritance strategies, a `discriminator` type other than string, integer or character, and a joined subclass of a root with a composite identifier. +A few mappings fail to boot with classic binding too, so they are not a difference between the two: a `SortedSet` of basic values, a `UserType` class as the `type` of a `hasMany` of domain classes, a `Map` of enums, a hierarchy that mixes inheritance strategies, a `discriminator` type other than string, integer or character, and a joined subclass of a root with a composite identifier. [[nativeDomainBinding-behavior]] === Differences in Behavior
