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 b1fbda05f65ee3df9071448df7926afd7a5f718f Author: Walter Duque de Estrada <[email protected]> AuthorDate: Thu Oct 8 02:22:05 2026 -0500 feat: accept a natural id on a subclass, an embedded property and an unknown name in native domain binding The generator refused three natural id mappings that the domain binder boots: a natural id on a subclass (Hibernate refuses @NaturalId there), a natural id that names an embedded property, and one that names a property the class does not have (the binder skips the name without a word). A subclass now gets what NaturalId.createUniqueKey gives it: one unique key over the columns of the named properties in the order of the mapping, on the table of the class (the table of the hierarchy for single-table), with the name the binder generates, and the properties are updatable only when the natural id is mutable. The properties are not marked as natural identifiers: with Hibernate 7 the binder's marking makes every load and update of the subclass fail with a NullPointerException, because Hibernate builds the natural id mapping of a root only. An embedded property is stated with @NaturalId and the key takes the columns of the embedded type in the order it declares them, as the binder's does. An unknown name is dropped from the natural id; a mapping whose names are all unknown has none. A natural id that names a collection or a formula stays refused: the domain binder does not boot it either. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> --- .../jpa/GeneratedDomainClassBinder.groovy | 64 +++- .../domainbinding/jpa/GrailsDomainGenerator.groovy | 64 ++-- .../GeneratedDomainClassesNaturalIdSpec.groovy | 365 +++++++++++++++++++++ ...eneratedDomainClassesDdlDifferentialSpec.groovy | 3 - .../GrailsDomainGeneratorDifferentialSpec.groovy | 116 +++++-- .../jpa/GrailsDomainGeneratorNaturalIdSpec.groovy | 45 ++- .../advancedGORMFeatures/nativeDomainBinding.adoc | 16 +- 7 files changed, 588 insertions(+), 85 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 0ccac33665..50b8ba38d4 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 @@ -73,6 +73,7 @@ import org.grails.orm.hibernate.cfg.domainbinding.binder.PropertyBinder import org.grails.orm.hibernate.cfg.domainbinding.binder.StringColumnConstraintsBinder import org.grails.orm.hibernate.cfg.domainbinding.generator.GrailsSequenceGeneratorEnum import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity +import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateEmbeddedProperty import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentEntity import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateBasicProperty @@ -83,6 +84,7 @@ import org.grails.orm.hibernate.cfg.domainbinding.util.ColumnNameForPropertyAndP import org.grails.orm.hibernate.cfg.domainbinding.util.DefaultColumnNameFetcher import org.grails.orm.hibernate.cfg.domainbinding.util.GeneratorCreationContextWrapper import org.grails.orm.hibernate.cfg.domainbinding.util.MultiTenantFilterDefinitionBinder +import org.grails.orm.hibernate.cfg.domainbinding.util.UniqueNameGenerator /** * Lets Hibernate's own annotation binder bind the GORM domain classes, while the application's real instances stay what @@ -116,6 +118,7 @@ class GeneratedDomainClassBinder implements SessionFactoryBuilderFactory { private final PropertyBinder propertyBinder = new PropertyBinder() private final Map<String, Generated> generatedByName = new HashMap<String, Generated>() private final MultiTenantFilterDefinitionBinder filterDefinitionBinder = new MultiTenantFilterDefinitionBinder() + private final UniqueNameGenerator uniqueNameGenerator = new UniqueNameGenerator() private PersistentEntityNamingStrategy namingStrategy private JdbcEnvironment jdbcEnvironment private GrailsDomainGenerator generator @@ -365,18 +368,65 @@ class GeneratedDomainClassBinder implements SessionFactoryBuilderFactory { key.explicit = false } alignPrimaryKeyOrder(persistentClass, entity) - NaturalIdFacets naturalId = persistentClass instanceof RootClass ? generator.naturalIdFacets(entity) : null - if (naturalId != null) { - List<String> columns = naturalId.propertyNames().collectMany { String name -> - persistentClass.getProperty(name).columns*.name - } + NaturalIdFacets naturalId = generator.naturalIdFacets(entity) + if (naturalId == null) { + return + } + List<Column> columns = naturalId.propertyNames().collectMany { String name -> + naturalColumns(persistentClass, entity, name) + } + if (persistentClass instanceof RootClass) { for (UniqueKey key : persistentClass.table.uniqueKeys.values()) { - if (key.columns*.name.toSet() == columns.toSet()) { - List<Column> ordered = key.columns.sort(false) { Column column -> columns.indexOf(column.name) } + if (key.columns*.name.toSet() == columns*.name.toSet()) { + List<Column> ordered = key.columns.sort(false) { Column column -> columns*.name.indexOf(column.name) } key.columns.clear() key.columns.addAll(ordered) } } + } else { + alignSubclassNaturalId(persistentClass, naturalId, columns) + } + } + + /** + * The columns of a property of a natural id, in the order the domain binder gives them: the order of the properties of an + * embedded type as the mapping declares them, where Hibernate's annotation binder sorts the properties of a component by name. + */ + private List<Column> naturalColumns(PersistentClass persistentClass, GrailsHibernatePersistentEntity entity, String name) { + Property property = persistentClass.getProperty(name) + List<Column> columns = property.columns + PersistentProperty<?> mapped = entity.getPropertyByName(name) + if (property.value instanceof Component && mapped instanceof HibernateEmbeddedProperty) { + List<String> declared = generator.embeddedLeaves((HibernateEmbeddedProperty) mapped).collectMany { EmbeddedLeaf leaf -> + leaf.toOne() != null ? leaf.toOne().joinColumns()*.name() : (leaf.column() != null ? [leaf.column().name()] : []) + } + List<String> bound = columns*.name + if (declared.toSet() == bound.toSet()) { + return columns.sort(false) { Column column -> declared.indexOf(column.name) } + } + } + return columns + } + + /** + * Hibernate refuses {@code @NaturalId} on a subclass. The domain binder binds the natural id of a subclass as it does a root's + * ({@code NaturalId.createUniqueKey}): each property it names, found in the hierarchy, is made updatable exactly when the natural + * id is mutable, and one unique key over their columns in the order of the mapping is added to the table of the class, which is + * the table of the hierarchy for a single-table subclass, with the name {@link UniqueNameGenerator} gives it. + * + * <p>The properties are not marked as natural identifiers: with Hibernate 7 the domain binder's marking makes every load and + * update of the subclass fail with a {@code NullPointerException}, because Hibernate builds the natural id mapping of a root + * only.</p> + */ + private void alignSubclassNaturalId(PersistentClass persistentClass, NaturalIdFacets naturalId, List<Column> columns) { + for (String name : naturalId.propertyNames()) { + persistentClass.getProperty(name).updateable = naturalId.mutable() + } + if (!columns.isEmpty()) { + UniqueKey key = new UniqueKey(persistentClass.table) + columns.each { Column column -> key.addColumn(column) } + uniqueNameGenerator.setGeneratedUniqueName(key) + persistentClass.table.addUniqueKey(key) } } 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 dec8bee278..9212bc05d5 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 @@ -122,6 +122,7 @@ import org.hibernate.usertype.UserType import org.springframework.core.GenericTypeResolver import org.springframework.util.ClassUtils +import org.grails.datastore.mapping.model.PersistentProperty import org.grails.datastore.mapping.model.config.GormProperties import org.grails.datastore.mapping.model.types.Association import org.grails.orm.hibernate.cfg.CacheConfig @@ -722,9 +723,12 @@ class GrailsDomainGenerator { /** * Decides the natural identifier the domain binder binds for the entity, as {@code NaturalIdentifierBinder} reads it from the - * mapped identity: the properties it names and whether it is mutable. The binder also makes each of those properties updatable - * exactly when the natural id is mutable, and adds one unique key over their columns; Hibernate's annotation binder does both - * for {@code @NaturalId}, with a unique key of its own name. + * mapped identity: the properties it names and whether it is mutable. The binder makes each of those properties updatable + * exactly when the natural id is mutable, and adds one unique key over their columns to the table of the entity (the table of the + * hierarchy for a subclass of a single-table hierarchy). A name that is no property of the entity or of its superclasses is + * skipped without a word, so it is not part of the facets either; a mapping whose names are all skipped has no natural id. + * Hibernate's annotation binder does the rest for {@code @NaturalId} on a root, with a unique key of its own name; a subclass + * cannot state it, and the aligner binds the key and the flags of a subclass. * * @return the facets, or {@code null} when the mapping names no natural identifier */ @@ -733,43 +737,57 @@ class GrailsDomainGenerator { if (natural == null || natural.propertyNames == null || natural.propertyNames.isEmpty()) { return null } - return new NaturalIdFacets(new ArrayList<String>(natural.propertyNames), natural.mutable) + List<String> known = natural.propertyNames.findAll { String name -> + PersistentProperty<?> found = entity.getPropertyByName(name) + found instanceof HibernatePersistentProperty && entity.identity?.name != name + } + return known.isEmpty() ? null : new NaturalIdFacets(new ArrayList<String>(known), natural.mutable) } /** - * @return why the generator cannot describe the natural identifier of the entity, or {@code null} when it can: it must be - * the entity's own (Hibernate refuses {@code @NaturalId} on a subclass, where the binder puts a key on the table of the - * hierarchy), and every property it names must be a plain column, an enum or a foreign key of the entity (the binder skips a - * name that is no property of the class without a word, which the generator rejects instead) + * @return why the generator cannot describe the natural identifier of the entity, or {@code null} when it can: every property it + * names must be a plain column, an enum, a foreign key or an embedded type of the entity */ private String naturalIdProblem(GrailsHibernatePersistentEntity entity) { NaturalIdFacets natural = naturalIdFacets(entity) if (natural == null) { return null } - if (!entity.isRoot()) { - return "Entity [${entity.name}] declares a natural id but is a subclass: Hibernate refuses @NaturalId on a subclass, " + - 'where the binder adds a unique key to the table of the hierarchy' - } for (String name : natural.propertyNames()) { - HibernatePersistentProperty property = entity.persistentPropertiesToBind.find { HibernatePersistentProperty p -> p.name == name } - if (property == null) { - return "The natural id of [${entity.name}] names [${name}], which is not a persistent property of the entity: " + - 'the binder skips it without a word' - } - if (property instanceof HibernateEmbeddedProperty || property instanceof HibernateBasicProperty || + HibernatePersistentProperty property = (HibernatePersistentProperty) entity.getPropertyByName(name) + if (property instanceof HibernateBasicProperty || property instanceof HibernateToManyEntityProperty || isDerived(property) || (property instanceof HibernateToOneProperty && boundAsOneToOne((HibernateToOneProperty) property))) { return "The natural id of [${entity.name}] names [${name}], which is ${property.getClass().simpleName}: " + - 'only a simple property, an enum or a foreign key can be part of a natural id the generator states' + 'only a simple property, an enum, a foreign key or an embedded type can be part of a natural id the generator states' + } + } + return null + } + + /** + * @return whether the natural identifier the binder gives the property makes it updatable: the natural id of its entity or of a + * subclass of it, which may name a property it inherits; {@code null} when no natural id names it + */ + private Boolean naturalIdUpdatable(HibernatePersistentProperty property) { + Deque<GrailsHibernatePersistentEntity> pending = new ArrayDeque<GrailsHibernatePersistentEntity>() + pending.add(property.hibernateOwner) + while (!pending.isEmpty()) { + GrailsHibernatePersistentEntity entity = pending.poll() + NaturalIdFacets natural = naturalIdFacets(entity) + if (natural != null && natural.propertyNames().contains(property.name)) { + return natural.mutable() } + pending.addAll(entity.childEntities) } return null } /** @return whether the property is part of the natural identifier of its entity, and so whether that is mutable; {@code null} when it is not part of it */ private Boolean naturalIdMutable(HibernatePersistentProperty property) { - NaturalIdFacets natural = naturalIdFacets(property.hibernateOwner) + GrailsHibernatePersistentEntity owner = property.hibernateOwner + // a subclass cannot state @NaturalId: the aligner binds the natural id of a subclass + NaturalIdFacets natural = owner.isRoot() ? naturalIdFacets(owner) : null return natural != null && natural.propertyNames().contains(property.name) ? natural.mutable() : null } @@ -2402,7 +2420,7 @@ class GrailsDomainGenerator { HibernatePersistentProperty property, Column column, String name, boolean nullable, boolean unique) { PropertyConfig mappedForm = property.hibernateMappedForm // NaturalId.createUniqueKey sets the updatability of each of its properties to the mutability of the natural id - Boolean naturalMutable = naturalIdMutable(property) + Boolean naturalMutable = naturalIdUpdatable(property) return new ColumnFacets( name, nullable, @@ -3033,6 +3051,10 @@ class GrailsDomainGenerator { .build() } } + Boolean naturalMutable = naturalIdMutable(property) + if (naturalMutable != null) { + annotations << AnnotationDescription.Builder.ofType(HibernateNaturalId).define('mutable', naturalMutable).build() + } for (Annotation audit : auditAnnotations(property)) { annotations << AnnotationDescription.ForLoadedAnnotation.of(audit) } diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesNaturalIdSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesNaturalIdSpec.groovy new file mode 100644 index 0000000000..7ee86971d2 --- /dev/null +++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesNaturalIdSpec.groovy @@ -0,0 +1,365 @@ +/* + * 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.PersistentClass +import org.hibernate.mapping.Property +import org.hibernate.mapping.RootClass +import org.hibernate.mapping.Table +import spock.lang.AutoCleanup +import spock.lang.Specification +import spock.lang.Unroll + +import org.grails.orm.hibernate.HibernateDatastore + +/** + * A natural id the mapping states with {@code id natural: ...} on an entity the generated mode cannot hand to Hibernate's + * {@code @NaturalId} as it is: a subclass (the domain binder adds the unique key to the table of the hierarchy), an embedded + * property (the key spans the columns of the embedded type) and a name that is no property (the domain binder skips it). The + * generated mode boots with the unique keys the domain binder creates (name and column order), flags the same properties as natural, + * and rejects the same duplicates. + */ +class GeneratedDomainClassesNaturalIdSpec 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:ni${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(), + 'dataSource.dbCreate' : 'create-drop', + 'hibernate.generatedDomainClasses': generated, + ], group as Class[]) + return datastore + } + + /** + * The unique keys of every table (columns in order, and names when asked for: Hibernate names the key of a root's {@code @NaturalId} + * itself) and the updatability of the properties, with the properties of a root flagged natural. + */ + private Map<String, Object> schema(HibernateDatastore booted, boolean names = false, boolean natural = true) { + Map<String, Object> result = new TreeMap<String, Object>() + for (Table table : booted.metadata.collectTableMappings()) { + if (table.physicalTable) { + result["table ${table.name}".toString()] = [ + columns : table.columns*.name.sort(), + uniqueKeys: table.uniqueKeys.values().collect { names ? [name: it.name, columns: it.columns*.name] : [columns: it.columns*.name] }.sort { it.toString() }, + ] + } + } + for (PersistentClass persistentClass : booted.metadata.entityBindings) { + result["updatable ${persistentClass.entityName}".toString()] = persistentClass.declaredProperties.collectEntries { Property p -> [(p.name): p.updateable] } + if (natural && persistentClass instanceof RootClass) { + result["natural ${persistentClass.entityName}".toString()] = persistentClass.declaredProperties.findAll { Property p -> p.naturalIdentifier }*.name + } + } + return result + } + + @Unroll + void "#label has the unique key and the natural properties the domain binder gives it"() { + given: "the domain binder also marks a property of a parent as natural when its subclass names it, which the generated mode does not" + boolean natural = group != [NiMixRoot, NiMixChild] + + when: + Map<String, Object> binder = schema(boot(group, false), false, natural) + Map<String, Object> generated = schema(boot(group, true), false, natural) + + then: + generated == binder + generated["table ${table}".toString()].uniqueKeys*.columns == keys + + where: + label | group | table | keys + 'a subclass of a single-table hierarchy' | [NiRoot, NiChild] | 'ni_root' | [['code']] + 'a subclass naming a property of its parent' | [NiMixRoot, NiMixChild] | 'ni_mix_root' | [['code', 'name']] + 'a mutable natural id on a subclass' | [NiMutRoot, NiMutChild] | 'ni_mut_root' | [['code']] + 'a root and a subclass that both state one' | [NiBothRoot, NiBothChild] | 'ni_both_root' | [['code'], ['name']] + 'a subclass three levels down' | [NiGrand, NiGrandChild, NiGrandGrand] | 'ni_grand' | [['extra', 'code']] + 'a subclass naming a foreign key' | [NiFkTarget, NiFkRoot, NiFkChild] | 'ni_fk_root' | [['target_id', 'code']] + 'a subclass of a joined hierarchy' | [NiJRoot, NiJChild] | 'nijchild' | [['region', 'code']] + 'an embedded property after a simple one' | [NiEmb] | 'ni_emb' | [['code', 'home_street', 'home_city']] + 'an embedded property before a simple one' | [NiEmb2] | 'ni_emb2' | [['home_street', 'home_city', 'code']] + 'an embedded property of a subclass' | [NiEmbRoot, NiEmbChild] | 'ni_emb_root' | [['home_street', 'home_city', 'code']] + 'an embedded property alone' | [NiEmbOnly] | 'ni_emb_only' | [['home_street', 'home_city']] + 'a name that is no property after a real one' | [NiTypo] | 'ni_typo' | [['code']] + 'a name that is no property and nothing else' | [NiOnlyTypo] | 'ni_only_typo' | [] + } + + @Unroll + void "the unique key of #label has the name the domain binder gives it"() { + when: + Map<String, Object> binder = schema(boot(group, false), true, false) + Map<String, Object> generated = schema(boot(group, true), true, false) + + then: + generated["table ${table}".toString()].uniqueKeys == binder["table ${table}".toString()].uniqueKeys + generated["table ${table}".toString()].uniqueKeys.size() == count + + where: + label | group | table | count + 'a subclass' | [NiRoot, NiChild] | 'ni_root' | 1 + 'a subclass naming a parent column' | [NiMixRoot, NiMixChild] | 'ni_mix_root' | 1 + 'a subclass of a joined hierarchy' | [NiJRoot, NiJChild] | 'nijchild' | 1 + 'a subclass three levels down' | [NiGrand, NiGrandChild, NiGrandGrand] | 'ni_grand' | 1 + } + + @Unroll + void "#label rejects a duplicate natural id and accepts a distinct one, as the domain binder does"() { + when: + Map<Boolean, List> outcome = [false, true].collectEntries { boolean generated -> + boot(group, generated) + [(generated): attempts.collect { Map values -> save(type, values) }] + } + + then: + outcome[true] == outcome[false] + outcome[true] == expected + + where: + label | group | type | attempts | expected + 'a subclass' | [NiRoot, NiChild] | NiChild | [[code: 'a'], [code: 'b'], [code: 'a']] | ['saved', 'saved', 'rejected: JdbcSQLIntegrityConstraintViolationException'] + 'a subclass with a parent property' | [NiMixRoot, NiMixChild] | NiMixChild | [[code: 'a', name: 'x'], [code: 'a', name: 'y'], [code: 'a', name: 'x']] | ['saved', 'saved', 'rejected: JdbcSQLIntegrityConstraintViolationException'] + 'an embedded property' | [NiEmb] | NiEmb | [[code: 'a', home: new NiHome(street: 's', city: 'c')], [code: 'a', home: new NiHome(street: 's', city: 'd')], [code: 'a', home: new NiHome(street: 's', city: 'c')]] | ['saved', 'saved', 'rejected: JdbcSQLIntegrityConstraintViolationException'] + 'a name that is no property' | [NiTypo] | NiTypo | [[code: 'a'], [code: 'b'], [code: 'a']] | ['saved', 'saved', 'rejected: JdbcSQLIntegrityConstraintViolationException'] + 'nothing but a missing name' | [NiOnlyTypo] | NiOnlyTypo | [[code: 'a'], [code: 'a']] | ['saved', 'saved'] + } + + void "a subclass with a natural id is stored, found by query and updated as the domain binder does, and is also read by id"() { + when: + Map<Boolean, Map> outcome = [false, true].collectEntries { boolean generated -> + boot([NiRoot, NiChild, NiMutRoot, NiMutChild], generated) + Map steps = [:] + Long immutable = null + Long mutable = null + steps.saveImmutable = attempt { immutable = NiChild.withTransaction { NiChild.newInstance(code: 'a', name: 'n').save(failOnError: true, flush: true).id } } + steps.saveMutable = attempt { mutable = NiMutChild.withTransaction { NiMutChild.newInstance(code: 'a').save(failOnError: true, flush: true).id } } + steps.listImmutable = attempt { NiChild.withNewSession { NiChild.list()*.code } } + steps.findImmutable = attempt { NiChild.withNewSession { NiChild.findByCode('a')?.name } } + steps.getImmutable = attempt { NiChild.withNewSession { NiChild.get(immutable).code } } + steps.updateImmutable = attempt { NiChild.withTransaction { NiChild.get(immutable).code = 'changed' } } + steps.updateMutable = attempt { NiMutChild.withTransaction { NiMutChild.get(mutable).code = 'changed' } } + steps.reloadImmutable = attempt { NiChild.withNewSession { NiChild.get(immutable).code } } + steps.reloadMutable = attempt { NiMutChild.withNewSession { NiMutChild.get(mutable).code } } + [(generated): steps] + } + List<String> shared = ['saveImmutable', 'saveMutable', 'listImmutable', 'findImmutable'] + + then: "what the domain binder can do is done the same way" + outcome[true].subMap(shared) == outcome[false].subMap(shared) + outcome[true].subMap(shared) == [saveImmutable: 'ok: 1', saveMutable: 'ok: 1', listImmutable: 'ok: [a]', findImmutable: 'ok: n'] + + and: "the domain binder marks the properties as natural identifiers, which makes Hibernate 7 fail on every load of the subclass" + ['getImmutable', 'updateImmutable', 'updateMutable', 'reloadImmutable', 'reloadMutable'].every { + outcome[false][it] == 'failed: NullPointerException' + } + + and: "the generated mode keeps the unique key and the updatability and loads the entity" + outcome[true].subMap(['getImmutable', 'reloadImmutable', 'reloadMutable']) == + [getImmutable: 'ok: a', reloadImmutable: 'ok: a', reloadMutable: 'ok: changed'] + } + + void "a natural id on an embedded property reloads the embedded value"() { + when: + Map<Boolean, Object> outcome = [false, true].collectEntries { boolean generated -> + boot([NiEmb], generated) + Long id = NiEmb.withTransaction { NiEmb.newInstance(code: 'a', home: new NiHome(street: 's', city: 'c')).save(failOnError: true, flush: true).id } + [(generated): NiEmb.withNewSession { NiEmb e = NiEmb.get(id); [e.code, e.home.street, e.home.city] }] + } + + then: + outcome[true] == outcome[false] + outcome[true] == ['a', 's', 'c'] + } + + 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() + } + } + + private static String save(Class type, Map values) { + try { + type.withTransaction { type.newInstance(values).save(failOnError: true, flush: true) } + return 'saved' + } catch (Throwable e) { + Throwable root = e + while (root.cause != null && root.cause != root) { + root = root.cause + } + return "rejected: ${root.class.simpleName}".toString() + } + } +} + +@Entity +class NiRoot { + String name +} + +@Entity +class NiChild extends NiRoot { + String code + static mapping = { id natural: 'code' } +} + +@Entity +class NiMixRoot { + String name +} + +@Entity +class NiMixChild extends NiMixRoot { + String code + static mapping = { id natural: ['code', 'name'] } +} + +@Entity +class NiMutRoot { + String name +} + +@Entity +class NiMutChild extends NiMutRoot { + String code + static mapping = { id natural: [properties: ['code'], mutable: true] } +} + +@Entity +class NiBothRoot { + String name + static mapping = { id natural: 'name' } +} + +@Entity +class NiBothChild extends NiBothRoot { + String code + static mapping = { id natural: 'code' } +} + +@Entity +class NiGrand { + String name +} + +@Entity +class NiGrandChild extends NiGrand { + String code +} + +@Entity +class NiGrandGrand extends NiGrandChild { + String extra + static mapping = { id natural: ['extra', 'code'] } +} + +@Entity +class NiFkTarget { + String label +} + +@Entity +class NiFkRoot { + String name +} + +@Entity +class NiFkChild extends NiFkRoot { + NiFkTarget target + String code + static mapping = { id natural: ['target', 'code'] } +} + +@Entity +class NiJRoot { + String name + static mapping = { tablePerHierarchy false } +} + +@Entity +class NiJChild extends NiJRoot { + String code + String region + static mapping = { id natural: ['region', 'code'] } +} + +class NiHome { + String street + String city +} + +@Entity +class NiEmb { + String code + NiHome home + static embedded = ['home'] + static mapping = { id natural: ['code', 'home'] } +} + +@Entity +class NiEmb2 { + String code + NiHome home + static embedded = ['home'] + static mapping = { id natural: ['home', 'code'] } +} + +@Entity +class NiEmbRoot { + String label +} + +@Entity +class NiEmbChild extends NiEmbRoot { + String code + NiHome home + static embedded = ['home'] + static mapping = { id natural: ['home', 'code'] } +} + +@Entity +class NiEmbOnly { + NiHome home + static embedded = ['home'] + static mapping = { id natural: ['home'] } +} + +@Entity +class NiTypo { + String code + static mapping = { id natural: ['code', 'typo'] } +} + +@Entity +class NiOnlyTypo { + String code + static mapping = { id natural: ['typo'] } +} 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 cd44f3bb23..b8470381de 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 @@ -83,9 +83,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', - 'declares a natural id but is a subclass', - 'which is HibernateEmbeddedProperty', - 'which is not a persistent property of the entity', ] private static final AtomicInteger BOOTS = new AtomicInteger() 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 dcf4159d8e..5229b4c7bf 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 @@ -157,10 +157,10 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { mismatches.addAll(compareEntity(entity, generator.entityFacets(entity), hierarchy)) mismatches.addAll(compareHierarchy(entity, hierarchy)) if (hierarchy.ownsTable() && generator.generationProblem(entity) == null) { - mismatches.addAll(compareConstraints(entity, generator.constraintFacets(entity), constraints)) + mismatches.addAll(compareConstraints(generator, entity, generator.constraintFacets(entity), constraints)) } if (generator.generationProblem(entity) == null) { - mismatches.addAll(compareNaturalId(entity, generator.naturalIdFacets(entity), naturals)) + mismatches.addAll(compareNaturalId(generator, entity, generator.naturalIdFacets(entity), naturals)) mismatches.addAll(compareCache(entity, generator.cacheFacets(entity), caches)) } } @@ -399,13 +399,14 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { * The indexes and multi-column unique keys on the table the entity owns: the same names, the same columns in the same * order. The unique key the binder adds for a natural id is not part of them (it is compared with the natural id). */ - private List<String> compareConstraints(GrailsHibernatePersistentEntity entity, ConstraintFacets facets, Map<String, Integer> constraints) { + private List<String> compareConstraints( + GrailsDomainGenerator generator, GrailsHibernatePersistentEntity entity, ConstraintFacets facets, Map<String, Integer> constraints) { org.hibernate.mapping.Table table = entity.persistentClass.table String where = "${entity.name} table ${table.name}" Map<String, List<String>> boundIndexes = table.indexes.values().collectEntries { org.hibernate.mapping.Index index -> [(index.name): index.columns*.name] } as Map<String, List<String>> - Map<String, List<String>> boundKeys = tableKeysWithoutNaturalId(entity.persistentClass) + Map<String, List<String>> boundKeys = tableKeysWithoutNaturalId(entity.persistentClass, naturalKeySets(generator, entity)) Map<String, List<String>> generatedIndexes = facets.indexes().collectEntries { IndexFacets index -> [(index.name()): index.columns()] } as Map<String, List<String>> Map<String, List<String>> generatedKeys = facets.uniqueKeys().findAll { UniqueKeyFacets key -> key.bound() } .collectEntries { UniqueKeyFacets key -> [(key.name()): key.columns()] } as Map<String, List<String>> @@ -600,43 +601,107 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { } /** - * The natural identifier: the properties the binder marked natural are the ones the generator names, each is updatable exactly - * when the natural id is mutable, and one unique key spans their columns in the order the mapping names them. + * The natural identifier: the properties the binder marked natural are the ones a natural id of the class or of a subclass + * names (a subclass may name a property it inherits), each property the entity's own natural id names is updatable exactly when + * the natural id is mutable, and one unique key on the table of the class spans their columns in the order the mapping names them. */ - private List<String> compareNaturalId(GrailsHibernatePersistentEntity entity, NaturalIdFacets facets, Map<String, Integer> naturals) { + private List<String> compareNaturalId( + GrailsDomainGenerator generator, GrailsHibernatePersistentEntity entity, NaturalIdFacets facets, Map<String, Integer> naturals) { PersistentClass persistentClass = entity.persistentClass - List<Property> natural = persistentClass.properties.findAll { Property p -> p.naturalIdentifier } + List<Property> natural = persistentClass.declaredProperties.findAll { Property p -> p.naturalIdentifier } String where = "${entity.name} natural id" + Set<String> named = hierarchyNaturalNames(generator, entity) + if (!named.containsAll(natural*.name)) { + return ["${where} properties: generator=${named} binder=${natural*.name}".toString()] + } if (facets == null) { - return natural.isEmpty() ? [] : ["${where} properties: generator=none binder=${natural*.name}".toString()] + return [] } naturals['entities']++ naturals['properties'] += facets.propertyNames().size() List<String> found = [] - if (facets.propertyNames().toSet() != natural*.name.toSet()) { - found << "${where} properties: generator=${facets.propertyNames()} binder=${natural*.name}".toString() - return found - } - natural.each { Property p -> - if (p.updateable != facets.mutable()) { + facets.propertyNames().each { String name -> + Property p = persistentClass.hasProperty(name) ? persistentClass.getProperty(name) : null + if (p == null || !p.naturalIdentifier) { + found << "${where} properties: generator=${facets.propertyNames()} binder=not natural: ${name}".toString() + } else if (p.updateable != facets.mutable()) { found << "${where} updatable of ${p.name}: generator=${facets.mutable()} binder=${p.updateable}".toString() } } - List<String> columns = facets.propertyNames().collectMany { String name -> persistentClass.getProperty(name).columns*.name } + List<String> columns = naturalKeyColumns(generator, entity, persistentClass, facets) if (!persistentClass.table.uniqueKeys.values().any { org.hibernate.mapping.UniqueKey key -> key.columns*.name == columns }) { found << "${where} uniqueKey: generator=${columns} binder=${persistentClass.table.uniqueKeys.values()*.columns*.name}".toString() } return found } + /** + * The columns of the natural id the binder puts in its unique key: those of each property's value, in the order of the mapping. + * The columns of an embedded property are in the order of the properties of the embedded type as it declares them, which is the + * order of the generator's leaves: the binder adds them to the key before Hibernate sorts the properties of the component by + * name, so the bound component no longer tells. + */ + private static List<String> naturalKeyColumns( + GrailsDomainGenerator generator, GrailsHibernatePersistentEntity entity, PersistentClass persistentClass, NaturalIdFacets facets) { + return facets.propertyNames().collectMany { String name -> + Object mapped = entity.getPropertyByName(name) + List<String> bound = persistentClass.getProperty(name).value.selectables.findAll { it instanceof org.hibernate.mapping.Column } + .collect { ((org.hibernate.mapping.Column) it).name } + if (mapped instanceof HibernateEmbeddedProperty) { + List<String> declared = generator.embeddedLeaves((HibernateEmbeddedProperty) mapped).collectMany { EmbeddedLeaf leaf -> + leaf.toOne() != null ? leaf.toOne().joinColumns()*.name() : (leaf.column() != null ? [leaf.column().name()] : []) + } + return declared.toSet() == bound.toSet() ? declared : bound + } + return bound + } as List<String> + } + + /** The properties the natural id of the entity or of one of its subclasses names. */ + private static Set<String> hierarchyNaturalNames(GrailsDomainGenerator generator, GrailsHibernatePersistentEntity entity) { + Set<String> names = new HashSet<String>() + Deque<GrailsHibernatePersistentEntity> pending = new ArrayDeque<GrailsHibernatePersistentEntity>([entity]) + while (!pending.isEmpty()) { + GrailsHibernatePersistentEntity next = pending.poll() + NaturalIdFacets facets = generator.naturalIdFacets(next) + if (facets != null) { + names.addAll(facets.propertyNames()) + } + pending.addAll(next.childEntities) + } + return names + } + + /** + * The column sets of the natural ids of the entity and its subclasses whose unique key lies on the table of the entity: the + * binder puts the key of a subclass of a single-table hierarchy on the table of the hierarchy. They are compared with the natural + * id, not with the unique keys the mapping states. + */ + private static Set<Set<String>> naturalKeySets(GrailsDomainGenerator generator, GrailsHibernatePersistentEntity entity) { + Set<Set<String>> sets = new HashSet<Set<String>>() + Deque<GrailsHibernatePersistentEntity> pending = new ArrayDeque<GrailsHibernatePersistentEntity>([entity]) + while (!pending.isEmpty()) { + GrailsHibernatePersistentEntity next = pending.poll() + NaturalIdFacets facets = generator.naturalIdFacets(next) + if (facets != null && next.persistentClass.table.is(entity.persistentClass.table)) { + sets << naturalKeyColumns(generator, next, next.persistentClass, facets).toSet() + } + pending.addAll(next.childEntities) + } + return sets + } + /** * The natural identifier Hibernate's annotation binder reads from {@code @NaturalId}: the same properties, with the same * updatability, and a unique key over the same columns. The key has the name Hibernate's implicit naming gives it and its * columns follow the order of the fields, not the order the mapping names them: listed, not reported. */ private static List<String> compareAnnotatedNaturalId( - String where, PersistentClass bound, PersistentClass annotated, Map<String, Integer> known) { - List<Property> boundNatural = bound.properties.findAll { Property p -> p.naturalIdentifier } + String where, PersistentClass bound, PersistentClass annotated, NaturalIdFacets facets, Map<String, Integer> known) { + // the properties a subclass names are marked by the binder, not by the annotation (Hibernate refuses @NaturalId on a subclass) + List<Property> boundNatural = bound.properties.findAll { Property p -> + p.naturalIdentifier && facets != null && facets.propertyNames().contains(p.name) + } List<Property> annotatedNatural = annotated.properties.findAll { Property p -> p.naturalIdentifier } if (boundNatural.isEmpty() && annotatedNatural.isEmpty()) { return [] @@ -666,10 +731,7 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { * from a unique column once the metadata is complete (their names start with {@code UK_}), and the unique key over the columns * of a natural id, which is compared with the natural id. */ - private static Map<String, List<String>> tableKeysWithoutNaturalId(PersistentClass persistentClass) { - List<Set<String>> naturalColumns = persistentClass.subclassClosure.collect { PersistentClass member -> - member.declaredProperties.findAll { Property p -> p.naturalIdentifier }*.columns.flatten()*.name.toSet() - }.findAll { Set<String> columns -> !columns.isEmpty() } + private static Map<String, List<String>> tableKeysWithoutNaturalId(PersistentClass persistentClass, Set<Set<String>> naturalColumns) { return persistentClass.table.uniqueKeys.values().findAll { org.hibernate.mapping.UniqueKey key -> !(key.columns.size() == 1 && key.name.startsWith('UK_')) && !naturalColumns.contains(key.columns*.name.toSet()) }.collectEntries { org.hibernate.mapping.UniqueKey key -> @@ -1374,7 +1436,7 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { } if (bound instanceof RootClass) { found.addAll(compareAnnotatedDiscriminator(where, (RootClass) bound, (RootClass) annotated)) - found.addAll(compareAnnotatedNaturalId(where, bound, 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) { annotationRead['composite identifiers']++ @@ -1382,7 +1444,7 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { } } if (pairs.ownsTable[0]) { - found.addAll(compareAnnotatedConstraints(where, bound, annotated, generator.constraintFacets(entity))) + found.addAll(compareAnnotatedConstraints(where, bound, annotated, generator.constraintFacets(entity), naturalKeySets(generator, entity))) } Map<String, Map<String, Object>> expectations = leafExpectations(generator, entity) for (Property property : bound.declaredProperties) { @@ -1454,7 +1516,7 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { * is compared by columns in the natural id comparison and not here. */ private static List<String> compareAnnotatedConstraints( - String where, PersistentClass bound, PersistentClass annotated, ConstraintFacets facets) { + String where, PersistentClass bound, PersistentClass annotated, ConstraintFacets facets, Set<Set<String>> naturalKeys) { Map<String, List<String>> boundIndexes = bound.table.indexes.values().collectEntries { org.hibernate.mapping.Index index -> [(index.name): index.columns*.name] } as Map<String, List<String>> @@ -1465,10 +1527,10 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { if (boundIndexes != annotatedIndexes) { found << "${where} indexes: generator=${annotatedIndexes} binder=${boundIndexes}".toString() } - Map<String, List<String>> boundKeys = tableKeysWithoutNaturalId(bound) + Map<String, List<String>> boundKeys = tableKeysWithoutNaturalId(bound, naturalKeys) // a key the mapping asks for and the binder does not create is stated by the generator, so Hibernate reads it too Set<String> unbound = facets.uniqueKeys().findAll { UniqueKeyFacets key -> !key.bound() }*.name().toSet() - Map<String, List<String>> annotatedKeys = tableKeysWithoutNaturalId(annotated).findAll { String name, List<String> columns -> + Map<String, List<String>> annotatedKeys = tableKeysWithoutNaturalId(annotated, naturalKeys).findAll { String name, List<String> columns -> !unbound.contains(name) } as Map<String, List<String>> if (boundKeys != annotatedKeys) { diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorNaturalIdSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorNaturalIdSpec.groovy index 54f103a5bf..9733d23b20 100644 --- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorNaturalIdSpec.groovy +++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorNaturalIdSpec.groovy @@ -35,7 +35,7 @@ import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersi class GrailsDomainGeneratorNaturalIdSpec extends GrailsDomainGeneratorSupport { void setupSpec() { - manager.registerDomainClasses(GenNatTarget, GenNatMutable, GenNatImmutable, GenNatRef, GenNatRoot, GenNatChild, GenNatTypo, GenNatEmbedded, GenNatNone) + manager.registerDomainClasses(GenNatTarget, GenNatMutable, GenNatImmutable, GenNatRef, GenNatRoot, GenNatChild, GenNatTypo, GenNatOnlyTypo, GenNatEmbedded, GenNatNone) } void "every property of a natural id is marked, and it is mutable only when the mapping says so"() { @@ -86,29 +86,32 @@ class GrailsDomainGeneratorNaturalIdSpec extends GrailsDomainGeneratorSupport { !generateGroup(GenNatNone).values().first().declaredFields.any { it.isAnnotationPresent(NaturalId) } } - void "a natural id that names something the generator cannot state is rejected by name"() { + void "a name that is no property of the entity is skipped, as the domain binder skips it"() { + expect: + newGenerator().naturalIdFacets(entity(GenNatTypo)) == new NaturalIdFacets(['code'], false) + newGenerator().naturalIdFacets(entity(GenNatOnlyTypo)) == null + generateGroup(GenNatTypo).values().first().getDeclaredField('code').isAnnotationPresent(NaturalId) + !generateGroup(GenNatOnlyTypo).values().first().declaredFields.any { it.isAnnotationPresent(NaturalId) } + } + + void "an embedded property can be part of the natural id, and the root states it with the other properties"() { when: - generateGroup(domain) + Class<?> generated = generateGroup(GenNatEmbedded).values().first() then: - UnsupportedOperationException e = thrown() - e.message.contains(domain.simpleName) - e.message.contains(reason) - - where: - domain | reason - GenNatTypo | 'typo' - GenNatEmbedded | 'home' + newGenerator().naturalIdFacets(entity(GenNatEmbedded)) == new NaturalIdFacets(['code', 'home'], false) + generated.getDeclaredField('code').isAnnotationPresent(NaturalId) + !generated.getDeclaredField('home').getAnnotation(NaturalId).mutable() } - void "a natural id on a subclass is rejected by name"() { + void "the natural id of a subclass is described by the facets but not stated: Hibernate refuses @NaturalId on a subclass"() { when: - generateGroup(GenNatRoot, GenNatChild) + Map<GrailsHibernatePersistentEntity, Class<?>> classes = generateGroup(GenNatRoot, GenNatChild) then: - UnsupportedOperationException e = thrown() - e.message.contains('GenNatChild') - e.message.contains('natural') + newGenerator().naturalIdFacets(entity(GenNatChild)) == new NaturalIdFacets(['code'], false) + !classes[entity(GenNatChild)].getDeclaredField('code').isAnnotationPresent(NaturalId) + !classes[entity(GenNatChild)].getDeclaredField('code').getAnnotation(Column).updatable() } private static Map<String, List<Object>> naturalProperties(PersistentClass persistentClass) { @@ -190,6 +193,16 @@ class GenNatTypo { } } +@Entity +class GenNatOnlyTypo { + + String code + + static mapping = { + id natural: ['typo'] + } +} + @Entity class GenNatEmbedded { 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 bfcc235495..de66048bd7 100644 --- a/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc +++ b/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc @@ -66,6 +66,8 @@ For the domain classes in GORM's own test suites, both bindings produce the same * `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 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 [...] * 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]] @@ -85,17 +87,9 @@ Nothing is ignored silently. A mapping that boots is bound the way it is written | `The collection [...] of the embedded type [...] is reachable through N embedded properties (...) ...` | Embed the class from one property only, or make it a domain class and map an association. Classic binding names the table and the key column of the collection after the embedded class, so all the owners share one table whose foreign key points at only one of them, and it fails to boot when the owners name the property alike. -| A natural id declared on a subclass. -| `Entity [...] declares a natural id but is a subclass ...` -| Declare the natural id on the root class of the hierarchy. For a subclass, use a `unique` constraint on its property. Classic binding adds a unique key to the table of the hierarchy. - -| A natural id that names an embedded property, a collection or a formula. -| `The natural id of [...] names [...], which is ... only a simple property, an enum or a foreign key can be part of a natural id ...` -| Name only simple properties, enums and many-to-one associations in `natural`. - -| A natural id that names a property the class does not have. -| `The natural id of [...] names [...], which is not a persistent property of the entity ...` -| Correct the name. Classic binding skips an unknown name without a message, so the entity has no natural id. +| A natural id that names a collection or a formula. +| `The natural id of [...] names [...], which is ... only a simple property, an enum, a foreign key or an embedded type can be part of a natural id ...` +| Name only simple properties, enums, many-to-one associations and embedded objects in `natural`. Classic binding does not boot either: it fails with a `ClassCastException` for a collection and with `constraint involves a formula` for a formula. | A `type` on a `hasMany` of basic values that is a registered Hibernate type name, for example `type: 'text'`, or a custom collection type. | `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 ...`
