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 f4580a8cb3a25b5860cfb2bcccba17c1f1041eef Author: Walter Duque de Estrada <[email protected]> AuthorDate: Thu Oct 8 01:03:11 2026 -0500 feat: accept serializable on a property that is not a collection in native domain binding The generator refused type: 'serializable' on a String or a byte[] because the type Hibernate registers under that name is for java.io.Serializable, not for the property's class. The domain binder accepts it: the column is varbinary(255) and the value is stored as its Java serialization (a String 'hello' is stored as ac ed 00 05 74 00 05 68 65 6c 6c 6f and read back). The generator now declares the field with the registered Java type when the property's class implements that interface, with the binary JDBC type, which is how it already stated a serialized collection. Hibernate then resolves the same type as the domain binder, so a byte[] behaves as it does there too: Hibernate writes an instance of the target type as it is, so the raw bytes are stored and cannot be read back as a serialization. That is the domain binder's behavior and both bindings are compared on it. A serialization written by the JDK is read by both. A registered type for an unrelated Java class (string on an Integer) stays refused by name. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> --- .../domainbinding/jpa/GrailsDomainGenerator.groovy | 12 +- ...neratedDomainClassesSerializableTypeSpec.groovy | 180 +++++++++++++++++++++ .../jpa/GrailsDomainGeneratorSpec.groovy | 33 +++- .../advancedGORMFeatures/nativeDomainBinding.adoc | 7 +- 4 files changed, 225 insertions(+), 7 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 7ca78ef1da..c0fc95658b 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 @@ -1114,7 +1114,7 @@ class GrailsDomainGenerator { null, registered.jdbcType.defaultSqlTypeCode, parameters, null, registered.valueConverter.getClass())) } if (registered != null && registered.valueConverter == null && parameters.isEmpty() && !isEnum && - (identity || registered.javaTypeDescriptor.javaTypeClass == boxed(type))) { + (identity || registered.javaTypeDescriptor.javaTypeClass == boxed(type) || serializesValueOf(registered, type))) { Class<?> registeredJava = registered.javaTypeDescriptor.javaTypeClass return new TypeDecision(true, name, new TypeFacets( null, registered.jdbcType.defaultSqlTypeCode, parameters, registeredJava == boxed(type) ? null : registeredJava)) @@ -1148,6 +1148,16 @@ class GrailsDomainGenerator { return new TypeDecision(true, 'serializable', new TypeFacets(null, Types.VARBINARY, parameters, 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)) + } + private static Class<?> loadClass(String name, HibernatePersistentProperty property) { for (ClassLoader loader : [property.hibernateOwner.javaClass.classLoader, Thread.currentThread().contextClassLoader]) { try { diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesSerializableTypeSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesSerializableTypeSpec.groovy new file mode 100644 index 0000000000..d2db542ef1 --- /dev/null +++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesSerializableTypeSpec.groovy @@ -0,0 +1,180 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package grails.gorm.tests.generated + +import java.sql.Connection +import java.sql.PreparedStatement +import java.sql.ResultSet +import java.sql.ResultSetMetaData +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 + +/** + * {@code type: 'serializable'} on a property that is not a collection. The registered type is for {@code java.io.Serializable}, so the + * domain binder stores the Java serialization of a {@code String} or any other value in a binary column. The generated mode boots with + * the same schema and stores the same bytes. + */ +class GeneratedDomainClassesSerializableTypeSpec 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:tns${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(), + 'dataSource.dbCreate' : 'create-drop', + 'hibernate.generatedDomainClasses': generated, + ], group as Class[]) + return datastore + } + + /** The tables of the boot model as plain data: columns with SQL type and nullability, indexes, unique keys. */ + private Map<String, Map> schema(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'}${column.unique ? ' unique' : ''}".toString()] + }, + primaryKey: table.primaryKey?.columns*.name?.sort(), + indexes : table.indexes.values().collectEntries { [(it.name): it.columns*.name] }, + uniqueKeys: table.uniqueKeys.values().collect { it.columns*.name.sort() }.sort { it.toString() }, + ] + } + } + return result + } + + /** The rows of a table as stored, binary values as lists of bytes. */ + private List<List> rows(String sql) { + return datastore.connectionSources.defaultConnectionSource.dataSource.connection.withCloseable { Connection connection -> + ResultSet result = connection.createStatement().executeQuery(sql) + ResultSetMetaData meta = result.metaData + List<List> found = [] + while (result.next()) { + found << (1..meta.columnCount).collect { int i -> + Object value = result.getObject(i) + value instanceof byte[] ? ((byte[]) value).toList() : value + } + } + found + } + } + + /** What a property does when it is saved, read back by a new session and stored: the value, or why it could not be read. */ + private Map roundTrip(HibernateDatastore booted, Class type, Map<String, Object> values, String property, String select) { + Long id = type.withTransaction { type.newInstance(values).save(failOnError: true, flush: true).id } + Map observed = [stored: rows(select)] + try { + Object value = type.withNewSession { type.get(id)."${property}" } + observed.reloaded = value instanceof byte[] ? ((byte[]) value).toList() : value + } catch (Throwable e) { + Throwable root = e + while (root.cause != null && root.cause != root) { + root = root.cause + } + observed.reloaded = "cannot be read: ${root.class.simpleName}".toString() + } + return observed + } + + @Unroll + void "#label has the column type the domain binder gives it"() { + when: + Map<String, Map> binder = schema(boot(group, false)) + Map<String, Map> generated = schema(boot(group, true)) + + then: + generated == binder + generated[table].columns[column] == type + + where: + label | group | table | column | type + 'a byte array typed serializable' | [TnSerializableBytes] | 'tn_serializable_bytes' | 'payload' | 'varbinary(255)' + 'a string typed serializable' | [TnSerializableString] | 'tn_serializable_string' | 'tag' | 'varbinary(255)' + } + + void "a string typed serializable is stored as the Java serialization of the string, as the domain binder stores it"() { + when: + Map binder = roundTrip(boot([TnSerializableString], false), TnSerializableString, [tag: 'hello'], 'tag', 'select tag from tn_serializable_string') + Map generated = roundTrip(boot([TnSerializableString], true), TnSerializableString, [tag: 'hello'], 'tag', 'select tag from tn_serializable_string') + + then: + generated == binder + generated.reloaded == 'hello' + generated.stored == [[[-84, -19, 0, 5, 116, 0, 5, 104, 101, 108, 108, 111]]] + } + + void "a byte array typed serializable behaves as it does in the domain binder"() { + when: + Map binder = roundTrip(boot([TnSerializableBytes], false), TnSerializableBytes, [payload: 'hello'.bytes], 'payload', 'select payload from tn_serializable_bytes') + Map generated = roundTrip(boot([TnSerializableBytes], true), TnSerializableBytes, [payload: 'hello'.bytes], 'payload', 'select payload from tn_serializable_bytes') + + then: + generated == binder + } + + void "a serialized byte array written by the Java serialization is read back by both bindings"() { + given: + byte[] serialized = new ByteArrayOutputStream().with { bytes -> + new ObjectOutputStream(bytes).with { it.writeObject('hello'.bytes); it.flush() } + bytes.toByteArray() + } + + when: + Map<Boolean, Object> read = [false, true].collectEntries { boolean generated -> + boot([TnSerializableBytes], generated) + datastore.connectionSources.defaultConnectionSource.dataSource.connection.withCloseable { Connection connection -> + PreparedStatement insert = connection.prepareStatement('insert into tn_serializable_bytes (id, version, payload) values (1, 0, ?)') + insert.setBytes(1, serialized) + insert.executeUpdate() + } + Object value = TnSerializableBytes.withNewSession { TnSerializableBytes.get(1L).payload } + [(generated): ((byte[]) value).toList()] + } + + then: + read[true] == read[false] + read[true] == 'hello'.bytes.toList() + } +} + +@Entity +class TnSerializableBytes { + byte[] payload + static mapping = { payload type: 'serializable' } +} + +@Entity +class TnSerializableString { + String tag + static mapping = { tag type: 'serializable' } +} 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 6834603cca..f25fbbe2fa 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 @@ -167,7 +167,8 @@ class GrailsDomainGeneratorSpec extends HibernateGormDatastoreSpec { GenFkTarget, GenFkOwned, GenFkOwner, GenFkCascades, GenFkNodeA, GenFkNodeB, GenFkHasOneOwner, GenFkHasOneDetail, GenOneFace, GenOneNose, GenFkManyOne, GenFkOneSide, GenFkSub, GenFkSubRoot, GenOmParent, GenOmChild, GenOmListed, GenOmOrdered, GenOmOrphan, GenOmFetched, GenOmTag, GenOmStep, GenOmKept, GenOmSortedOwner, GenOmMapOwner, GenMapBidiOwner, GenMapBidiChild, GenEmbAssocOwner, GenMmStudent, GenMmCourse, GenMmPerson, GenParamsOnly, GenDecimal, GenUnversioned, GenUnversionedRoot, GenUnversionedChild, GenConverted, GenValueTyped, - GenCollEmbeddedHolder, GenCollEmbeddedSibling, GenCollEmbeddedItem, GenCollEmbeddedEntityHolder, GenMapM2mLeft, GenMapM2mRight) + GenCollEmbeddedHolder, GenCollEmbeddedSibling, GenCollEmbeddedItem, GenCollEmbeddedEntityHolder, GenMapM2mLeft, GenMapM2mRight, + GenSerialized) } List<StandardServiceRegistry> registries = [] @@ -286,7 +287,7 @@ class GrailsDomainGeneratorSpec extends HibernateGormDatastoreSpec { then: UnsupportedOperationException e = thrown() - e.message.contains('Type [serializable] of property [tag] of [' + GenUnsupportedType.name + ']') + e.message.contains('Type [string] of property [tag] of [' + GenUnsupportedType.name + ']') } void "the version is marked as the optimistic lock"() { @@ -382,6 +383,19 @@ class GrailsDomainGeneratorSpec extends HibernateGormDatastoreSpec { !converted.getDeclaredField('plain').isAnnotationPresent(Convert) } + void "serializable on a property that is not a collection is a binary column of the Serializable Java type"() { + when: + Class<?> serialized = generate(GenSerialized) + + then: + serialized.getDeclaredField('tag').type == Serializable + serialized.getDeclaredField('tag').getAnnotation(JdbcTypeCode).value() == java.sql.Types.VARBINARY + serialized.getDeclaredField('payload').type == Serializable + serialized.getDeclaredField('payload').getAnnotation(JdbcTypeCode).value() == java.sql.Types.VARBINARY + serialized.getDeclaredField('plain').type == String + !serialized.getDeclaredField('plain').isAnnotationPresent(JdbcTypeCode) + } + void "Hibernate's own annotation binder resolves a converted type like the domain binder"() { given: Map<GrailsHibernatePersistentEntity, Class<?>> classes = generateGroup(GenConverted) @@ -449,7 +463,7 @@ class GrailsDomainGeneratorSpec extends HibernateGormDatastoreSpec { then: UnsupportedOperationException e = thrown() e.message.contains('tag') - e.message.contains('serializable') + e.message.contains('string') } void "Hibernate's own annotation binder reads the generated types and formulas"() { @@ -2788,10 +2802,23 @@ class GenParamsOnly { @Entity class GenUnsupportedType { + Integer tag + + static mapping = { + tag type: 'string' + } +} + +@Entity +class GenSerialized { + String tag + byte[] payload + String plain static mapping = { tag type: 'serializable' + payload type: 'serializable' } } 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 42b70ef4d9..d29d522bb2 100644 --- a/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc +++ b/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc @@ -62,6 +62,7 @@ For the domain classes in GORM's own test suites, both bindings produce the same * An `index` on the property of a `hasMany` is created over the key column of the collection table (and over the element column of a collection of enums), and `indexColumn` may give the index of a list or the key of a map a `type` other than integer or string. * A `hasMany` inside a class listed in `static embedded` (basic values, enums or domain classes, also in a nested embedded class) is stored in a collection table named after the embedded class, not after the owner, with a key column named after the embedded class too, as with classic binding. * A `Map` on a many-to-many (`Map<String, Book> books` with a `Set` or another `Map` on the other side) writes its own join table, with the key column of the map as part of the primary key, as with classic binding. A `Set` on the other side reads that table and does not write it, and two maps are two separate tables: rows stored through one map are not visible through the other, in both bindings. +* `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. * 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]] @@ -97,8 +98,8 @@ 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 the collection property ...` | Remove the `type`, or use `'serializable'` or a `UserType` class to store the collection in one column. Classic binding does not boot with a registered type name (it fails with `Could not load requested class`); a custom collection type is not described yet. -| A `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] ...` +| 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. | A registered type name together with `params`. @@ -165,7 +166,7 @@ Some bugs of classic binding are not copied by native binding. Native binding do [[nativeDomainBinding-schema]] === Differences in the Schema -The schema of 685 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 8 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 689 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 7 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. [cols="2,3,3", options="header"] |===
