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 fb745b648a1698855ecfb724275704331a48d61e Author: Walter Duque de Estrada <[email protected]> AuthorDate: Thu Oct 8 14:57:22 2026 -0500 feat: accept column settings on foreign keys in native domain binding The generated mode refused a to-one association, a collection key or a many-to-many whose column mapping sets length, precision, scale, defaultValue, read, write or comment, because a join column annotation states none of them. Probed with both modes: the domain binder ignores length, precision and scale (a foreign key column takes the type of the column it references, and a hasMany of basic values ignores them too) and puts the default, the comment and the read and write expressions [...] Co-Authored-By: Claude Sonnet 5.5 <[email protected]> --- .../jpa/GeneratedDomainClassBinder.groovy | 50 +++ .../domainbinding/jpa/GrailsDomainGenerator.groovy | 28 -- .../GeneratedDomainClassesJoinColumnSpec.groovy | 344 +++++++++++++++++++++ .../GrailsDomainGeneratorDifferentialSpec.groovy | 8 + .../GrailsDomainGeneratorOptionCoverageSpec.groovy | 36 ++- .../advancedGORMFeatures/nativeDomainBinding.adoc | 5 +- 6 files changed, 434 insertions(+), 37 deletions(-) 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 70586b01ef..d79cac710b 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 @@ -79,6 +79,7 @@ import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentP import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateBasicProperty import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateSimpleIdentityProperty import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyEntityProperty +import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToOneProperty import org.grails.orm.hibernate.cfg.domainbinding.util.BackticksRemover import org.grails.orm.hibernate.cfg.domainbinding.util.ColumnNameForPropertyAndPathFetcher import org.grails.orm.hibernate.cfg.domainbinding.util.DefaultColumnNameFetcher @@ -600,6 +601,9 @@ class GeneratedDomainClassBinder implements SessionFactoryBuilderFactory { HibernatePersistentProperty part = entity.compositeIdentity.find { HibernatePersistentProperty candidate -> candidate.name == property.name } if (part != null) { property.propertyAccessorName = propertyBinder.accessorName(part) + if (property.value instanceof ManyToOne && part instanceof HibernateToOneProperty) { + alignJoinColumns(property.value, generator.toOneFacets((HibernateToOneProperty) part).joinColumns()) + } } } } @@ -625,7 +629,11 @@ class GeneratedDomainClassBinder implements SessionFactoryBuilderFactory { if (persistentProperty instanceof HibernatePersistentProperty) { property.propertyAccessorName = propertyBinder.accessorName((HibernatePersistentProperty) persistentProperty) } + if (property.value instanceof ManyToOne && persistentProperty instanceof HibernateToOneProperty) { + alignJoinColumns(property.value, generator.toOneFacets((HibernateToOneProperty) persistentProperty).joinColumns()) + } if (property.value instanceof Collection && persistentProperty instanceof HibernatePersistentProperty) { + alignJoinColumns((Collection) property.value, (HibernatePersistentProperty) persistentProperty) alignExtraLazy((Collection) property.value, (HibernatePersistentProperty) persistentProperty) alignCollectionTable((Collection) property.value, (HibernatePersistentProperty) persistentProperty) alignListIndexLength((Collection) property.value, (HibernatePersistentProperty) persistentProperty) @@ -647,6 +655,48 @@ class GeneratedDomainClassBinder implements SessionFactoryBuilderFactory { } } + /** + * The domain binder puts the {@code defaultValue}, {@code comment}, {@code read} and {@code write} of a column config on the foreign + * key column of a to-one association, on the key column of a collection and on the element column of a many-to-many (the {@code length}, + * {@code precision} and {@code scale} change nothing, as the type of a foreign key column is the one of the column it references). A + * {@code @JoinColumn} states none of them, so they are set on the columns of the bound model. + */ + private void alignJoinColumns(Collection collection, HibernatePersistentProperty property) { + if (property instanceof HibernateToManyEntityProperty) { + ToManyFacets facets = generator.toManyFacets((HibernateToManyEntityProperty) property) + alignJoinColumns(collection.key, facets.keys()) + if (facets.manyToMany()) { + alignJoinColumns(collection.element, [facets.element()]) + } + } else if (property instanceof HibernateBasicProperty) { + alignJoinColumns(collection.key, generator.collectionFacets((HibernateBasicProperty) property).keys()) + } + } + + private static void alignJoinColumns(Value value, List<ColumnFacets> facets) { + List<Column> columns = value.selectables.findAll { it instanceof Column }.collect { (Column) it } + for (int i = 0; i < facets.size(); i++) { + ColumnFacets facet = facets[i] + Column column = columns.size() == facets.size() ? columns[i] : + columns.find { Column candidate -> candidate.name == facet.name().replace('`', '') } + if (column == null) { + continue + } + if (facet.defaultValue() != null) { + column.defaultValue = facet.defaultValue() + } + if (facet.comment() != null) { + column.comment = facet.comment() + } + if (facet.read() != null) { + column.customRead = facet.read() + } + if (facet.write() != null) { + column.customWrite = facet.write() + } + } + } + /** * An explicit {@code lazy: true} on a collection makes the domain binder bind an extra-lazy collection ({@code size()}, * {@code contains()} and {@code isEmpty()} do not initialize it). Hibernate 7's annotation binder always binds an ordinary 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 f421805393..127443eca1 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 @@ -1312,12 +1312,6 @@ class GrailsDomainGenerator { if (indexTypeProblem != null) { return indexTypeProblem } - ColumnFacets key = collectionKeyFacets(property) - if (key.length() != null || key.precision() != null || key.scale() != null || key.defaultValue() != null || - key.read() != null || key.write() != null || key.comment() != null) { - return 'the column config of the collection property sets a length, a precision, a scale, a default, a read or ' + - 'write expression or a comment, which a join column cannot state' - } return null } @@ -1722,15 +1716,6 @@ class GrailsDomainGenerator { other.hibernateMappedForm.joinTable.keys != null && other.hibernateMappedForm.joinTable.keys.size() > 1) { return 'a join table has a composite key' } - ColumnFacets key = collectionKeyFacets(property) - ColumnFacets element = toOneColumnFacets(other) - for (ColumnFacets facets : [key, element]) { - if (facets.length() != null || facets.precision() != null || facets.scale() != null || facets.defaultValue() != null || - facets.read() != null || facets.write() != null || facets.comment() != null) { - return 'the column config of a side of the many-to-many sets a length, a precision, a scale, a default, a read or ' + - 'write expression or a comment, which a join column cannot state' - } - } } else if (property.bidirectional) { if (!(property.hibernateInverseSide instanceof HibernateManyToOneProperty)) { return "the other side [${property.hibernateInverseSide?.name}] is not a many-to-one" @@ -1739,12 +1724,6 @@ class GrailsDomainGenerator { if (mapped.joinTable.keys != null && mapped.joinTable.keys.size() > 1) { return 'the join table has a composite key' } - ColumnFacets key = collectionKeyFacets(property) - if (key.length() != null || key.precision() != null || key.scale() != null || key.defaultValue() != null || - key.read() != null || key.write() != null || key.comment() != null) { - return 'the column config of the collection property sets a length, a precision, a scale, a default, a read or ' + - 'write expression or a comment, which a join column cannot state' - } } String indexTypeProblem = collectionIndexTypeProblem(property, kind) if (indexTypeProblem != null) { @@ -1898,13 +1877,6 @@ class GrailsDomainGenerator { if (mapped.derived) { return 'the association is mapped with a formula' } - for (ColumnFacets key : toOneColumnsFacets(property)) { - if (key.length() != null || key.precision() != null || key.scale() != null || key.defaultValue() != null || - key.read() != null || key.write() != null || key.comment() != null) { - return 'the column config sets a length, a precision, a scale, a default, a read or write expression or a comment, ' + - 'which a join column cannot state' - } - } return null } diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesJoinColumnSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesJoinColumnSpec.groovy new file mode 100644 index 0000000000..8ed5a9f5b1 --- /dev/null +++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesJoinColumnSpec.groovy @@ -0,0 +1,344 @@ +/* + * 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 + * + * http://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 + +/** + * Column settings on a foreign key: a to-one association, the key of a collection, the element of a many-to-many. The domain binder puts + * the {@code defaultValue}, {@code comment}, {@code read} and {@code write} of the column config on the foreign key column and ignores + * {@code length}, {@code precision} and {@code scale} (the type of the column is the one of the column it references). The generated + * mode accepts the mapping and creates the same columns, instead of refusing it. + */ +class GeneratedDomainClassesJoinColumnSpec 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:gdj${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(), + 'dataSource.dbCreate' : 'create-drop', + 'hibernate.generatedDomainClasses': generated, + ], group as Class[]) + return datastore + } + + /** The columns of the boot model with the type, nullability, comment, default and read and write expressions of each, and the foreign 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 -> + [(column.name): [ + type : "${column.getSqlType(booted.metadata)}${column.nullable ? '' : ' not null'}".toString(), + comment : column.comment, + default : column.defaultValue, + read : column.customRead, + write : column.customWrite, + ]] + }, + primaryKey : table.primaryKey?.columns*.name?.sort(), + foreignKeys: table.foreignKeys.values().collect { "${it.columns*.name} -> ${it.referencedTable.name}".toString() }.sort(), + ] + } + } + return result + } + + @Unroll + void "#label: the generated mode creates the foreign key column of the domain binder, with its comment, default and expressions"() { + when: + Map<String, Map> binder = schema(group, false) + Map<String, Map> generated = schema(group, true) + + then: + generated == binder + generated[table].columns[column].subMap(['comment', 'default', 'read', 'write']) == expected + + where: + label | group | table | column | expected + 'a many-to-one' | [GdjRef, GdjTarget] | 'gdj_ref' | 'target_id' | [comment: 'the target', default: '1', read: 'target_id', write: '?'] + 'a many-to-one to a string id' | [GdjStrRef, GdjStrTarget] | 'gdj_str_ref' | 'target_id' | [comment: 'to a string', default: null, read: null, write: null] + 'a unidirectional collection of entities' | [GdjUniOwner, GdjTarget] | 'gdj_uni_owner_gdj_target' | 'gdj_uni_owner_items_id' | [comment: 'the key', default: '0', read: 'gdj_uni_owner_items_id', write: '?'] + 'a collection of basic values' | [GdjBasicOwner] | 'gdj_basic_owner_tags' | 'gdj_basic_owner_id' | [comment: 'the tags key', default: '0', read: 'gdj_basic_owner_id', write: '?'] + 'a many-to-many' | [GdjManyA, GdjManyB] | 'gdj_manya_bs' | 'gdj_manya_id' | [comment: 'the key of A', default: null, read: null, write: null] + 'a bidirectional one-to-many' | [GdjParent, GdjKid] | 'gdj_kid' | 'parent_id' | [comment: 'the parent', default: null, read: null, write: null] + 'a many-to-one inside an embedded type' | [GdjEmbOwner, GdjTarget] | 'gdj_emb_owner' | 'holder_ref_id' | [comment: 'in the holder', default: null, read: null, write: null] + 'a part of a composite identifier' | [GdjCompPart, GdjTarget] | 'gdj_comp_part' | 'target_id' | [comment: 'the part', default: null, read: null, write: null] + 'a foreign key to a composite identifier (nothing to state)' | [GdjCompRef, GdjCompKey] | 'gdj_comp_ref' | 'k1' | [comment: null, default: null, read: null, write: null] + } + + @Unroll + void "#label: the types of the foreign key columns ignore length, precision and scale in both modes"() { + when: + Map<String, Map> binder = schema(group, false) + Map<String, Map> generated = schema(group, true) + + then: + generated == binder + generated[table].columns[column].type == type + + where: + label | group | table | column | type + 'a many-to-one to a long id' | [GdjRef, GdjTarget] | 'gdj_ref' | 'target_id' | 'bigint' + 'a many-to-one to a string id' | [GdjStrRef, GdjStrTarget] | 'gdj_str_ref' | 'target_id' | 'varchar(255)' + 'a collection of numbers with a precision' | [GdjBasicOwner] | 'gdj_basic_owner_amounts' | 'amounts_java_math_big_decimal' | 'numeric(38,2)' + } + + @Unroll + void "#label: the associations are stored and read back in both modes"() { + when: + Map<Boolean, List> results = [false, true].collectEntries { boolean generated -> + boot(group, generated) + [(generated): this."${cycle}"()] + } + + then: + results[true] == results[false] + results[true] == expected + + where: + label | group | cycle | expected + 'a many-to-one' | [GdjRef, GdjTarget] | 'refCycle' | ['t1', 't2'] + 'a unidirectional collection' | [GdjUniOwner, GdjTarget] | 'uniCycle' | [['t1', 't2'], ['t3']] + 'a collection of basic values' | [GdjBasicOwner] | 'basicCycle' | [['a', 'b'], ['c']] + 'a many-to-many' | [GdjManyA, GdjManyB] | 'manyCycle' | [['b1', 'b2'], ['b3']] + 'a bidirectional one-to-many' | [GdjParent, GdjKid] | 'kidsCycle' | [['k1', 'k2'], ['k1', 'k2', 'k3']] + } + + private List refCycle() { + Long id = GdjRef.withTransaction { new GdjRef(target: new GdjTarget(name: 't1').save(failOnError: true)).save(failOnError: true, flush: true).id } + String first = GdjRef.withNewSession { GdjRef.get(id).target.name } + GdjRef.withTransaction { GdjRef ref = GdjRef.get(id); ref.target = new GdjTarget(name: 't2').save(failOnError: true); ref.save(failOnError: true, flush: true) } + return [first, GdjRef.withNewSession { GdjRef.get(id).target.name }] + } + + private List uniCycle() { + Long id = GdjUniOwner.withTransaction { + new GdjUniOwner(items: [new GdjTarget(name: 't1').save(failOnError: true), new GdjTarget(name: 't2').save(failOnError: true)] as Set).save(failOnError: true, flush: true).id + } + List first = GdjUniOwner.withNewSession { GdjUniOwner.get(id).items*.name.sort() } + GdjUniOwner.withTransaction { + GdjUniOwner owner = GdjUniOwner.get(id) + owner.items = [new GdjTarget(name: 't3').save(failOnError: true)] as Set + owner.save(failOnError: true, flush: true) + } + return [first, GdjUniOwner.withNewSession { GdjUniOwner.get(id).items*.name.sort() }] + } + + private List basicCycle() { + Long id = GdjBasicOwner.withTransaction { new GdjBasicOwner(tags: ['a', 'b'] as Set).save(failOnError: true, flush: true).id } + List first = GdjBasicOwner.withNewSession { GdjBasicOwner.get(id).tags.sort() } + GdjBasicOwner.withTransaction { GdjBasicOwner owner = GdjBasicOwner.get(id); owner.tags = ['c'] as Set; owner.save(failOnError: true, flush: true) } + return [first, GdjBasicOwner.withNewSession { GdjBasicOwner.get(id).tags.sort() }] + } + + private List manyCycle() { + Long id = GdjManyA.withTransaction { + new GdjManyA(bs: [new GdjManyB(name: 'b1').save(failOnError: true), new GdjManyB(name: 'b2').save(failOnError: true)] as Set).save(failOnError: true, flush: true).id + } + List first = GdjManyA.withNewSession { GdjManyA.get(id).bs*.name.sort() } + GdjManyA.withTransaction { + GdjManyA owner = GdjManyA.get(id) + owner.bs = [new GdjManyB(name: 'b3').save(failOnError: true)] as Set + owner.save(failOnError: true, flush: true) + } + return [first, GdjManyA.withNewSession { GdjManyA.get(id).bs*.name.sort() }] + } + + private List kidsCycle() { + Long id = GdjParent.withTransaction { + GdjParent parent = new GdjParent() + parent.addToKids(new GdjKid(name: 'k1')) + parent.addToKids(new GdjKid(name: 'k2')) + parent.save(failOnError: true, flush: true).id + } + List first = GdjParent.withNewSession { GdjParent.get(id).kids*.name.sort() } + GdjParent.withTransaction { + GdjParent parent = GdjParent.get(id) + parent.addToKids(new GdjKid(name: 'k3')) + parent.save(failOnError: true, flush: true) + } + return [first, GdjParent.withNewSession { GdjParent.get(id).kids*.name.sort() }] + } +} + +@Entity +class GdjTarget { + String name +} + +@Entity +class GdjRef { + GdjTarget target + + static mapping = { + target length: 20, precision: 10, scale: 2, defaultValue: '1', comment: 'the target', read: 'target_id', write: '?' + } +} + +@Entity +class GdjStrTarget { + String code + String name + + static mapping = { + id name: 'code', generator: 'assigned' + } +} + +@Entity +class GdjStrRef { + GdjStrTarget target + + static mapping = { + target length: 20, comment: 'to a string' + } +} + +@Entity +class GdjUniOwner { + Set<GdjTarget> items + + static hasMany = [items: GdjTarget] + + static mapping = { + items length: 20, comment: 'the key', defaultValue: '0', read: 'gdj_uni_owner_items_id', write: '?' + } +} + +@Entity +class GdjBasicOwner { + Set<String> tags + Set<BigDecimal> amounts + + static hasMany = [tags: String, amounts: BigDecimal] + + static mapping = { + tags length: 20, comment: 'the tags key', defaultValue: '0', read: 'gdj_basic_owner_id', write: '?' + amounts precision: 10, scale: 2 + } +} + +@Entity +class GdjManyA { + Set<GdjManyB> bs + + static hasMany = [bs: GdjManyB] + + static mapping = { + bs comment: 'the key of A' + } +} + +@Entity +class GdjManyB { + String name + Set<GdjManyA> owners + + static hasMany = [owners: GdjManyA] + static belongsTo = [GdjManyA] +} + +@Entity +class GdjParent { + Set<GdjKid> kids + + static hasMany = [kids: GdjKid] + + static mapping = { + kids comment: 'ignored: the key is the column of the kid' + } +} + +@Entity +class GdjKid { + String name + GdjParent parent + + static belongsTo = [parent: GdjParent] + + static mapping = { + parent comment: 'the parent' + } +} + +class GdjHolder { + GdjTarget ref + + static mapping = { + ref comment: 'in the holder' + } +} + +@Entity +class GdjEmbOwner { + GdjHolder holder + + static embedded = ['holder'] +} + +@Entity +class GdjCompPart implements Serializable { + GdjTarget target + String code + + static mapping = { + id composite: ['target', 'code'] + target comment: 'the part' + } +} + +@Entity +class GdjCompKey implements Serializable { + String a + String b + + static mapping = { + id composite: ['a', 'b'] + } +} + +@Entity +class GdjCompRef { + GdjCompKey key + + static mapping = { + columns { + key { + column name: 'k1' + column name: 'k2' + } + } + } +} 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 dc4e81e26d..80c50c5d98 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 @@ -2018,6 +2018,14 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { pairs.remove('precision') pairs.remove('scale') } + if (key || bound.value instanceof ToOne) { + ['default', 'read', 'write', 'comment'].each { String facet -> + if (pairs[facet] != null && pairs[facet][1] == null) { + known['the default, comment and read and write expressions of a foreign key column: a join column annotation cannot state them, GeneratedDomainClassBinder sets them after binding']++ + pairs.remove(facet) + } + } + } found.addAll(pairs.findAll { String facet, List values -> values[0] != values[1] }.collect { String facet, List values -> "${where} ${facet}: generator=${values[1]} binder=${values[0]}".toString() }) diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorOptionCoverageSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorOptionCoverageSpec.groovy index 0f1c2aa71a..862200c33e 100644 --- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorOptionCoverageSpec.groovy +++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorOptionCoverageSpec.groovy @@ -40,6 +40,7 @@ import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateBasicProper import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateEmbeddedProperty import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyEntityProperty +import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToOneProperty /** * Guards the rule that {@link GrailsDomainGenerator} never drops a mapping option without a word. Every option of @@ -107,9 +108,9 @@ class GrailsDomainGeneratorOptionCoverageSpec extends GrailsDomainGeneratorSuppo 'column.enumType' : ['mode', 'modes'], 'column.index' : KINDS - ['home'], 'column.unique' : KINDS - ['home'], - 'column.length' : KINDS - ['home'], - 'column.precision' : KINDS - ['home'], - 'column.scale' : KINDS - ['home'], + 'column.length' : KINDS - ['home'] - ['target', 'tags', 'targets', 'ordered'], + 'column.precision' : KINDS - ['home'] - ['target', 'tags', 'targets', 'ordered'], + 'column.scale' : KINDS - ['home'] - ['target', 'tags', 'targets', 'ordered'], 'column.defaultValue' : KINDS - ['home'], 'column.comment' : KINDS - ['home'], 'column.read' : KINDS - ['home'], @@ -134,6 +135,11 @@ class GrailsDomainGeneratorOptionCoverageSpec extends GrailsDomainGeneratorSuppo private static final Map<String, List<String>> IGNORED_LIKE_THE_BINDER = [ 'property.insertable': NO_COLUMN_KINDS, 'property.updatable' : NO_COLUMN_KINDS, + // the type of a foreign key column is the one of the column it references, and the binder ignores the length, precision and scale + // of a collection of basic values too + 'column.length' : ['target', 'tags', 'targets', 'ordered'], + 'column.precision' : ['target', 'tags', 'targets', 'ordered'], + 'column.scale' : ['target', 'tags', 'targets', 'ordered'], ] /** Options that change nothing anywhere, and why that is no silent drop. */ @@ -431,7 +437,7 @@ class GrailsDomainGeneratorOptionCoverageSpec extends GrailsDomainGeneratorSuppo /** * What the generator decides for the group: the generated classes (annotations and fields) and the facets that no annotation * carries but the binding of the generated classes applies to the bound properties: an extra-lazy collection, the indexes of the - * table of a collection and a lazy embedded property. + * table of a collection, a lazy embedded property and the default, comment and read and write expressions of a foreign key column. */ private String signature() { Map<GrailsHibernatePersistentEntity, Class<?>> classes = generateGroup(GenCovOwner, GenCovTarget) @@ -445,7 +451,7 @@ class GrailsDomainGeneratorOptionCoverageSpec extends GrailsDomainGeneratorSuppo } private static String appliedAfterBinding(GrailsDomainGenerator generator, GrailsHibernatePersistentEntity entity) { - return entity.hibernatePersistentProperties.findAll { HibernatePersistentProperty property -> + String lazyAndIndexes = entity.hibernatePersistentProperties.findAll { HibernatePersistentProperty property -> if (property instanceof HibernateBasicProperty && generator.supports(property)) { CollectionFacets facets = generator.collectionFacets((HibernateBasicProperty) property) return facets.extraLazy() || !facets.indexes().isEmpty() @@ -459,6 +465,26 @@ class GrailsDomainGeneratorOptionCoverageSpec extends GrailsDomainGeneratorSuppo } return false }*.name.sort().join(',') + return lazyAndIndexes + '#' + joinColumnExtras(generator, entity) + } + + private static String joinColumnExtras(GrailsDomainGenerator generator, GrailsHibernatePersistentEntity entity) { + Closure<String> extras = { ColumnFacets facets -> "${facets.defaultValue()}|${facets.comment()}|${facets.read()}|${facets.write()}".toString() } + return entity.hibernatePersistentProperties.collect { HibernatePersistentProperty property -> + if (!generator.supports(property)) { + return '' + } + if (property instanceof HibernateToOneProperty) { + return "${property.name}=${generator.toOneFacets((HibernateToOneProperty) property).joinColumns().collect(extras)}".toString() + } + if (property instanceof HibernateToManyEntityProperty) { + return "${property.name}=${generator.toManyFacets((HibernateToManyEntityProperty) property).keys().collect(extras)}".toString() + } + if (property instanceof HibernateBasicProperty) { + return "${property.name}=${generator.collectionFacets((HibernateBasicProperty) property).keys().collect(extras)}".toString() + } + return '' + }.join(';') } } 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 ef9c0526b5..02fbc86614 100644 --- a/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc +++ b/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc @@ -71,6 +71,7 @@ For the domain classes in GORM's own test suites, both bindings produce the same * `insertable: false` and `updatable: false` are honored on a property with a column. On an embedded object they apply to every column of the object. On a `hasMany` and on the inverse side of a one-to-one (the side with no column) both bindings ignore them: the collection is written through its own table, and the foreign key lives on the other side. * A `discriminator` column may set `precision` and `scale`. They change nothing in the DDL of a string, integer or character column, in both bindings. * A multi-tenant id (`tenantId`) may have a mapped `type`: its column has the type, and the tenant filter still compares it with the current tenant. +* The `defaultValue`, `comment`, `read` and `write` of the column mapping of an association or of a `hasMany` are put on the foreign key column (on the key column of a collection, and on the element column of a many-to-many for the options of the other side). The `length`, `precision` and `scale` change nothing: a foreign key column has the type of the column it references, and a `hasMany` of basic values ignores them too. This is the same in both bindings. * 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]] @@ -102,10 +103,6 @@ Nothing is ignored silently. A mapping that boots is bound the way it is written | `... composite identifier ...`, naming the entity and the part. | Give the entity a single-column identifier, or map the relationship with a domain class of its own. -| A foreign key, join column or collection key whose column mapping sets `length`, `precision`, `scale`, `defaultValue`, `read`, `write` or `comment`. -| `... the column config ... sets a length, a precision, a scale, a default, a read or write expression or a comment, which a join column cannot state` -| Remove the option. A join column takes its type from the column it references. - | An association mapped with a `formula`, or with several columns where the target does not have a composite identifier. | `... the association is mapped with a formula` or `... the mapping states several columns ...` | Map the association with a single `column`.
