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 9b30aeec6feebb986562adb5b4d5417bab0203a2 Author: Walter Duque de Estrada <[email protected]> AuthorDate: Thu Oct 8 16:20:13 2026 -0500 feat: accept mappings the domain binder boots although they say more than it uses in native domain binding Probed against the domain binder, these mappings boot and were refused by the generated mode: a join table that names several key columns (the binder uses the first), a type that names a Java class that is neither a UserType nor a converter (the binder finds the type registered for that class, java.util.Date is the timestamp type), a property of a class GORM does not know with no type (Hibernate infers the type, binary for a serializable class), an embedded property that is given a Us [...] Co-Authored-By: Claude Sonnet 5.5 <[email protected]> --- .../domainbinding/jpa/GrailsDomainGenerator.groovy | 85 +++--- ...GeneratedDomainClassesBinderLeniencySpec.groovy | 338 +++++++++++++++++++++ .../GrailsDomainGeneratorOptionCoverageSpec.groovy | 13 +- .../advancedGORMFeatures/nativeDomainBinding.adoc | 5 + 4 files changed, 388 insertions(+), 53 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 7098933160..346c703e44 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 @@ -330,7 +330,7 @@ class GrailsDomainGenerator { Map<String, List<EmbeddedUse>> uses = new LinkedHashMap<String, List<EmbeddedUse>>() for (GrailsHibernatePersistentEntity entity : entities) { for (HibernatePersistentProperty property : entity.persistentPropertiesToBind) { - if (property instanceof HibernateEmbeddedProperty) { + if (isComponent(property)) { collectCollectionUses(entity, (HibernateEmbeddedProperty) property, property.name, uses, []) } } @@ -381,7 +381,7 @@ class GrailsDomainGenerator { return } for (HibernatePersistentProperty peer : embeddedPeers(property)) { - if (peer instanceof HibernateEmbeddedProperty) { + if (isComponent(peer)) { collectCollectionUses(owner, (HibernateEmbeddedProperty) peer, "${path}.${peer.name}".toString(), uses, visiting + [type.javaClass]) } else if (peer instanceof HibernateToManyProperty) { uses.computeIfAbsent(sharedKey(type, peer.name)) { String key -> new ArrayList<EmbeddedUse>() } @@ -443,7 +443,7 @@ class GrailsDomainGenerator { if (target != null && !found.any { GrailsHibernatePersistentEntity other -> other.javaClass == target.javaClass }) { found << target } - } else if (property instanceof HibernateEmbeddedProperty) { + } else if (isComponent(property)) { // the generated embeddable types its association fields with the generated target classes GrailsHibernatePersistentEntity type = (GrailsHibernatePersistentEntity) ((HibernateEmbeddedProperty) property).associatedEntity if (type != null && !visiting.contains(type.javaClass)) { @@ -650,7 +650,7 @@ class GrailsDomainGenerator { * @return why {@link #generate} rejects the property, as the {@link UnsupportedOperationException} message names it */ String unsupportedReason(GrailsHibernatePersistentEntity entity, HibernatePersistentProperty property) { - if (property instanceof HibernateEmbeddedProperty) { + if (isComponent(property)) { String problem = embeddedProblem((HibernateEmbeddedProperty) property, []) if (problem != null) { return "Embedded property [${property.name}] of [${entity.name}]: ${problem}" @@ -681,13 +681,9 @@ class GrailsDomainGenerator { } } if ((property instanceof HibernateSimpleProperty || property instanceof HibernateTenantIdProperty || - isCustomProperty(property)) && !decideType(property).supported) { + isCustomProperty(property) || isEmbeddedValue(property)) && !decideType(property).supported) { return typeNotSupported(property, decideType(property)) } - if (isCustomProperty(property)) { - return "Property [${property.name}] of [${entity.name}] is a HibernateCustomProperty with no type mapped, " + - 'which the generator does not support yet: it states a custom type only when the mapping names a UserType class' - } return "Property [${property.name}] of [${entity.name}] is a ${property.getClass().simpleName}, " + 'which the generator does not support yet' } @@ -912,7 +908,7 @@ class GrailsDomainGenerator { } private void collectConstraintSites(HibernatePersistentProperty property, String path, List<ConstraintSite> sites) { - if (property instanceof HibernateEmbeddedProperty) { + if (isComponent(property)) { HibernateEmbeddedProperty embedded = (HibernateEmbeddedProperty) property String current = path.isEmpty() ? embedded.name : "${path}.${embedded.name}".toString() for (HibernatePersistentProperty peer : embeddedPeers(embedded)) { @@ -1043,14 +1039,13 @@ class GrailsDomainGenerator { * @return whether the generator can describe the property today: a plain single-column basic property, a * derived (formula) property, the tenant id (an ordinary column), the version, an enum, an embedded object whose own properties are all * supported, a collection of basic values or enums, a many-to-one association, the simple identifier, or a property of a type - * GORM does not know ({@link HibernateCustomProperty}) that the mapping gives a {@code UserType} class. Custom types with no - * type mapped, multi-column properties and the other associations are not supported yet. + * GORM does not know ({@link HibernateCustomProperty}). Multi-column properties are not supported. */ boolean supports(HibernatePersistentProperty property) { if (property instanceof HibernateSimpleIdentityProperty) { return property.hibernateOwner.isRoot() && decideType(property).supported } - if (property instanceof HibernateEmbeddedProperty) { + if (isComponent(property)) { return embeddedProblem((HibernateEmbeddedProperty) property, []) == null } if (property instanceof HibernateBasicProperty) { @@ -1063,7 +1058,7 @@ class GrailsDomainGenerator { return toManyProblem((HibernateToManyEntityProperty) property) == null } if (!(property instanceof HibernateSimpleProperty) && !(property instanceof HibernateTenantIdProperty) && - !isCustomProperty(property)) { + !isCustomProperty(property) && !isEmbeddedValue(property)) { return false } PropertyConfig mappedForm = property.hibernateMappedForm @@ -1075,9 +1070,22 @@ class GrailsDomainGenerator { return false } TypeDecision decision = decideType(property) - // the binder binds a custom property like a simple one, from the type its mapping names; with none, the type it resolves - // from the class alone is not one an annotation states, so only a mapped UserType class is supported - return decision.supported && (!isCustomProperty(property) || decision.facets != null) + // the binder binds a custom property like a simple one, from the type its mapping names; with none, Hibernate infers the type from + // the field as the binder's resolution does (a serializable class is stored as bytes) + return decision.supported + } + + /** + * @return whether the property is an embedded object the binder binds as a component. An embedded property that the mapping gives a + * {@code UserType} is bound as one simple value of that type and not as a component, and is described like any other column. + */ + private static boolean isComponent(HibernatePersistentProperty property) { + return property instanceof HibernateEmbeddedProperty && !((HibernateEmbeddedProperty) property).isUserButNotCollectionType() + } + + /** @return whether the property is an embedded property the binder binds as one simple value of a {@code UserType}, see {@link #isComponent} */ + private static boolean isEmbeddedValue(HibernatePersistentProperty property) { + return property instanceof HibernateEmbeddedProperty && !isComponent(property) } /** @@ -1159,8 +1167,8 @@ class GrailsDomainGenerator { if (AttributeConverter.isAssignableFrom(named) && !isEnum) { return convertedType(name, named, type) } - return new TypeDecision(false, name, null, 'names a class that is neither a UserType nor an AttributeConverter, which ' + - '@Type and @Convert cannot name') + // the binder resolves a class name that is no UserType or converter through the types registered under Java class names + // (java.util.Date is the timestamp type), so the name is looked up as a registered type below } BasicType<?> registered = typeConfiguration.basicTypeRegistry.getRegisteredType(name) boolean identity = property instanceof HibernateSimpleIdentityProperty @@ -1182,7 +1190,8 @@ class GrailsDomainGenerator { if (registered == null) { 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' + problem = 'is a registered type on an enum: the binder boots it but cannot store a single row (the enum value cannot be cast to the ' + + 'type), so the application would fail on its first save' } 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)' @@ -1329,9 +1338,6 @@ class GrailsDomainGenerator { if (elementType == null || elementType == Object) { return 'the element type is not known' } - if (mapped.joinTable.keys != null && mapped.joinTable.keys.size() > 1) { - return 'the join table has a composite key' - } if (compositeIdentifier(property.hibernateOwner)) { String compositeProblem = compositeOwnerKeyProblem(property) if (compositeProblem != null) { @@ -1661,8 +1667,9 @@ class GrailsDomainGenerator { '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' + return "the index column type [${name}] is a registered type that converts its value: the binder boots it, but a list fails on " + + 'its first row (the integer index violates the check of the converted column) and the table of a map is not created ' + + '(the column gets the type name as its SQL type), so the application cannot store a collection with it' } if (kind == CollectionKind.LIST) { Class<?> descriptor = javaTypeDescriptorClass(registered.javaTypeDescriptor.javaTypeClass) @@ -1791,18 +1798,10 @@ class GrailsDomainGenerator { 'no row is ever written, and annotations cannot say it (Hibernate\'s annotation binder fails with a ' + 'NullPointerException when both sides are mappedBy)' } - if (property.hibernateMappedForm.joinTable.keys != null && property.hibernateMappedForm.joinTable.keys.size() > 1 || - other.hibernateMappedForm.joinTable.keys != null && other.hibernateMappedForm.joinTable.keys.size() > 1) { - return 'a join table has a composite key' - } } else if (property.bidirectional) { if (!(property.hibernateInverseSide instanceof HibernateManyToOneProperty)) { return "the other side [${property.hibernateInverseSide?.name}] is not a many-to-one" } - } else { - if (mapped.joinTable.keys != null && mapped.joinTable.keys.size() > 1) { - return 'the join table has a composite key' - } } String indexTypeProblem = collectionIndexTypeProblem(property, kind) if (indexTypeProblem != null) { @@ -2301,7 +2300,7 @@ class GrailsDomainGenerator { enclosing << embedded for (HibernatePersistentProperty peer : embeddedPeers(embedded)) { String path = relative.isEmpty() ? peer.name : "${relative}.${peer.name}".toString() - if (peer instanceof HibernateEmbeddedProperty) { + if (isComponent(peer)) { collectLeaves((HibernateEmbeddedProperty) peer, currentPath, path, enclosing, leaves) } else if (peer instanceof HibernateToManyProperty) { // a collection has a table of its own and no column in the owner's table: the embeddable states its table and columns itself @@ -2366,28 +2365,20 @@ class GrailsDomainGenerator { /** * @return why the generator cannot describe the embedded property, or {@code null} when it can: every property of - * the embedded type, nested embedded types included, must be supported, the embedded type must not extend - * another persistent class, and embedded types must not contain each other + * the embedded type, nested embedded types included, must be supported, and embedded types must not contain each other */ private String embeddedProblem(HibernateEmbeddedProperty property, List<Class<?>> visiting) { GrailsHibernatePersistentEntity type = (GrailsHibernatePersistentEntity) property.associatedEntity if (type == null) { return 'the embedded type is unknown' } - if (!type.isRoot()) { - return "the embedded type [${type.name}] extends another persistent class" - } - if (property.isUserButNotCollectionType()) { - return "the property is mapped with the type [${property.userType.name}]: the binder binds it as one simple value of that " + - 'type and not as an embedded object, which the generator does not state' - } if (visiting.contains(type.javaClass)) { return "the embedded type [${type.name}] contains itself" } List<Class<?>> path = new ArrayList<Class<?>>(visiting) path << type.javaClass for (HibernatePersistentProperty peer : embeddedPeers(property)) { - if (peer instanceof HibernateEmbeddedProperty) { + if (isComponent(peer)) { String problem = embeddedProblem((HibernateEmbeddedProperty) peer, path) if (problem != null) { return problem @@ -2638,7 +2629,7 @@ class GrailsDomainGenerator { private DynamicType.Builder<Object> defineField( DynamicType.Builder<Object> builder, HibernatePersistentProperty property, List<AnnotationDescription> extra, Map<String, DynamicType.Unloaded<?>> embeddables) { - if (property instanceof HibernateEmbeddedProperty) { + if (isComponent(property)) { return defineEmbeddedField(builder, (HibernateEmbeddedProperty) property, embeddables, true) } if (property instanceof HibernateBasicProperty && !boundAsColumn(property)) { @@ -3086,7 +3077,7 @@ class GrailsDomainGenerator { return } for (HibernatePersistentProperty peer : embeddedPeers(property)) { - if (peer instanceof HibernateEmbeddedProperty) { + if (isComponent(peer)) { sharedCollectionPeers((HibernateEmbeddedProperty) peer, relative.isEmpty() ? peer.name : "${relative}.${peer.name}".toString(), "${binderPath}.${peer.name}".toString(), visiting + [type.javaClass], into) } else if (peer instanceof HibernateToManyProperty && sharedEmbeddedCollection(peer)) { @@ -3233,7 +3224,7 @@ class GrailsDomainGenerator { .name(name) .annotateType(AnnotationDescription.Builder.ofType(Embeddable).build()) for (HibernatePersistentProperty peer : peers) { - builder = peer instanceof HibernateEmbeddedProperty ? + builder = isComponent(peer) ? defineEmbeddedField(builder, (HibernateEmbeddedProperty) peer, embeddables, false) : defineField(builder, peer, [], embeddables) } diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesBinderLeniencySpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesBinderLeniencySpec.groovy new file mode 100644 index 0000000000..10c3320f75 --- /dev/null +++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesBinderLeniencySpec.groovy @@ -0,0 +1,338 @@ +/* + * 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.sql.PreparedStatement +import java.sql.ResultSet +import java.sql.SQLException +import java.sql.Types +import java.util.concurrent.atomic.AtomicInteger + +import grails.gorm.annotation.Entity +import org.hibernate.mapping.Table +import org.hibernate.type.descriptor.WrapperOptions +import org.hibernate.usertype.UserType +import spock.lang.AutoCleanup +import spock.lang.Specification +import spock.lang.Unroll + +import org.grails.orm.hibernate.HibernateDatastore + +/** + * Mappings that say more than the domain binder uses, and that it boots all the same: a join table that names a composite key (the + * binder uses the first key column and ignores the others), a {@code type} that names a Java class and not a type (the binder looks + * the class name up among the types registered for Java classes), and a property of a class GORM does not know and the mapping gives no + * type (the binder lets Hibernate pick the type, which is binary for a serializable class). The generated mode boots them with the same + * columns instead of refusing them. + */ +class GeneratedDomainClassesBinderLeniencySpec 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:gbl${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(), + 'dataSource.dbCreate' : 'create-drop', + 'hibernate.generatedDomainClasses': generated, + ], group as Class[]) + return datastore + } + + 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) { + List<String> key = table.primaryKey?.columns*.name ?: [] + result[table.name] = [ + columns : table.columns.collectEntries { org.hibernate.mapping.Column column -> + [(column.name): "${column.getSqlType(booted.metadata)}${column.nullable && !key.contains(column.name) ? '' : ' not null'}".toString()] + }, + primaryKey : key.sort(), + foreignKeys: table.foreignKeys.values().collect { "${it.columns*.name} -> ${it.referencedTable.name}".toString() }.sort(), + ] + } + } + return result + } + + @Unroll + void "#label: the generated mode creates the tables and columns of the domain binder"() { + when: + Map<String, Map> binder = schema(group, false) + Map<String, Map> generated = schema(group, true) + + then: + generated == binder + generated[table].columns.keySet() == columns as Set + + where: + label | group | table | columns + 'a join table of values that names two key columns' | [GblJoinKeyTags] | 'gbl_join_tags' | ['a', 't'] + 'a join table of entities that names two key columns' | [GblJoinKeyItems, GblItem] | 'gbl_join_items' | ['a', 'gbl_item_id'] + 'a many-to-many that names two key columns' | [GblJoinKeyA, GblJoinKeyB] | 'gbl_join_ab' | ['k1', 'bid'] + 'a type that names a Java class' | [GblClassTypes] | 'gbl_class_types' | ['id', 'version', 'total', 'stamp', 'name2'] + 'a property of a serializable class with no type' | [GblSerializable] | 'gbl_serializable' | ['id', 'version', 'thing'] + 'an embedded property that is given a user type' | [GblUserTyped] | 'gbl_user_typed' | ['id', 'version', 'home'] + 'an embedded type that extends a domain class' | [GblEmbBase, GblEmbOwner] | 'gbl_emb_owner' | ['id', 'version', 'emb_id', 'emb_a', 'emb_b'] + } + + @Unroll + void "#label: the rows are stored, read back and changed 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 join table of values that names two key columns' | [GblJoinKeyTags] | 'tagsCycle' | [['a', 'b'], ['c']] + 'a join table of entities that names two key columns' | [GblJoinKeyItems, GblItem] | 'itemsCycle' | [['one', 'two'], ['three']] + 'a many-to-many that names two key columns' | [GblJoinKeyA, GblJoinKeyB] | 'manyCycle' | [['b1', 'b2'], ['b3']] + 'a type that names a Java class' | [GblClassTypes] | 'classTypeCycle' | [null, 'text'] + 'a property of a serializable class with no type' | [GblSerializable] | 'serialCycle' | ['first', 'second'] + 'an embedded property that is given a user type' | [GblUserTyped] | 'userTypedCycle' | ['STREET', 'AVENUE'] + 'an embedded type that extends a domain class' | [GblEmbBase, GblEmbOwner] | 'embeddedSubCycle' | ['a1/b1', 'a2/b2'] + } + + private List tagsCycle() { + Long id = GblJoinKeyTags.withTransaction { new GblJoinKeyTags(tags: ['a', 'b'] as Set).save(failOnError: true, flush: true).id } + List first = GblJoinKeyTags.withNewSession { GblJoinKeyTags.get(id).tags.sort() } + GblJoinKeyTags.withTransaction { GblJoinKeyTags owner = GblJoinKeyTags.get(id); owner.tags = ['c'] as Set; owner.save(failOnError: true, flush: true) } + return [first, GblJoinKeyTags.withNewSession { GblJoinKeyTags.get(id).tags.sort() }] + } + + private List itemsCycle() { + Long id = GblJoinKeyItems.withTransaction { + new GblJoinKeyItems(items: [new GblItem(name: 'one').save(failOnError: true), new GblItem(name: 'two').save(failOnError: true)] as Set) + .save(failOnError: true, flush: true).id + } + List first = GblJoinKeyItems.withNewSession { GblJoinKeyItems.get(id).items*.name.sort() } + GblJoinKeyItems.withTransaction { + GblJoinKeyItems owner = GblJoinKeyItems.get(id) + owner.items = [new GblItem(name: 'three').save(failOnError: true)] as Set + owner.save(failOnError: true, flush: true) + } + return [first, GblJoinKeyItems.withNewSession { GblJoinKeyItems.get(id).items*.name.sort() }] + } + + private List manyCycle() { + Long id = GblJoinKeyA.withTransaction { + new GblJoinKeyA(bs: [new GblJoinKeyB(name: 'b1').save(failOnError: true), new GblJoinKeyB(name: 'b2').save(failOnError: true)] as Set) + .save(failOnError: true, flush: true).id + } + List first = GblJoinKeyA.withNewSession { GblJoinKeyA.get(id).bs*.name.sort() } + GblJoinKeyA.withTransaction { + GblJoinKeyA owner = GblJoinKeyA.get(id) + owner.bs = [new GblJoinKeyB(name: 'b3').save(failOnError: true)] as Set + owner.save(failOnError: true, flush: true) + } + return [first, GblJoinKeyA.withNewSession { GblJoinKeyA.get(id).bs*.name.sort() }] + } + + private List classTypeCycle() { + Long id = GblClassTypes.withTransaction { new GblClassTypes().save(failOnError: true, flush: true).id } + Object first = GblClassTypes.withNewSession { GblClassTypes.get(id).stamp } + GblClassTypes.withTransaction { GblClassTypes row = GblClassTypes.get(id); row.name2 = 'text'; row.save(failOnError: true, flush: true) } + return [first, GblClassTypes.withNewSession { GblClassTypes.get(id).name2 }] + } + + private List userTypedCycle() { + Long id = GblUserTyped.withTransaction { new GblUserTyped(home: new GblAddress(street: 'street')).save(failOnError: true, flush: true).id } + String first = GblUserTyped.withNewSession { GblUserTyped.get(id).home.street } + GblUserTyped.withTransaction { GblUserTyped row = GblUserTyped.get(id); row.home = new GblAddress(street: 'avenue'); row.save(failOnError: true, flush: true) } + return [first, GblUserTyped.withNewSession { GblUserTyped.get(id).home.street }] + } + + private List embeddedSubCycle() { + Long id = GblEmbOwner.withTransaction { new GblEmbOwner(emb: new GblEmbSub(a: 'a1', b: 'b1')).save(failOnError: true, flush: true).id } + String first = GblEmbOwner.withNewSession { GblEmbOwner owner = GblEmbOwner.get(id); "${owner.emb.a}/${owner.emb.b}".toString() } + GblEmbOwner.withTransaction { GblEmbOwner owner = GblEmbOwner.get(id); owner.emb = new GblEmbSub(a: 'a2', b: 'b2'); owner.save(failOnError: true, flush: true) } + return [first, GblEmbOwner.withNewSession { GblEmbOwner owner = GblEmbOwner.get(id); "${owner.emb.a}/${owner.emb.b}".toString() }] + } + + private List serialCycle() { + Long id = GblSerializable.withTransaction { new GblSerializable(thing: new GblThing(a: 'first')).save(failOnError: true, flush: true).id } + String first = GblSerializable.withNewSession { GblSerializable.get(id).thing.a } + GblSerializable.withTransaction { GblSerializable row = GblSerializable.get(id); row.thing = new GblThing(a: 'second'); row.save(failOnError: true, flush: true) } + return [first, GblSerializable.withNewSession { GblSerializable.get(id).thing.a }] + } +} + +@Entity +class GblItem { + String name +} + +@Entity +class GblJoinKeyTags { + Set<String> tags + + static hasMany = [tags: String] + + static mapping = { + tags joinTable: [name: 'gbl_join_tags', key: ['a', 'b'], column: 't'] + } +} + +@Entity +class GblJoinKeyItems { + Set<GblItem> items + + static hasMany = [items: GblItem] + + static mapping = { + items joinTable: [name: 'gbl_join_items', key: ['a', 'b']] + } +} + +@Entity +class GblJoinKeyA { + Set<GblJoinKeyB> bs + + static hasMany = [bs: GblJoinKeyB] + + static mapping = { + bs joinTable: [name: 'gbl_join_ab', key: ['k1', 'k2'], column: 'bid'] + } +} + +@Entity +class GblJoinKeyB { + String name + Set<GblJoinKeyA> owners + + static hasMany = [owners: GblJoinKeyA] + static belongsTo = [GblJoinKeyA] +} + +@Entity +class GblClassTypes { + Integer total + String stamp + String name2 + + static mapping = { + total type: 'java.lang.String' + stamp type: 'java.util.Date' + } +} + +class GblThing implements Serializable { + String a +} + +@Entity +class GblSerializable { + GblThing thing +} + +class GblAddress { + String street +} + +class GblAddressType implements UserType<GblAddress> { + + @Override + int getSqlType() { + return Types.VARCHAR + } + + @Override + Class<GblAddress> returnedClass() { + return GblAddress + } + + @Override + boolean equals(GblAddress x, GblAddress y) { + return x?.street == y?.street + } + + @Override + int hashCode(GblAddress x) { + return x?.street.hashCode() ?: 0 + } + + @Override + GblAddress nullSafeGet(ResultSet rs, int position, WrapperOptions options) throws SQLException { + String street = rs.getString(position) + return street == null ? null : new GblAddress(street: street.toLowerCase().toUpperCase()) + } + + @Override + void nullSafeSet(PreparedStatement st, GblAddress value, int index, WrapperOptions options) throws SQLException { + st.setString(index, value?.street?.toUpperCase()) + } + + @Override + GblAddress deepCopy(GblAddress value) { + return value == null ? null : new GblAddress(street: value.street) + } + + @Override + boolean isMutable() { + return true + } + + @Override + Serializable disassemble(GblAddress value) { + return value?.street + } + + @Override + GblAddress assemble(Serializable cached, Object owner) { + return cached == null ? null : new GblAddress(street: (String) cached) + } +} + +@Entity +class GblUserTyped { + GblAddress home + + static embedded = ['home'] + + static mapping = { + home type: GblAddressType + } +} + +@Entity +class GblEmbBase { + String a +} + +class GblEmbSub extends GblEmbBase { + String b +} + +@Entity +class GblEmbOwner { + GblEmbSub emb + + static embedded = ['emb'] +} 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 862200c33e..6d63fffdb8 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 @@ -21,6 +21,7 @@ package org.grails.orm.hibernate.cfg.domainbinding.jpa import grails.gorm.annotation.Entity import jakarta.persistence.AccessType import jakarta.persistence.CascadeType +import jakarta.persistence.Embedded import jakarta.persistence.EnumType import jakarta.persistence.FetchType import org.hibernate.MappingException @@ -258,19 +259,19 @@ class GrailsDomainGeneratorOptionCoverageSpec extends GrailsDomainGeneratorSuppo property << ['tags', 'targets'] } - void "a user type mapped on an embedded property is rejected by name, because the binder binds it as a simple value"() { + void "a user type mapped on an embedded property makes it one simple column of that type, as the binder binds it"() { given: PropertyConfig config = entity(GenCovOwner).getHibernatePropertyByName('home').hibernateMappedForm config.type = GenUpperType when: - generateGroup(GenCovOwner, GenCovTarget) + Class<?> owner = generateGroup(GenCovOwner, GenCovTarget).find { it.key.name == GenCovOwner.name }.value + java.lang.reflect.Field home = owner.getDeclaredField('home') then: - UnsupportedOperationException e = thrown() - e.message.contains('GenCovOwner') - e.message.contains('home') - e.message.contains('GenUpperType') + !home.isAnnotationPresent(Embedded) + home.getAnnotation(org.hibernate.annotations.Type).value() == GenUpperType + home.getAnnotation(jakarta.persistence.Column).name() == 'home' cleanup: config.type = null 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 85ee4a3b1e..e720267976 100644 --- a/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc +++ b/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc @@ -73,6 +73,7 @@ For the domain classes in GORM's own test suites, both bindings produce the same * 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. +* A `joinTable` that names several `key` columns uses the first one in both bindings (the other names are ignored). A `type` that names a Java class that is no `UserType` or converter, for example `type: 'java.util.Date'`, gives the column of the type Hibernate registers for that class, and a property of a class GORM does not know (a `Serializable` class, with no `type`) is stored as bytes. An embedded property with a `type` that is a `UserType` is one column of that type, not an embedde [...] * 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]] @@ -100,6 +101,10 @@ 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. Classic binding fails with `Foreign key ... must have same number of columns as the referenced primary key` or an `IndexOutOfBoundsException`. +| A registered Hibernate type name as the `type` of an enum property (`type: 'integer'`), or a registered type that converts its value (`yes_no`) as the `type` of the `indexColumn` of a list or a map. +| `Type [...] of property [...] is a registered type on an enum ...` or `... the index column type [...] is a registered type that converts its value ...` +| Remove the `type` (an enum is stored as a string unless `enumType` says otherwise). Classic binding boots these mappings but cannot use them: saving a row fails with a `ClassCastException` for the enum, with a check constraint violation for the list, and the table of the map is not created. + | 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`.
