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 6895d3af6cc8bae90552e06aec69862dd45861b8 Author: Walter Duque de Estrada <[email protected]> AuthorDate: Wed Oct 7 20:05:06 2026 -0500 feat: type the index of a list and the key of a map as the mapping says in native domain binding A map whose indexColumn (or index settings) carries a type other than string, or a list whose index carries a type other than integer, was refused. The domain binder types the key column of a map and the index column of a list with the registered type the mapping names, whatever the declared key class is. The generator now states the Java type of the key in the generics of the generated field and with @MapKeyJdbcTypeCode for a map, and the Java and JDBC type of the index with @ListIndexJavaType and @ListIndexJdbcTypeCode for a list. Hibernate sizes the index column of a list typed as a string as a long string, so the aligner gives it the default length of every column the domain binder creates. The differentials compare the Java and JDBC type of the index as well. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> --- .../cfg/domainbinding/jpa/CollectionFacets.groovy | 8 +- .../jpa/GeneratedDomainClassBinder.groovy | 27 +++ .../domainbinding/jpa/GrailsDomainGenerator.groovy | 114 ++++++++++-- .../cfg/domainbinding/jpa/ToManyFacets.groovy | 8 +- ...atedDomainClassesCollectionIndexTypeSpec.groovy | 194 +++++++++++++++++++++ ...eneratedDomainClassesDdlDifferentialSpec.groovy | 1 - .../GrailsDomainGeneratorDifferentialSpec.groovy | 27 +++ .../advancedGORMFeatures/nativeDomainBinding.adoc | 4 - 8 files changed, 358 insertions(+), 25 deletions(-) diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/CollectionFacets.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/CollectionFacets.groovy index f1a34957ad..ebde8f77e4 100644 --- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/CollectionFacets.groovy +++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/CollectionFacets.groovy @@ -36,6 +36,11 @@ import org.hibernate.FetchMode * a composite identifier; {@code referencedKeys} names the column of the owner's key each one points at, and is empty unless the * owner has a composite identifier. {@code key} is the first of the key columns.</p> * + * <p>{@code indexType} is the type the binder gives the index column of a list or the key column of a map when the mapping types it + * ({@code indexColumn: [type: 'long']}), independently of the declared key class: the Java type and the JDBC type of the registered + * type of that name. It is {@code null} when the mapping states none, or the type is the default (an integer for a list, a string for + * a map). A list's index stays an integer in Java whatever its JDBC type; the key of a map is typed with the facets' Java type.</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> * @@ -56,5 +61,6 @@ record CollectionFacets( int batchSize, String cacheUsage, List<ColumnFacets> keys, - List<String> referencedKeys) { + List<String> referencedKeys, + TypeFacets indexType) { } diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassBinder.groovy index 59f6c5ebfb..8a63ef0851 100644 --- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassBinder.groovy +++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassBinder.groovy @@ -21,6 +21,7 @@ package org.grails.orm.hibernate.cfg.domainbinding.jpa import java.lang.reflect.Field import groovy.transform.CompileStatic +import org.hibernate.Length import org.hibernate.MappingException import org.hibernate.boot.SessionFactoryBuilder import org.hibernate.boot.internal.InFlightMetadataCollectorImpl @@ -46,11 +47,14 @@ import org.hibernate.mapping.Column import org.hibernate.mapping.Component import org.hibernate.mapping.ForeignKey import org.hibernate.mapping.GeneratorSettings +import org.hibernate.mapping.IndexedCollection import org.hibernate.mapping.ManyToOne import org.hibernate.mapping.PersistentClass import org.hibernate.mapping.PrimaryKey import org.hibernate.mapping.Property import org.hibernate.mapping.RootClass +import org.hibernate.mapping.List as HibernateList +import org.hibernate.mapping.Selectable import org.hibernate.mapping.Set as HibernateSet import org.hibernate.mapping.Table import org.hibernate.mapping.UniqueKey @@ -551,6 +555,7 @@ class GeneratedDomainClassBinder implements SessionFactoryBuilderFactory { if (property.value instanceof Collection && persistentProperty instanceof HibernatePersistentProperty) { alignExtraLazy((Collection) property.value, (HibernatePersistentProperty) persistentProperty) alignCollectionTable((Collection) property.value, (HibernatePersistentProperty) persistentProperty) + alignListIndexLength((Collection) property.value, (HibernatePersistentProperty) persistentProperty) } if (property.value instanceof Component && persistentProperty instanceof Embedded) { // PropertyBinder marks the property lazy when the mapping says lazy: true; @Basic(fetch = LAZY) on an @Embedded is ignored @@ -587,6 +592,28 @@ class GeneratedDomainClassBinder implements SessionFactoryBuilderFactory { } } + /** + * Hibernate's annotation binder gives the index column of a list no length, which it sizes as a long string when the mapping types + * the index as a string (a CLOB, which cannot be a key). The domain binder's column has the default length of every column it creates. + */ + private void alignListIndexLength(Collection collection, HibernatePersistentProperty property) { + TypeFacets indexType + if (property instanceof HibernateToManyEntityProperty) { + indexType = generator.toManyFacets((HibernateToManyEntityProperty) property).indexType() + } else if (property instanceof HibernateBasicProperty) { + indexType = generator.collectionFacets((HibernateBasicProperty) property).indexType() + } else { + return + } + if (indexType != null && collection instanceof HibernateList) { + for (Selectable selectable : ((IndexedCollection) collection).index.selectables) { + if (selectable instanceof Column) { + ((Column) selectable).length = (long) Length.DEFAULT + } + } + } + } + /** * Hibernate's annotation binder forces the key and element columns of a collection table not null ("I break the spec, but it's * for good"), where the domain binder leaves them nullable unless they are part of the primary key, and a set whose element 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 16456786a0..7fa9930039 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 @@ -93,6 +93,9 @@ import org.hibernate.annotations.FetchMode as AnnotationFetchMode import org.hibernate.annotations.Formula import org.hibernate.annotations.Immutable import org.hibernate.annotations.JdbcTypeCode +import org.hibernate.annotations.ListIndexJavaType +import org.hibernate.annotations.ListIndexJdbcTypeCode +import org.hibernate.annotations.MapKeyJdbcTypeCode import org.hibernate.annotations.NaturalId as HibernateNaturalId import org.hibernate.annotations.NotFound import org.hibernate.annotations.NotFoundAction @@ -1215,13 +1218,9 @@ class GrailsDomainGenerator { if (kind == CollectionKind.MAP && type.facets != null) { return 'a mapped element type on a map' } - if (kind == CollectionKind.LIST && property.getIndexColumnType('integer') != 'integer') { - return "the index column type [${property.getIndexColumnType('integer')}] is not integer" - } - if (kind == CollectionKind.MAP && property.getIndexColumnType('string') != 'string') { - return "the index column of the map is mapped with the type [${property.getIndexColumnType('string')}], which the binder gives the key " + - 'independently of the declared key class; the generator types the key as the declared String and would need ' + - '@MapKeyJdbcTypeCode to say another type, which it does not write yet' + String indexTypeProblem = collectionIndexTypeProblem(property, kind) + if (indexTypeProblem != null) { + return indexTypeProblem } ColumnFacets key = collectionKeyFacets(property) if (key.length() != null || key.precision() != null || key.scale() != null || key.defaultValue() != null || @@ -1345,7 +1344,8 @@ class GrailsDomainGenerator { Math.max(property.batchSize, 0), property.cacheUsage, collectionKeyColumns(property), - collectionKeyReferencedColumns(property)) + collectionKeyReferencedColumns(property), + collectionIndexType(property, kind)) } /** @@ -1442,6 +1442,54 @@ class GrailsDomainGenerator { column.precision?.intValue(), column.scale?.intValue(), column.sqlType, null, null, null, null) } + /** + * The binder types the index column of a list and the key column of a map with the type the mapping names + * ({@code indexColumn: [type: 'long']}, or the {@code type} of the {@code index:} settings), whatever the declared key class is. + * + * @return why the generator cannot state that type, or {@code null} when it can (or the mapping states none) + */ + private String collectionIndexTypeProblem(HibernateToManyProperty property, CollectionKind kind) { + if (!kind.indexed) { + return null + } + String name = property.getIndexColumnType(kind == CollectionKind.LIST ? 'integer' : 'string') + BasicType<?> registered = typeConfiguration.basicTypeRegistry.getRegisteredType(name) + if (registered == null) { + return "the index column type [${name}] is not a type registered with Hibernate, which is the only kind of type the generator " + + 'states for the index of a list or the key of a map' + } + if (registered.valueConverter != null) { + return "the index column type [${name}] is a registered type that converts its value, which no annotation states for the " + + 'index of a list or the key of a map' + } + if (kind == CollectionKind.LIST) { + Class<?> descriptor = javaTypeDescriptorClass(registered.javaTypeDescriptor.javaTypeClass) + if (!Modifier.isPublic(descriptor.modifiers) || descriptor.constructors.every { it.parameterCount != 0 }) { + return "the index column type [${name}] has a Java type descriptor [${descriptor.simpleName}] that Hibernate cannot instantiate " + + 'from an annotation, which is how the generator types the index of a list' + } + } + return null + } + + /** + * @return the type of the index column of a list or the key column of a map when the mapping types it with other than the + * default (an integer for a list, a string for a map), as the Java and the JDBC type of the registered type of that name; + * {@code null} otherwise + */ + private TypeFacets collectionIndexType(HibernateToManyProperty property, CollectionKind kind) { + if (!kind.indexed) { + return null + } + String defaultName = kind == CollectionKind.LIST ? 'integer' : 'string' + String name = property.getIndexColumnType(defaultName) + if (name == defaultName) { + return null + } + BasicType<?> registered = typeConfiguration.basicTypeRegistry.getRegisteredType(name) + return new TypeFacets(null, registered.jdbcType.defaultSqlTypeCode, [:], registered.javaTypeDescriptor.javaTypeClass) + } + /** * Mirrors {@code ListSecondPassBinder} (a nullable index column named by {@code getIndexColumnName}) and * {@code MapSecondPassBinder} (the same name, plus the index column config's facets); {@code null} for a set or a bag. @@ -1566,13 +1614,9 @@ class GrailsDomainGenerator { 'write expression or a comment, which a join column cannot state' } } - if (kind == CollectionKind.LIST && property.getIndexColumnType('integer') != 'integer') { - return "the index column type [${property.getIndexColumnType('integer')}] is not integer" - } - if (kind == CollectionKind.MAP && property.getIndexColumnType('string') != 'string') { - return "the index column of the map is mapped with the type [${property.getIndexColumnType('string')}], which the binder gives the key " + - 'independently of the declared key class; the generator types the key as the declared String and would need ' + - '@MapKeyJdbcTypeCode to say another type, which it does not write yet' + String indexTypeProblem = collectionIndexTypeProblem(property, kind) + if (indexTypeProblem != null) { + return indexTypeProblem } if (property.hasSort()) { if (kind.indexed) { @@ -1687,7 +1731,8 @@ class GrailsDomainGenerator { property.hasSort() ? (property.order != null ? property.order : 'asc') : null, condition, keys != null ? keys : [key], - keys != null ? collectionKeyReferencedColumns(property) : []) + keys != null ? collectionKeyReferencedColumns(property) : [], + collectionIndexType(property, kind)) } /** @@ -2538,8 +2583,10 @@ class GrailsDomainGenerator { .define('name', facets.index().name()) .define('nullable', facets.index().nullable()) .build() + annotations.addAll(listIndexTypeAnnotations(facets.indexType())) } else if (facets.kind() == CollectionKind.MAP) { annotations << mapKeyColumnAnnotation(facets.index()) + annotations.addAll(mapKeyTypeAnnotations(facets.indexType())) } if (facets.kind() == CollectionKind.SORTED_SET) { // the binder marks the collection sorted and names no comparator: the elements' natural order @@ -2573,7 +2620,7 @@ class GrailsDomainGenerator { annotations << AnnotationDescription.ForLoadedAnnotation.of(constraint) } List<TypeDescription> arguments = facets.kind() == CollectionKind.MAP ? - [TypeDescription.ForLoadedType.of(String), generatedType(property.hibernateAssociatedEntity)] : + [TypeDescription.ForLoadedType.of(mapKeyClass(facets.indexType())), generatedType(property.hibernateAssociatedEntity)] : [generatedType(property.hibernateAssociatedEntity)] TypeDescription.Generic fieldType = TypeDescription.Generic.Builder.parameterizedType( TypeDescription.ForLoadedType.of(facets.kind().javaType), arguments).build() @@ -2646,8 +2693,10 @@ class GrailsDomainGenerator { .define('name', facets.index().name()) .define('nullable', facets.index().nullable()) .build() + annotations.addAll(listIndexTypeAnnotations(facets.indexType())) } else if (facets.kind() == CollectionKind.MAP) { annotations << mapKeyColumnAnnotation(facets.index()) + annotations.addAll(mapKeyTypeAnnotations(facets.indexType())) } TypeFacets type = typeFacets(property) if (type != null) { @@ -2670,7 +2719,7 @@ class GrailsDomainGenerator { Class<?> elementClass = property instanceof HibernateEnumProperty ? ((HibernateEnumProperty) property).enumType : ((HibernateBasicProperty) property).componentType TypeDescription.Generic fieldType = facets.kind() == CollectionKind.MAP ? - TypeDescription.Generic.Builder.parameterizedType(Map, String, elementClass).build() : + TypeDescription.Generic.Builder.parameterizedType(Map, mapKeyClass(facets.indexType()), elementClass).build() : TypeDescription.Generic.Builder.parameterizedType(facets.kind().javaType, elementClass).build() return builder.defineField(property.name, fieldType, Visibility.PRIVATE) .annotateField(annotations as AnnotationDescription[]) @@ -2701,6 +2750,35 @@ class GrailsDomainGenerator { return annotation.build() } + /** The Java type of the key of a map: the declared one is a string, the mapping can type the key column with another registered type. */ + private static Class<?> mapKeyClass(TypeFacets indexType) { + return indexType == null ? String : indexType.javaType() + } + + /** The Java and the JDBC type of the index column of a list, which the binder types as the mapping says, as it types the key of a map. */ + private List<AnnotationDescription> listIndexTypeAnnotations(TypeFacets indexType) { + if (indexType == null) { + return [] + } + return [ + AnnotationDescription.Builder.ofType(ListIndexJavaType).define('value', TypeDescription.ForLoadedType.of(javaTypeDescriptorClass(indexType.javaType()))).build(), + AnnotationDescription.Builder.ofType(ListIndexJdbcTypeCode).define('value', indexType.jdbcTypeCode()).build(), + ] + } + + /** The class of Hibernate's Java type descriptor of a Java type, which an annotation names and Hibernate instantiates. */ + private Class<?> javaTypeDescriptorClass(Class<?> javaType) { + return typeConfiguration.javaTypeRegistry.getDescriptor(javaType).getClass() + } + + /** The JDBC type of the key column of a map; its Java type is the key of the generated field. */ + private static List<AnnotationDescription> mapKeyTypeAnnotations(TypeFacets indexType) { + if (indexType == null) { + return [] + } + return [AnnotationDescription.Builder.ofType(MapKeyJdbcTypeCode).define('value', indexType.jdbcTypeCode()).build()] + } + private static AnnotationDescription mapKeyColumnAnnotation(ColumnFacets facets) { AnnotationDescription.Builder annotation = AnnotationDescription.Builder.ofType(MapKeyColumn) .define('name', facets.name()) 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 2acc0b2fc6..0b5bd9502a 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 @@ -44,6 +44,11 @@ import org.hibernate.FetchMode * a composite identifier; {@code referencedKeys} names the column of the owner's key each one points at, and is empty unless the * owner has a composite identifier. {@code key} is the first of the key columns.</p> * + * <p>{@code indexType} is the type the binder gives the index column of a list or the key column of a map when the mapping types it + * ({@code indexColumn: [type: 'long']}), independently of the declared key class: the Java type and the JDBC type of the registered + * type of that name. It is {@code null} when the mapping states none, or the type is the default (an integer for a list, a string for + * a map). A list's index stays an integer in Java whatever its JDBC type; the key of a map is typed with the facets' Java type.</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> * @@ -71,5 +76,6 @@ record ToManyFacets( String orderDirection, String tenantCondition, List<ColumnFacets> keys, - List<String> referencedKeys) { + List<String> referencedKeys, + TypeFacets indexType) { } diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCollectionIndexTypeSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCollectionIndexTypeSpec.groovy new file mode 100644 index 0000000000..d30cb11fad --- /dev/null +++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCollectionIndexTypeSpec.groovy @@ -0,0 +1,194 @@ +/* + * 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.mapping.Table +import spock.lang.AutoCleanup +import spock.lang.Specification +import spock.lang.Unroll + +import org.grails.orm.hibernate.HibernateDatastore + +/** + * The index column of a list and the key column of a map are typed by the mapping ({@code indexColumn: [type: 'long']}, or the + * {@code type} of the {@code index:} settings), independently of the declared key class, and the domain binder gives them that + * type. The generated classes state it with Hibernate's own annotations, so a database created by the binder keeps its schema and + * the keys of a map are read back as the type the column holds. + */ +class GeneratedDomainClassesCollectionIndexTypeSpec 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:cit${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(), + 'dataSource.dbCreate' : 'create-drop', + 'hibernate.generatedDomainClasses': generated, + ], group as Class[]) + return datastore + } + + /** The collection tables of the boot model as plain data: every column with its SQL type, nullability and length. */ + 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 -> + // a primary key column is not null in the schema whatever the column says + boolean nullable = column.nullable && !(table.primaryKey != null && table.primaryKey.columns*.name.contains(column.name)) + [(column.name): "${column.getSqlType(booted.metadata)}${nullable ? '' : ' not null'}".toString()] + }, + primaryKey: table.primaryKey?.columns*.name?.sort(), + ] + } + } + return result + } + + @Unroll + void "#label is typed in the generated mode as the domain binder types it"() { + when: + Map<String, Map> binder = schema(group, false) + Map<String, Map> generated = schema(group, true) + + then: "the column and the key it is part of are the binder's (the binder leaves an unused column in the table of a map of values)" + binder[table].columns[column] == type + generated[table].columns[column] == type + generated[table].primaryKey == binder[table].primaryKey + generated.keySet() == binder.keySet() + + where: + label | group | table | column | type + 'the key of a map of entities, mapped as long' | [CitLongMap, CitValue] | 'cit_long_map_tags' | 'tags_idx' | 'long not null' + 'the key of a map of values, mapped as long' | [CitValueMap] | 'cit_value_map_attrs' | 'k' | 'long not null' + 'the key of a map, mapped as integer and named' | [CitIntegerMap] | 'cit_integer_map_attrs' | 'k' | 'integer not null' + 'the key of a map, with a length' | [CitLengthMap] | 'cit_length_map_attrs' | 'k' | 'varchar(40) not null' + 'the index of a list, mapped as long' | [CitLongList] | 'cit_long_list_items' | 'ix' | 'bigint not null' + 'the index of a list, mapped as string' | [CitStringList] | 'cit_string_list_items' | 'ix' | 'varchar(255) not null' + 'the index of a list of entities, mapped as long' | [CitEntityList, CitValue] | 'cit_entity_list_cit_value' | 'ix' | 'bigint not null' + } + + void "a map keyed by long saves, reloads and is queried with the keys the column holds"() { + given: + boot([CitLongMap, CitValue], true) + + when: + Long id = CitLongMap.withTransaction { + CitLongMap owner = new CitLongMap() + owner.tags = [(1L): new CitValue(name: 'one').save(failOnError: true), (22L): new CitValue(name: 'two').save(failOnError: true)] + owner.save(failOnError: true, flush: true).id + } + + then: + CitLongMap.withNewSession { + Map<Long, CitValue> loaded = CitLongMap.get(id).tags + loaded.keySet() == [1L, 22L] as Set && loaded[22L].name == 'two' + } + } + + void "the index of a list mapped as long keeps the order of the elements"() { + given: + boot([CitLongList, CitStringList], true) + + when: + Long longId = CitLongList.withTransaction { new CitLongList(items: ['c', 'a', 'b']).save(failOnError: true, flush: true).id } + Long stringId = CitStringList.withTransaction { new CitStringList(items: ['z', 'y']).save(failOnError: true, flush: true).id } + + then: + CitLongList.withNewSession { CitLongList.get(longId).items } == ['c', 'a', 'b'] + CitStringList.withNewSession { CitStringList.get(stringId).items } == ['z', 'y'] + } +} + +@Entity +class CitValue { + String name +} + +@Entity +class CitLongMap { + Map<Long, CitValue> tags + static hasMany = [tags: CitValue] + static mapping = { + tags indexColumn: [type: 'long'] + } +} + +@Entity +class CitValueMap { + Map<String, String> attrs + static hasMany = [attrs: String] + static mapping = { + attrs indexColumn: [type: 'long', name: 'k'] + } +} + +@Entity +class CitIntegerMap { + Map<Integer, String> attrs + static hasMany = [attrs: String] + static mapping = { + attrs indexColumn: [type: 'integer', name: 'k'] + } +} + +@Entity +class CitLengthMap { + Map<String, String> attrs + static hasMany = [attrs: String] + static mapping = { + attrs indexColumn: [name: 'k', length: 40] + } +} + +@Entity +class CitLongList { + List<String> items + static hasMany = [items: String] + static mapping = { + items indexColumn: [type: 'long', name: 'ix'] + } +} + +@Entity +class CitStringList { + List<String> items + static hasMany = [items: String] + static mapping = { + items indexColumn: [type: 'string', name: 'ix'] + } +} + +@Entity +class CitEntityList { + List<CitValue> values + static hasMany = [values: CitValue] + static mapping = { + values indexColumn: [type: 'long', name: 'ix'] + } +} 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 5db18f52d3..c91853f0cc 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 @@ -88,7 +88,6 @@ class GeneratedDomainClassesDdlDifferentialSpec extends Specification { 'which is HibernateEmbeddedProperty', 'which is not a persistent property of the entity', 'is a registered type with type parameters', - 'the index column of the map is mapped with the type', 'a map on a many-to-many', ] 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 620e26ab98..e036390f7f 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 @@ -18,6 +18,8 @@ */ package org.grails.orm.hibernate.cfg.domainbinding.jpa +import java.sql.Types + import jakarta.persistence.InheritanceType import grails.gorm.tests.HibernateGormDatastoreSpec import org.hibernate.FetchMode @@ -822,6 +824,7 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { if (collection instanceof IndexedCollection) { found.addAll(compareValueColumn( "${where} index".toString(), facets.index(), ((IndexedCollection) collection).index, collection.collectionTable, false)) + found.addAll(compareIndexType("${where} index".toString(), facets.kind(), facets.indexType(), (IndexedCollection) collection)) } else { found << "${where} index: generator=${facets.index().name()} binder=none".toString() } @@ -1666,6 +1669,7 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { if (collection instanceof IndexedCollection) { found.addAll(compareValueColumn( "${where} index".toString(), facets.index(), ((IndexedCollection) collection).index, collection.collectionTable, false)) + found.addAll(compareIndexType("${where} index".toString(), facets.kind(), facets.indexType(), (IndexedCollection) collection)) } else { found << "${where} index: generator=${facets.index().name()} binder=none".toString() } @@ -1675,6 +1679,29 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { return found } + /** + * The type the binder gave the index column of a list or the key column of a map against the one the generator decided: the JDBC type + * and the Java type of both. + */ + private static List<String> compareIndexType(String where, CollectionKind kind, TypeFacets indexType, IndexedCollection collection) { + if (!(collection.index instanceof BasicValue)) { + return [] + } + BasicValue index = (BasicValue) collection.index + List<String> found = [] + int expectedJdbc = indexType != null ? indexType.jdbcTypeCode() : (kind == CollectionKind.LIST ? Types.INTEGER : Types.VARCHAR) + int boundJdbc = index.resolve().jdbcType.defaultSqlTypeCode + if (expectedJdbc != boundJdbc) { + found << "${where} jdbcTypeCode: generator=${expectedJdbc} binder=${boundJdbc}".toString() + } + Class<?> expectedJava = indexType != null ? indexType.javaType() : (kind == CollectionKind.LIST ? Integer : String) + Class<?> boundJava = index.resolve().domainJavaType.javaTypeClass + if (expectedJava != boundJava) { + found << "${where} javaType: generator=${expectedJava.name} binder=${boundJava.name}".toString() + } + return found + } + /** * A collection of entities against the one Hibernate's annotation binder built from the generated field: the same kind, * ownership, join table, key, element and index columns, fetching, cascade, ordering and filters. 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 887b6ec058..981de8025c 100644 --- a/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc +++ b/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc @@ -101,10 +101,6 @@ Nothing is ignored silently. A mapping that boots is bound the way it is written | `Association property [...]: a map on a many-to-many ...` | Use a `Set` or `List` many-to-many, or model the join with a domain class of its own. -| A map whose `indexColumn` has a `type` other than string, or a list whose `indexColumn` has a `type` other than integer. -| `... the index column of the map is mapped with the type [long] ...` or `... the index column type [long] is not integer` -| Remove the `type` from `indexColumn`. Use `String` map keys and the default list index. - | A `type` that is a registered Hibernate type name for a different Java type than the property, for example `type: 'serializable'` on a `String`. | `Type [serializable] of property [...] is registered for the Java type [java.io.Serializable], not the property's [java.lang.String] ...` | Use a `UserType` class, or a type name registered for the property's own type.
