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 ff9292e942f0a420fc2345ca3e4ba8fe5f255060 Author: Walter Duque de Estrada <[email protected]> AuthorDate: Thu Oct 8 02:35:21 2026 -0500 feat: accept a registered type name for a different Java type in native domain binding The generator refused type: 'string' on an Integer (and the like) because the type Hibernate registers under that name is for another Java class than the property's. The domain binder boots it: it resolves the name and not the property's class, so the column is the registered type's (varchar(255) for string, integer for integer, clob for materialized_clob), and saving a value that is not null fails with a ClassCastException because the type cannot unwrap it, while null and the other properties are stored. The generator now types the field with the registered Java type and its JDBC type whenever the registered type does not convert its value, which is what it already did for serializable. The real class is still read and written through its own accessors, so the failure on save is the binder's too, and the spec compares both modes on the column and on that outcome. The DDL differential now boots every group the domain binder boots. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> --- .../domainbinding/jpa/GrailsDomainGenerator.groovy | 20 +-- .../GeneratedDomainClassesTypeMismatchSpec.groovy | 185 +++++++++++++++++++++ ...eneratedDomainClassesDdlDifferentialSpec.groovy | 1 - .../jpa/GrailsDomainGeneratorSpec.groovy | 22 +-- .../advancedGORMFeatures/nativeDomainBinding.adoc | 7 +- 5 files changed, 198 insertions(+), 37 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 9212bc05d5..c038eb92e9 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 @@ -1138,8 +1138,9 @@ class GrailsDomainGenerator { return new TypeDecision(true, name, new TypeFacets( null, registered.jdbcType.defaultSqlTypeCode, [:], null, registered.valueConverter.getClass())) } - if (registered != null && registered.valueConverter == null && !isEnum && - (identity || registered.javaTypeDescriptor.javaTypeClass == boxed(type) || serializesValueOf(registered, type))) { + if (registered != null && registered.valueConverter == null && !isEnum) { + // the binder resolves the name and not the property's class: the field has the registered Java type, whatever the + // property's class is (a String or a byte[] for serializable, an Integer for string), with the registered JDBC type Class<?> registeredJava = registered.javaTypeDescriptor.javaTypeClass return new TypeDecision(true, name, new TypeFacets( null, registered.jdbcType.defaultSqlTypeCode, [:], registeredJava == boxed(type) ? null : registeredJava)) @@ -1149,12 +1150,9 @@ class GrailsDomainGenerator { problem = 'is neither a UserType class nor a type registered with Hibernate' } else if (isEnum) { problem = 'is a registered type on an enum, which the binder binds with its own type parameters' - } else if (registered.valueConverter != null) { + } else { problem = 'is a registered type that converts its value in a way @Convert does not state (not a JPA attribute converter, ' + 'or the type of a collection element, an identifier or an enum)' - } else { - problem = "is registered for the Java type [${registered.javaTypeDescriptor.javaTypeClass.name}], not the property's [${type?.name}]: " + - 'stating it would need a converter, which annotations do not say for a type name' } return new TypeDecision(false, name, null, problem) } @@ -1168,16 +1166,6 @@ class GrailsDomainGenerator { return new TypeDecision(true, 'serializable', new TypeFacets(null, Types.VARBINARY, [:], Serializable)) } - /** - * {@code serializable} (and any registered type of a Java interface) on a property of a class that implements it: the property is - * typed with the registered Java type, as the binder resolves the type name and not the property's class, so a {@code String} or a - * {@code byte[]} is read and written through that type. - */ - private static boolean serializesValueOf(BasicType<?> registered, Class<?> type) { - Class<?> registeredJava = registered.javaTypeDescriptor.javaTypeClass - return registeredJava.interface && type != null && registeredJava.isAssignableFrom(boxed(type)) - } - /** * A {@code type} naming an {@code AttributeConverter}: the binder resolves the name to the converter and binds the property with it, * whatever the property's class is. {@code @Convert} states it, on a field of the Java type the converter converts when the diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesTypeMismatchSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesTypeMismatchSpec.groovy new file mode 100644 index 0000000000..e871fe3c0c --- /dev/null +++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesTypeMismatchSpec.groovy @@ -0,0 +1,185 @@ +/* + * 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 + +/** + * A registered type name for a different Java type than the property's, for example {@code type: 'string'} on an {@code Integer}. The + * domain binder resolves the name and not the property's class: the column has the registered type's SQL type, and the type cannot + * convert the value, so a value that is not null fails when it is saved with a {@code ClassCastException}. The generated mode boots with the + * same column and fails the same way. + */ +class GeneratedDomainClassesTypeMismatchSpec 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:tm${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. */ + private Map<String, Map> schema(HibernateDatastore booted) { + Map<String, Map> result = new TreeMap<String, Map>() + for (Table table : booted.metadata.collectTableMappings()) { + if (table.physicalTable) { + result[table.name] = [ + columns : table.columns.collectEntries { org.hibernate.mapping.Column column -> + boolean nullable = column.nullable && !(table.primaryKey != null && table.primaryKey.columns*.name.contains(column.name)) + [(column.name): "${column.getSqlType(booted.metadata)}${nullable ? '' : ' not null'}".toString()] + }, + primaryKey: table.primaryKey?.columns*.name?.sort(), + ] + } + } + return result + } + + private static String attempt(Closure<?> step) { + try { + return "ok: ${step.call()}".toString() + } catch (Throwable e) { + Throwable root = e + while (root.cause != null && root.cause != root) { + root = root.cause + } + return "failed: ${root.class.simpleName}".toString() + } + } + + @Unroll + void "#label has the column type the domain binder gives it"() { + when: + Map<String, Map> binder = schema(boot([type], false)) + Map<String, Map> generated = schema(boot([type], true)) + + then: + generated == binder + generated[table].columns.tag.startsWith(sqlType) + + where: + label | type | table | sqlType + 'a string type on an Integer' | TmStringOnInt | 'tm_string_on_int' | 'varchar(255)' + 'an integer type on a String' | TmIntOnString | 'tm_int_on_string' | 'integer' + 'a long type on an Integer' | TmLongOnInt | 'tm_long_on_int' | 'bigint' + 'a boolean type on a String' | TmBoolOnString | 'tm_bool_on_string' | 'boolean' + 'a text type on an Integer' | TmTextOnInt | 'tm_text_on_int' | 'varchar(32600)' + 'a timestamp type on a Long' | TmDateOnLong | 'tm_date_on_long' | 'timestamp' + 'a materialized_clob type on an Integer' | TmClobOnInt | 'tm_clob_on_int' | 'clob' + } + + @Unroll + void "#label fails to save a value as the domain binder does, and stores null and the other properties"() { + when: + Map<Boolean, Map> outcome = [false, true].collectEntries { boolean generated -> + boot([type], generated) + Map steps = [:] + steps.saveValue = attempt { type.withTransaction { type.newInstance(tag: value, name: 'a').save(failOnError: true, flush: true).id } } + Long id = null + steps.saveNull = attempt { id = type.withTransaction { type.newInstance(name: 'b').save(failOnError: true, flush: true).id } } + steps.reload = attempt { type.withNewSession { Object found = type.get(id); [found.name, found.tag] } } + [(generated): steps] + } + + then: + outcome[true] == outcome[false] + outcome[true].saveValue == 'failed: ClassCastException' + outcome[true].reload.startsWith('ok: [b, null]') + + where: + label | type | value + 'a string type on an Integer' | TmStringOnInt | 42 + 'an integer type on a String' | TmIntOnString | '42' + 'a long type on an Integer' | TmLongOnInt | 42 + 'a boolean type on a String' | TmBoolOnString | 'x' + } +} + +@Entity +class TmStringOnInt { + String name + Integer tag + static constraints = { name nullable: true; tag nullable: true } + static mapping = { tag type: 'string' } +} + +@Entity +class TmIntOnString { + String name + String tag + static constraints = { name nullable: true; tag nullable: true } + static mapping = { tag type: 'integer' } +} + +@Entity +class TmLongOnInt { + String name + Integer tag + static constraints = { name nullable: true; tag nullable: true } + static mapping = { tag type: 'long' } +} + +@Entity +class TmBoolOnString { + String name + String tag + static constraints = { name nullable: true; tag nullable: true } + static mapping = { tag type: 'boolean' } +} + +@Entity +class TmTextOnInt { + String name + Integer tag + static constraints = { name nullable: true; tag nullable: true } + static mapping = { tag type: 'text' } +} + +@Entity +class TmDateOnLong { + String name + Long tag + static constraints = { name nullable: true; tag nullable: true } + static mapping = { tag type: 'timestamp' } +} + +@Entity +class TmClobOnInt { + String name + Integer tag + static constraints = { name nullable: true; tag nullable: true } + static mapping = { tag type: 'materialized_clob' } +} 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 b8470381de..b29aa1a7ec 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 @@ -82,7 +82,6 @@ class GeneratedDomainClassesDdlDifferentialSpec extends Specification { */ private static final List<String> REFUSALS = [ 'neither side of the many-to-many owns it', - 'is registered for the Java type', ] private static final AtomicInteger BOOTS = new AtomicInteger() 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 f34e01b2e9..faa5b295c8 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 @@ -283,15 +283,6 @@ class GrailsDomainGeneratorSpec extends HibernateGormDatastoreSpec { getPersistentEntity(GenParamsOnly).persistentClass.getProperty('quantity').value.typeParameters.getProperty('sequence_name') == 'seq' } - void "a property the generator does not support is rejected by name"() { - when: - newGenerator().generateAll([unbound(GenUnsupportedType)], getClass().classLoader) - - then: - UnsupportedOperationException e = thrown() - e.message.contains('Type [string] of property [tag] of [' + GenUnsupportedType.name + ']') - } - void "the version is marked as the optimistic lock"() { expect: field('version').isAnnotationPresent(Version) @@ -491,14 +482,15 @@ class GrailsDomainGeneratorSpec extends HibernateGormDatastoreSpec { !typed.getDeclaredField('kind').isAnnotationPresent(Enumerated) } - void "a type name that is neither a user type nor a registered type for the class is rejected by name"() { + void "a registered type name for a different Java type types the field with the registered Java type and its JDBC type"() { when: - generate(GenUnsupportedType) + Class<?> generated = generate(GenUnsupportedType) - then: - UnsupportedOperationException e = thrown() - e.message.contains('tag') - e.message.contains('string') + then: "the binder resolves the name and not the property's class, so the column is the registered type's" + generated.getDeclaredField('tag').type == String + generated.getDeclaredField('tag').getAnnotation(JdbcTypeCode).value() == Types.VARCHAR + newGenerator().typeFacets((HibernatePersistentProperty) entity(GenUnsupportedType).getPropertyByName('tag')) == + new TypeFacets(null, Types.VARCHAR, [:], String) } void "Hibernate's own annotation binder reads the generated types and formulas"() { 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 de66048bd7..657c068079 100644 --- a/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc +++ b/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc @@ -65,6 +65,7 @@ For the domain classes in GORM's own test suites, both bindings produce the same * `type: 'serializable'` on a property that is not a collection (a `String`, a `byte[]` or any `Serializable`) is a binary column holding the Java serialization of the value, as with classic binding. * `params` on a registered type name such as `type: 'string'` are ignored, as with classic binding. They reach the type when it is a `UserType` that implements `ParameterizedType`. * A `type` that names an `AttributeConverter` class, for example `type: 'org.hibernate.type.YesNoConverter'`, converts the property with it, on a single property as well as on a `hasMany` stored in one column, as with classic binding. +* A registered type name for a different Java type than the property's, for example `type: 'string'` on an `Integer`, gives the column of the registered type (`varchar(255)`), as with classic binding. Neither binding converts the value, so saving a value that is not null fails with a `ClassCastException` in both; a null value and the other properties of the class are stored. * A custom collection type (a `UserCollectionType` class) as the `type` of a `hasMany` of domain classes is applied to the collection. Classic binding boots with the same schema but never uses the class: it keeps Hibernate's own collection. * 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 [...] @@ -95,10 +96,6 @@ Nothing is ignored silently. A mapping that boots is bound the way it is written | `Collection property [...]: the type [...] mapped on the collection property names neither a class nor serializable ...` or `... a custom collection type (a UserCollectionType) is mapped on a collection of basic values ...` | Remove the `type`, or use `'serializable'` or a `UserType` class to store the collection in one column. Classic binding does not boot with a registered type name (it fails with `Could not load requested class`), and neither with a custom collection type on a collection of basic values. -| A `type` that is a registered Hibernate type name for a different Java type than the property, where the type is not an interface the property implements, for example `type: 'string'` on an `Integer`. -| `Type [string] of property [...] is registered for the Java type [java.lang.String], not the property's [java.lang.Integer] ...` -| Use a `UserType` class, or a type name registered for the property's own type. - | `insertable: false` or `updatable: false` on a property that has no column of its own: a collection, an embedded object, or the inverse side of a one-to-one. | `... insertable: false or updatable: false is mapped on a property that has no column of its own ...` | Remove the option. Classic binding ignores it on such a property. On a property with a column, both bindings honor it. @@ -155,7 +152,7 @@ Some bugs of classic binding are not copied by native binding. Native binding do [[nativeDomainBinding-schema]] === Differences in the Schema -The schema of 702 groups of related domain classes was created with both bindings on H2 and compared: tables, columns with type, nullability, default, length, precision and scale, primary keys with their column order, foreign keys, unique keys, indexes, check constraints and sequences. Apart from the 4 groups that native binding refuses, these are the differences. Other databases are not covered by this comparison, so verify against your own database as described below. +The schema of 734 groups of related domain classes was created with both bindings on H2 and compared: tables, columns with type, nullability, default, length, precision and scale, primary keys with their column order, foreign keys, unique keys, indexes, check constraints and sequences. Native binding booted every group that classic binding boots, and these are the differences. Other databases are not covered by this comparison, so verify against your own database as described below. [cols="2,3,3", options="header"] |===
