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 73415618cdce5e6bd5eea0535bf5e04a18d0454e Author: Walter Duque de Estrada <[email protected]> AuthorDate: Thu Oct 8 15:49:28 2026 -0500 feat: accept a discriminator of any registered type in native domain binding The generated mode refused a discriminator whose type is not string, integer or character, and the manual said the domain binder cannot boot one either. Probed: the binder boots a hierarchy with type: 'long' and creates a bigint discriminator column. @DiscriminatorColumn names only string, integer and character, so the annotation states a string and the aligner binds the discriminator of the model again with the type name of the mapping, in a copy of the column that has no JDBC type y [...] Co-Authored-By: Claude Sonnet 5.5 <[email protected]> --- .../jpa/GeneratedDomainClassBinder.groovy | 45 +++++++++++++++++++++- .../domainbinding/jpa/GrailsDomainGenerator.groovy | 8 ++-- .../GeneratedDomainClassesDiscriminatorSpec.groovy | 33 ++++++++++++++-- .../GrailsDomainGeneratorDifferentialSpec.groovy | 8 +++- .../advancedGORMFeatures/nativeDomainBinding.adoc | 4 +- 5 files changed, 86 insertions(+), 12 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 975e37967c..01e77175f4 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 jakarta.persistence.DiscriminatorType import org.hibernate.Length import org.hibernate.MappingException import org.hibernate.boot.SessionFactoryBuilder @@ -46,6 +47,7 @@ import org.hibernate.mapping.Collection import org.hibernate.mapping.Column import org.hibernate.mapping.Component import org.hibernate.mapping.ForeignKey +import org.hibernate.mapping.Formula import org.hibernate.mapping.GeneratorSettings import org.hibernate.mapping.IndexedCollection import org.hibernate.mapping.ManyToOne @@ -121,6 +123,7 @@ class GeneratedDomainClassBinder implements SessionFactoryBuilderFactory { private final MultiTenantFilterDefinitionBinder filterDefinitionBinder = new MultiTenantFilterDefinitionBinder() private final UniqueNameGenerator uniqueNameGenerator = new UniqueNameGenerator() private PersistentEntityNamingStrategy namingStrategy + private MetadataBuildingContext buildingContext private JdbcEnvironment jdbcEnvironment private GrailsDomainGenerator generator private GeneratedDomainClassLoaderService classLoaderService @@ -161,6 +164,7 @@ class GeneratedDomainClassBinder implements SessionFactoryBuilderFactory { PersistentEntityNamingStrategy namingStrategy, JdbcEnvironment jdbcEnvironment) { this.namingStrategy = namingStrategy + this.buildingContext = buildingContext this.jdbcEnvironment = jdbcEnvironment List<GrailsHibernatePersistentEntity> toGenerate = hierarchies(entities) if (toGenerate.isEmpty()) { @@ -361,13 +365,28 @@ class GeneratedDomainClassBinder implements SessionFactoryBuilderFactory { /** * The mapping can give the discriminator column a precision and a scale, which {@code @DiscriminatorColumn} cannot state. They change * nothing in the DDL of the string, integer or character column, but the domain binder puts them on the column of the model, so the - * same is done here and a schema comparison finds the same column. + * same is done here and a schema comparison finds the same column. It can also give the discriminator another type than string, integer + * or character ({@code type: 'long'}), which the annotation cannot name either: the type name is put on the discriminator of the model. */ private void alignDiscriminator(RootClass root, GrailsHibernatePersistentEntity entity) { DiscriminatorFacets discriminator = generator.hierarchyFacets(entity).discriminator() if (discriminator == null || root.discriminator == null) { return } + if (discriminator.type() == DiscriminatorType.STRING && !(discriminator.typeName() in ['string', 'java.lang.String'])) { + // the annotation can only name a string, an integer or a character; the binder gives the discriminator the type the mapping + // names, and Hibernate has resolved the one the annotation named by now, so the discriminator is bound again with the type + BasicValue retyped = new BasicValue(buildingContext, root.table) + retyped.typeName = discriminator.typeName() + for (Selectable selectable : ((BasicValue) root.discriminator).selectables) { + if (selectable instanceof Column) { + retyped.addColumn(untypedCopy(root.table, (Column) selectable, discriminator.sqlType())) + } else if (selectable instanceof Formula) { + retyped.addFormula((Formula) selectable) + } + } + root.discriminator = retyped + } for (Selectable selectable : root.discriminator.selectables) { if (selectable instanceof Column) { if (discriminator.precision() != null) { @@ -380,6 +399,30 @@ class GeneratedDomainClassBinder implements SessionFactoryBuilderFactory { } } + /** + * A column whose JDBC type Hibernate has resolved cannot be given another one, so the column of a discriminator that is typed again is + * replaced, in the same place of the table, by a copy that has none. + */ + private static Column untypedCopy(Table table, Column column, String sqlType) { + Column copy = new Column(column.quoted ? '`' + column.name + '`' : column.name) + copy.nullable = column.nullable + copy.unique = column.unique + copy.length = column.length + copy.precision = column.precision + copy.scale = column.scale + copy.comment = column.comment + copy.defaultValue = column.defaultValue + copy.customRead = column.customRead + copy.customWrite = column.customWrite + copy.sqlType = sqlType + List<Column> columns = new ArrayList<Column>(table.columns) + table.columns.clear() + for (Column existing : columns) { + table.addColumn(existing.is(column) ? copy : existing) + } + return copy + } + /** * Hibernate's annotation binder names the unique keys of a table and marks them as stated by the user: the schema then has * them as named constraints, and the key an {@code orderingUniqueKey} gives the primary key is named too. The domain binder's keys 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 c0fa89f916..7098933160 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 @@ -958,7 +958,7 @@ class GrailsDomainGenerator { * {@code getDiscriminatorValue}, and a joined subclass's key column is named like its identifier column. * * @throws UnsupportedOperationException for a hierarchy that mixes strategies (annotations state the strategy - * once, on the root) or whose discriminator has a type other than string, integer or character + * once, on the root) */ HierarchyFacets hierarchyFacets(GrailsHibernatePersistentEntity entity) { boolean root = entity.isRoot() @@ -1033,9 +1033,9 @@ class GrailsDomainGenerator { case 'java.lang.Character': return DiscriminatorType.CHAR default: - throw new UnsupportedOperationException( - "The discriminator type [${typeName}] of [${entity.name}] is not one of string, integer " + - 'or character, which the generator does not support yet') + // @DiscriminatorColumn names string, integer and character only: any other type is put on the discriminator of the model + // after binding (GeneratedDomainClassBinder), as the binder gives it its type name, so the annotation only needs a type + return DiscriminatorType.STRING } } diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesDiscriminatorSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesDiscriminatorSpec.groovy index 30a1023ea7..7704a63684 100644 --- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesDiscriminatorSpec.groovy +++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesDiscriminatorSpec.groovy @@ -29,9 +29,10 @@ import spock.lang.Unroll import org.grails.orm.hibernate.HibernateDatastore /** - * A discriminator column with a precision or a scale. {@code @DiscriminatorColumn} cannot state them and they change nothing in the - * DDL of a string or an integer column, but the domain binder puts them on the column, and a mapping that sets them must boot in the - * generated mode as it does in the domain binder, with the same column. + * A discriminator column with a precision or a scale, and a discriminator of a type other than string, integer or character. + * {@code @DiscriminatorColumn} cannot state either. The precision and the scale change nothing in the DDL of a string or an integer + * column, but the domain binder puts them on the column, and a mapping that sets them must boot in the generated mode as it does in the + * domain binder, with the same column. A discriminator typed {@code 'long'} is a bigint column in both. */ class GeneratedDomainClassesDiscriminatorSpec extends Specification { @@ -79,6 +80,7 @@ class GeneratedDomainClassesDiscriminatorSpec extends Specification { label | group | table | column 'a string discriminator with both' | [GddStringBase, GddStringSub] | 'gdd_string_base' | 'varchar(255) not null precision=5 scale=2' 'an integer discriminator with a precision' | [GddIntBase, GddIntSub] | 'gdd_int_base' | 'integer not null precision=5 scale=null' + 'a discriminator typed long' | [GddLongBase, GddLongSub] | 'gdd_long_base' | 'bigint not null precision=null scale=null' } @Unroll @@ -97,6 +99,7 @@ class GeneratedDomainClassesDiscriminatorSpec extends Specification { label | group | cycle 'a string discriminator' | [GddStringBase, GddStringSub] | 'stringCycle' 'an integer discriminator' | [GddIntBase, GddIntSub] | 'intCycle' + 'a discriminator typed long' | [GddLongBase, GddLongSub] | 'longCycle' } private List stringCycle() { @@ -107,6 +110,14 @@ class GeneratedDomainClassesDiscriminatorSpec extends Specification { return GddStringBase.withNewSession { [GddStringBase.count(), GddStringSub.count(), GddStringSub.list()*.name] } } + private List longCycle() { + GddLongBase.withTransaction { + new GddLongBase(name: 'base').save(failOnError: true) + new GddLongSub(name: 'sub', more: 'x').save(failOnError: true, flush: true) + } + return GddLongBase.withNewSession { [GddLongBase.count(), GddLongSub.count(), GddLongSub.list()*.name] } + } + private List intCycle() { GddIntBase.withTransaction { new GddIntBase(name: 'base').save(failOnError: true) @@ -144,3 +155,19 @@ class GddIntSub extends GddIntBase { discriminator value: '2' } } + +@Entity +class GddLongBase { + String name + static mapping = { + discriminator value: '1', type: 'long', column: [name: 'kind'] + } +} + +@Entity +class GddLongSub extends GddLongBase { + String more + static mapping = { + discriminator value: '2' + } +} 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 56a6cea4ef..0fabe92f70 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 @@ -1437,7 +1437,7 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { "${where} ${facet}: generator=${values[1]} binder=${values[0]}".toString() } if (bound instanceof RootClass) { - found.addAll(compareAnnotatedDiscriminator(where, (RootClass) bound, (RootClass) annotated)) + found.addAll(compareAnnotatedDiscriminator(where, (RootClass) bound, (RootClass) annotated, known)) found.addAll(compareAnnotatedNaturalId(where, bound, annotated, generator.naturalIdFacets(entity), known)) found.addAll(compareAnnotatedCache(where, (RootClass) bound, (RootClass) annotated)) if (entity.identity == null && generator.generationProblem(entity) == null) { @@ -2090,7 +2090,7 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { return false } - private static List<String> compareAnnotatedDiscriminator(String where, RootClass bound, RootClass annotated) { + private static List<String> compareAnnotatedDiscriminator(String where, RootClass bound, RootClass annotated, Map<String, Integer> known) { if ((bound.discriminator != null) != (annotated.discriminator != null)) { return ["${where} discriminator: generator=${annotated.discriminator != null} binder=${bound.discriminator != null}".toString()] } @@ -2105,6 +2105,10 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { ((BasicValue) annotated.discriminator).resolve().jdbcType.defaultSqlTypeCode], insertable : [bound.isDiscriminatorInsertable(), annotated.isDiscriminatorInsertable()], ] + if (pairs.jdbcType[0] != pairs.jdbcType[1] && !(((BasicValue) bound.discriminator).typeName in ['string', 'integer', 'character'])) { + known['a discriminator typed other than string, integer or character: @DiscriminatorColumn cannot state the type, GeneratedDomainClassBinder binds the discriminator again with it']++ + pairs.remove('jdbcType') + } Column boundColumn = (Column) bound.discriminator.selectables.find { it instanceof Column } if (boundColumn != null && ((BasicValue) bound.discriminator).typeName == 'string') { // the binder leaves an unset length null, which Hibernate reads as its default 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 49f072df83..85ee4a3b1e 100644 --- a/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc +++ b/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc @@ -69,7 +69,7 @@ For the domain classes in GORM's own test suites, both bindings produce the same * A natural id (`id natural: [...]`) may name an embedded object (the unique key spans its columns, in the order of the embedded class), and a name that is no property of the class is skipped without a message, as with classic binding. * A natural id declared on a subclass adds a unique key to the table of the hierarchy (the table of the subclass in a joined hierarchy), over the columns of the named properties in the order the mapping names them, and makes those properties updatable only when the natural id is `mutable`. Classic binding also marks the properties as natural identifiers, and with Hibernate 7 that makes every load of the subclass entity fail with a `NullPointerException`; native binding does not mark them [...] * `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 `discriminator` column may set `precision` and `scale`, and the discriminator may have a `type` other than string, integer or character, for example `type: 'long'`. The precision and the scale 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. * A many-to-many or a map of domain classes may involve an entity with a composite identifier on either side or on both: the join table has a key column for each identifier property of the owner and an element column for each one of the target, named as with classic binding. A foreign key to a composite identifier that the mapping gives fewer columns than the identifier has properties keeps the columns the mapping names and names the missing ones as classic binding does. @@ -105,7 +105,7 @@ Nothing is ignored silently. A mapping that boots is bound the way it is written | Map the association with a single `column`. |=== -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. +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 and a joined subclass of a root with a composite identifier. [[nativeDomainBinding-behavior]] === Differences in Behavior
