You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@grails.apache.org by bo...@apache.org on 2026/10/10 00:37:21 UTC
(grails-core) branch 9.0.x-h7-improvement-phase3 updated (eb82a95c44 -> 22d431010e)
This is an automated email from the ASF dual-hosted git repository.
borinquenkid pushed a change to branch 9.0.x-h7-improvement-phase3
in repository https://gitbox.apache.org/repos/asf/grails-core.git
from eb82a95c44 fix(hibernate7): accept the tenant id as a part of a composite identifier in native binding
new e27c4fdc84 test(hibernate7): state the classic facts the both-modes specs compared against as literal expectations
new 955a1dfe64 refactor(hibernate7): native domain binding is the only binding, the setting that selected the classic one is ignored with a warning
new be15a6fad1 refactor(hibernate7): delete the classic domain binder
new b53eacbe30 test(hibernate7): the classic oracle is frozen, and a new fixture is recorded from a native boot
new edb22b5fec docs(hibernate7): native domain binding is the only binding, the classic binding of Grails 8 is gone
new 22d431010e test(hibernate7): state the Envers audit columns and revision rows native binding gives, as measured
The 6 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
.agents/skills/hibernate-developer/SKILL.md | 67 +-
gradle/hibernate7-test-config.gradle | 29 +-
grails-data-hibernate7/README.md | 44 +-
grails-data-hibernate7/core/classic-only-specs.txt | 39 --
.../HibernateMappingContextConfiguration.groovy | 89 +--
.../cfg/domainbinding/binder/ClassBinder.groovy | 85 ---
.../binder/ClassPropertiesBinder.groovy | 78 ---
.../domainbinding/binder/CollectionBinder.groovy | 231 ------
.../CollectionForPropertyConfigBinder.groovy | 44 --
.../cfg/domainbinding/binder/ColumnBinder.groovy | 156 -----
.../domainbinding/binder/ComponentBinder.groovy | 128 ----
.../domainbinding/binder/ComponentUpdater.groovy | 54 --
.../domainbinding/binder/CompositeIdBinder.groovy | 82 ---
.../CompositeIdentifierToManyToOneBinder.groovy | 159 -----
.../binder/ConfiguredDiscriminatorBinder.groovy | 106 ---
.../binder/DefaultDiscriminatorBinder.groovy | 52 --
.../binder/DiscriminatorPropertyBinder.groovy | 76 --
.../cfg/domainbinding/binder/EnumTypeBinder.groovy | 114 ---
.../binder/ForeignKeyOneToOneBinder.groovy | 79 ---
.../domainbinding/binder/GrailsDomainBinder.groovy | 321 ---------
.../binder/GrailsPropertyBinder.groovy | 116 ---
.../cfg/domainbinding/binder/IdentityBinder.groovy | 54 --
.../binder/JoinedSubClassBinder.groovy | 124 ----
.../domainbinding/binder/ManyToOneBinder.groovy | 152 ----
.../binder/ManyToOneValuesBinder.groovy | 45 --
.../binder/NaturalIdentifierBinder.groovy | 61 --
.../cfg/domainbinding/binder/OneToOneBinder.groovy | 62 --
.../cfg/domainbinding/binder/PropertyBinder.groovy | 118 ----
.../cfg/domainbinding/binder/RootBinder.groovy | 108 ---
.../RootPersistentClassCommonValuesBinder.groovy | 111 ---
.../cfg/domainbinding/binder/SimpleIdBinder.groovy | 84 ---
.../domainbinding/binder/SimpleValueBinder.groovy | 118 ----
.../binder/SimpleValueColumnBinder.groovy | 74 --
.../binder/SingleTableSubclassBinder.groovy | 66 --
.../cfg/domainbinding/binder/SubClassBinder.groovy | 80 ---
.../binder/SubclassMappingBinder.groovy | 74 --
.../binder/UnionSubclassBinder.groovy | 94 ---
.../cfg/domainbinding/binder/VersionBinder.groovy | 77 --
.../collectionType/BagCollectionType.groovy | 39 --
.../collectionType/CollectionHolder.groovy | 59 --
.../collectionType/CollectionType.groovy | 73 --
.../collectionType/ListCollectionType.groovy | 38 -
.../collectionType/MapCollectionType.groovy | 38 -
.../collectionType/SetCollectionType.groovy | 38 -
.../collectionType/SortedSetCollectionType.groovy | 38 -
.../ColumnConfigToColumnBinder.groovy | 2 +-
.../{binder => column}/IndexBinder.groovy | 2 +-
.../NumericColumnConstraintsBinder.groovy | 2 +-
.../StringColumnConstraintsBinder.groovy | 2 +-
.../GrailsHibernatePersistentEntity.groovy | 7 +-
.../hibernate/HibernateBasicEnumProperty.groovy | 5 +-
.../HibernateEmbeddedCollectionProperty.groovy | 7 +-
.../hibernate/HibernateEnumProperty.groovy | 9 +-
.../hibernate/HibernateMappingBuilder.groovy | 4 +-
.../hibernate/HibernateToManyProperty.groovy | 20 +-
.../hibernate/HibernateVersionProperty.groovy | 3 +-
.../cfg/domainbinding/jpa/ConstraintFacets.groovy | 2 +-
.../jpa/GeneratedDomainClassBinder.groovy | 18 +-
.../jpa/GormMappingContributor.groovy | 114 +++
.../domainbinding/jpa/GrailsDomainGenerator.groovy | 119 ++--
.../ManyToManyOwnerValidator.groovy | 6 +-
.../domainbinding/jpa/PropertyAccessorName.groovy | 57 ++
.../cfg/domainbinding/jpa/UniqueKeyFacets.groovy | 2 +-
.../secondpass/BasicCollectionElementBinder.groovy | 89 ---
.../BidirectionalMapElementBinder.groovy | 56 --
.../secondpass/BidirectionalOneToManyLinker.groovy | 63 --
.../secondpass/CollectionKeyBinder.groovy | 102 ---
.../secondpass/CollectionKeyColumnUpdater.groovy | 63 --
.../secondpass/CollectionSecondPassBinder.groovy | 106 ---
.../CollectionWithJoinTableBinder.groovy | 94 ---
.../secondpass/DependentKeyValueBinder.groovy | 61 --
.../HibernateToManyEntityOrderByBinder.groovy | 83 ---
.../domainbinding/secondpass/ListSecondPass.groovy | 47 --
.../secondpass/ListSecondPassBinder.groovy | 156 -----
.../secondpass/ManyToOneElementBinder.groovy | 53 --
.../domainbinding/secondpass/MapSecondPass.groovy | 47 --
.../secondpass/MapSecondPassBinder.groovy | 106 ---
.../secondpass/PrimaryKeyValueCreator.groovy | 57 --
.../domainbinding/secondpass/SetSecondPass.groovy | 53 --
.../ToManyEntityMultiTenantFilterBinder.groovy | 70 --
.../UnidirectionalOneToManyBinder.groovy | 90 ---
...idirectionalOneToManyInverseValuesBinder.groovy | 47 --
.../util/DefaultColumnNameFetcher.groovy | 5 +-
.../util/GrailsPropertyResolver.groovy | 52 --
.../util/MultiTenantFilterBinder.groovy | 171 -----
.../util/NamingStrategyWrapper.groovy | 2 +-
.../domainbinding/util/OrderByClauseBuilder.groovy | 134 ----
.../util/PropertyFromValueCreator.groovy | 55 --
.../util/SimpleValueColumnFetcher.groovy | 32 -
.../util/TableForManyCalculator.groovy | 2 +-
.../HibernateConnectionSourceFactory.groovy | 27 +-
.../HibernateConnectionSourceSettings.groovy | 9 -
.../additional-spring-configuration-metadata.json | 7 +-
.../gorm/tests/HibernateGormDatastoreSpec.groovy | 79 +--
...neratedDomainClassesAnnotatedClassesSpec.groovy | 9 +-
...GeneratedDomainClassesBinderLeniencySpec.groovy | 39 +-
.../GeneratedDomainClassesBootSpec.groovy | 11 +-
.../GeneratedDomainClassesCacheRegionSpec.groovy | 45 +-
...ratedDomainClassesCircularManyToManySpec.groovy | 96 +--
...edDomainClassesCollectionConstraintsSpec.groovy | 80 +--
...atedDomainClassesCollectionIndexTypeSpec.groovy | 50 +-
...GeneratedDomainClassesCollectionSortSpec.groovy | 25 +-
...GeneratedDomainClassesCollectionTypeSpec.groovy | 52 +-
...atedDomainClassesCompositeCollectionSpec.groovy | 36 +-
.../GeneratedDomainClassesCompositeIdSpec.groovy | 2 +-
.../GeneratedDomainClassesContributorSpec.groovy | 22 +-
...GeneratedDomainClassesConverterClassSpec.groovy | 44 +-
.../GeneratedDomainClassesConverterSpec.groovy | 2 +-
...tedDomainClassesCustomCollectionTypeSpec.groovy | 64 +-
.../generated/GeneratedDomainClassesDdlSpec.groovy | 2 +-
.../GeneratedDomainClassesDiscriminatorSpec.groovy | 32 +-
...ratedDomainClassesEmbeddedCollectionSpec.groovy | 96 +--
...tedDomainClassesEmbeddedIdWorkaroundSpec.groovy | 158 ++---
.../GeneratedDomainClassesExtraLazySpec.groovy | 2 +-
.../GeneratedDomainClassesJoinColumnSpec.groovy | 42 +-
.../GeneratedDomainClassesLazyEmbeddedSpec.groovy | 2 +-
.../GeneratedDomainClassesMapManyToManySpec.groovy | 112 ++-
...eneratedDomainClassesMultiDataSourceSpec.groovy | 75 +-
.../GeneratedDomainClassesMultiTenancySpec.groovy | 15 +-
.../GeneratedDomainClassesNaturalIdSpec.groovy | 116 ++-
.../GeneratedDomainClassesQuerySpec.groovy | 2 +-
...neratedDomainClassesSerializableTypeSpec.groovy | 50 +-
.../GeneratedDomainClassesSerializationSpec.groovy | 65 +-
...omainClassesSharedEmbeddedCollectionSpec.groovy | 96 +--
.../generated/GeneratedDomainClassesSpec.groovy | 2 +-
.../GeneratedDomainClassesTenancyModesSpec.groovy | 134 ++--
.../GeneratedDomainClassesTenantTypeSpec.groovy | 42 +-
.../GeneratedDomainClassesTypeMismatchSpec.groovy | 43 +-
...GeneratedDomainClassesTypeParametersSpec.groovy | 27 +-
.../GeneratedDomainClassesWidenedSpecs.groovy | 779 ---------------------
.../GeneratedDomainClassesWriteFlagsSpec.groovy | 63 +-
.../core/GrailsDataHibernate7TckManager.groovy | 26 -
.../orm/hibernate/UserTypeMappingSpec.groovy | 2 +-
...vy => GeneratedDomainClassesSettingSpec.groovy} | 70 +-
.../GrailsHibernatePersistentPropertySpec.groovy | 6 +-
...HibernateMappingContextConfigurationSpec.groovy | 13 +-
.../grails/orm/hibernate/cfg/MappingSpec.groovy | 8 +-
.../grails/orm/hibernate/cfg/NaturalIdSpec.groovy | 6 +-
.../cfg/domainbinding/BasicValueCreatorSpec.groovy | 2 +-
.../CascadeBehaviorFetcherSpec.groovy | 4 +-
.../cfg/domainbinding/ClassBinderSpec.groovy | 177 -----
.../domainbinding/CollectionBinderFixtures.groovy | 87 +++
.../cfg/domainbinding/CollectionBinderSpec.groovy | 227 ------
.../CollectionForPropertyConfigBinderSpec.groovy | 77 --
.../cfg/domainbinding/ColumnBinderFixtures.groovy | 131 ++++
.../cfg/domainbinding/ColumnBinderSpec.groovy | 626 -----------------
.../ColumnConfigToColumnBinderSpec.groovy | 2 +-
.../cfg/domainbinding/ComponentBinderSpec.groovy | 217 ------
.../cfg/domainbinding/CompositeIdBinderSpec.groovy | 97 ---
...CompositeIdentifierToManyToOneBinderSpec.groovy | 176 -----
.../DefaultColumnNameFetcherSpec.groovy | 40 +-
.../domainbinding/EnumTypeBinderFixtures.groovy | 83 +++
.../cfg/domainbinding/EnumTypeBinderSpec.groovy | 266 -------
.../ForeignKeyOneToOneBinderSpec.groovy | 138 ----
.../GrailsIdentityGeneratorSpec.groovy | 4 +-
.../GrailsPropertyBinderFixtures.groovy | 128 ++++
.../domainbinding/GrailsPropertyBinderSpec.groovy | 505 -------------
.../cfg/domainbinding/IdentityBinderSpec.groovy | 83 ---
.../cfg/domainbinding/IndexBinderSpec.groovy | 2 +-
.../cfg/domainbinding/ManyToOneBinderSpec.groovy | 314 ---------
.../domainbinding/ManyToOneValuesBinderSpec.groovy | 76 --
.../domainbinding/NamingStrategyWrapperSpec.groovy | 4 +-
.../NaturalIdentifierBinderSpec.groovy | 103 ---
.../NumericColumnConstraintsBinderSpec.groovy | 2 +-
.../cfg/domainbinding/OneToOneBinderSpec.groovy | 145 ----
.../domainbinding/OrderByClauseBuilderSpec.groovy | 182 -----
.../domainbinding/PropertyBinderFixtures.groovy | 43 +-
.../cfg/domainbinding/PropertyBinderSpec.groovy | 229 ------
.../PropertyFromValueCreatorSpec.groovy | 85 ---
.../cfg/domainbinding/SimpleIdBinderSpec.groovy | 231 ------
.../cfg/domainbinding/SimpleValueBinderSpec.groovy | 342 ---------
.../SimpleValueColumnBinderSpec.groovy | 70 --
.../SimpleValueColumnFetcherSpec.groovy | 62 --
.../StringColumnConstraintsBinderSpec.groovy | 2 +-
.../TableForManyCalculatorSpec.groovy | 26 +-
.../cfg/domainbinding/VersionBinderFixtures.groovy | 41 +-
.../cfg/domainbinding/VersionBinderSpec.groovy | 150 ----
.../binder/ClassPropertiesBinderSpec.groovy | 111 ---
.../binder/ComponentUpdaterFixtures.groovy | 24 +-
.../binder/ComponentUpdaterSpec.groovy | 115 ---
.../ConfiguredDiscriminatorBinderFixtures.groovy} | 16 +-
.../ConfiguredDiscriminatorBinderSpec.groovy | 195 ------
.../binder/DefaultDiscriminatorBinderSpec.groovy | 65 --
.../DiscriminatorPropertyBinderFixtures.groovy} | 16 +-
.../binder/DiscriminatorPropertyBinderSpec.groovy | 135 ----
.../binder/JoinedSubClassBinderFixtures.groovy} | 26 +-
.../binder/JoinedSubClassBinderSpec.groovy | 105 ---
.../binder/ManyToManyWithoutOwnerSpec.groovy | 71 +-
.../cfg/domainbinding/binder/RootBinderSpec.groovy | 173 -----
...ersistentClassCommonValuesBinderFixtures.groovy | 50 +-
...ootPersistentClassCommonValuesBinderSpec.groovy | 173 -----
.../SingleTableSubclassBinderFixtures.groovy} | 31 +-
.../binder/SingleTableSubclassBinderSpec.groovy | 104 ---
.../domainbinding/binder/SubClassBinderSpec.groovy | 105 ---
.../binder/SubclassMappingBinderFixtures.groovy} | 46 +-
.../binder/SubclassMappingBinderSpec.groovy | 173 -----
.../binder/UnionSubclassBinderFixtures.groovy} | 27 +-
.../binder/UnionSubclassBinderSpec.groovy | 88 ---
.../collectionType/BagCollectionTypeSpec.groovy | 63 --
.../collectionType/CollectionHolderSpec.groovy | 53 --
.../collectionType/ListCollectionTypeSpec.groovy | 63 --
.../collectionType/MapCollectionTypeSpec.groovy | 63 --
.../collectionType/SetCollectionTypeSpec.groovy | 98 ---
.../SortedSetCollectionTypeSpec.groovy | 63 --
.../GrailsSequenceStyleGeneratorSpec.groovy | 12 +-
.../generator/GrailsTableGeneratorSpec.groovy | 6 +-
.../hibernate/HibernateBasicPropertySpec.groovy | 27 +-
.../HibernateEmbeddedCollectionPropertySpec.groovy | 2 +-
.../HibernateManyToManyPropertySpec.groovy | 6 +-
.../HibernateOneToManyPropertySpec.groovy | 4 +-
.../hibernate/HibernatePersistentEntitySpec.groovy | 2 +-
.../hibernate/HibernateToManyPropertySpec.groovy | 80 +--
.../cfg/domainbinding/jpa/ClassicOracle.groovy | 148 ++--
.../cfg/domainbinding/jpa/ClassicOracleSpec.groovy | 121 +++-
...onDefectSpec.groovy => ColumnOptionSpec.groovy} | 29 +-
...eneratedDomainClassesDdlDifferentialSpec.groovy | 53 +-
.../GrailsDomainBinderCompositeIdDefectSpec.groovy | 96 ---
...DomainBinderEmbeddedCollectionDefectSpec.groovy | 50 --
.../GrailsDomainGeneratorCompositeIdSpec.groovy | 4 +-
.../GrailsDomainGeneratorDifferentialSpec.groovy | 122 ++--
.../jpa/GrailsDomainGeneratorSpec.groovy | 17 +-
.../jpa/GrailsDomainGeneratorSupport.groovy | 8 +-
.../jpa/GrailsDomainGeneratorTenantSpec.groovy | 8 +-
.../GrailsDomainGeneratorUniqueGroupSpec.groovy | 17 +-
...tSpec.groovy => ManyToManyOwnershipSpec.groovy} | 9 +-
.../jpa/PropertyAccessorNameSpec.groovy | 73 ++
...y => UnidirectionalBasicCollectionsSpec.groovy} | 9 +-
... => UnidirectionalEntityCollectionsSpec.groovy} | 13 +-
.../BasicCollectionElementBinderFixtures.groovy | 95 +++
.../BasicCollectionElementBinderSpec.groovy | 271 -------
.../BasicCollectionKeyPersistenceSpec.groovy | 6 +-
.../BidirectionalMapElementBinderFixtures.groovy} | 25 +-
.../BidirectionalMapElementBinderSpec.groovy | 102 ---
.../BidirectionalOneToManyLinkerSpec.groovy | 79 ---
.../secondpass/CollectionKeyBinderFixtures.groovy | 94 +++
.../secondpass/CollectionKeyBinderSpec.groovy | 289 --------
.../CollectionKeyColumnUpdaterFixtures.groovy} | 46 +-
.../CollectionKeyColumnUpdaterSpec.groovy | 141 ----
.../CollectionSecondPassBinderFixtures.groovy | 117 ++++
.../CollectionSecondPassBinderSpec.groovy | 390 -----------
.../CollectionWithJoinTableBinderFixtures.groovy} | 31 +-
.../CollectionWithJoinTableBinderSpec.groovy | 177 -----
.../DependentKeyValueBinderFixtures.groovy | 49 +-
.../secondpass/DependentKeyValueBinderSpec.groovy | 131 ----
...bernateToManyEntityOrderByBinderFixtures.groovy | 67 ++
.../HibernateToManyEntityOrderByBinderSpec.groovy | 218 ------
.../secondpass/ListSecondPassBinderFixtures.groovy | 91 +++
.../secondpass/ListSecondPassBinderSpec.groovy | 323 ---------
.../ManyToOneElementBinderFixtures.groovy} | 54 +-
.../secondpass/ManyToOneElementBinderSpec.groovy | 106 ---
.../secondpass/MapSecondPassBinderFixtures.groovy} | 33 +-
.../secondpass/MapSecondPassBinderSpec.groovy | 465 ------------
.../secondpass/PrimaryKeyValueCreatorSpec.groovy | 102 ---
...anyEntityMultiTenantFilterBinderFixtures.groovy | 78 +++
.../ToManyEntityMultiTenantFilterBinderSpec.groovy | 191 -----
.../UnidirectionalOneToManyBinderFixtures.groovy | 23 +-
.../UnidirectionalOneToManyBinderSpec.groovy | 162 -----
...onalOneToManyInverseValuesBinderFixtures.groovy | 43 +-
...ectionalOneToManyInverseValuesBinderSpec.groovy | 105 ---
.../util/GrailsPropertyResolverSpec.groovy | 101 ---
.../util/MultiTenantFilterBinderSpec.groovy | 196 ------
.../MultiTenantFilterDefinitionBinderSpec.groovy | 2 +-
.../HibernateConnectionSourceSettingsSpec.groovy | 84 +--
.../src/test/resources/simplelogger.properties | 1 -
.../generated/GeneratedModeEnversSpec.groovy | 103 +--
.../generated/GeneratedModeSnapshotSpec.groovy | 90 +--
.../advancedGORMFeatures/nativeDomainBinding.adoc | 166 ++---
.../configuration/configurationReference.adoc | 2 +-
.../asciidoc/gettingStarted/hibernateVersions.adoc | 10 +-
.../src/en/guide/upgrading/upgrading90x.adoc | 45 +-
270 files changed, 3180 insertions(+), 19107 deletions(-)
delete mode 100644 grails-data-hibernate7/core/classic-only-specs.txt
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ClassBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ClassPropertiesBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CollectionBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CollectionForPropertyConfigBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ColumnBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ComponentBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ComponentUpdater.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeIdBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeIdentifierToManyToOneBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ConfiguredDiscriminatorBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/DefaultDiscriminatorBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/DiscriminatorPropertyBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/EnumTypeBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ForeignKeyOneToOneBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/GrailsDomainBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/GrailsPropertyBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/IdentityBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/JoinedSubClassBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ManyToOneBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ManyToOneValuesBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/NaturalIdentifierBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/OneToOneBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/PropertyBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/RootBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/RootPersistentClassCommonValuesBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SimpleIdBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SimpleValueBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SimpleValueColumnBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SingleTableSubclassBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SubClassBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SubclassMappingBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/UnionSubclassBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/VersionBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/collectionType/BagCollectionType.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/collectionType/CollectionHolder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/collectionType/CollectionType.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/collectionType/ListCollectionType.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/collectionType/MapCollectionType.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/collectionType/SetCollectionType.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/collectionType/SortedSetCollectionType.groovy
rename grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/{binder => column}/ColumnConfigToColumnBinder.groovy (97%)
rename grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/{binder => column}/IndexBinder.groovy (97%)
rename grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/{binder => column}/NumericColumnConstraintsBinder.groovy (98%)
rename grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/{binder => column}/StringColumnConstraintsBinder.groovy (98%)
create mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GormMappingContributor.groovy
rename grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/{binder => jpa}/ManyToManyOwnerValidator.groovy (92%)
create mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/PropertyAccessorName.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/BasicCollectionElementBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/BidirectionalMapElementBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/BidirectionalOneToManyLinker.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionKeyBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionKeyColumnUpdater.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionSecondPassBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionWithJoinTableBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/DependentKeyValueBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/HibernateToManyEntityOrderByBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/ListSecondPass.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/ListSecondPassBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/ManyToOneElementBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/MapSecondPass.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/MapSecondPassBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/PrimaryKeyValueCreator.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/SetSecondPass.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/ToManyEntityMultiTenantFilterBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/UnidirectionalOneToManyBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/UnidirectionalOneToManyInverseValuesBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/GrailsPropertyResolver.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/MultiTenantFilterBinder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/OrderByClauseBuilder.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/PropertyFromValueCreator.groovy
delete mode 100644 grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/SimpleValueColumnFetcher.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesWidenedSpecs.groovy
rename grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/{ClassicDomainBindingDeprecationSpec.groovy => GeneratedDomainClassesSettingSpec.groovy} (55%)
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ClassBinderSpec.groovy
create mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CollectionBinderFixtures.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CollectionBinderSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CollectionForPropertyConfigBinderSpec.groovy
create mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ColumnBinderFixtures.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ColumnBinderSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ComponentBinderSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CompositeIdBinderSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CompositeIdentifierToManyToOneBinderSpec.groovy
create mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/EnumTypeBinderFixtures.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/EnumTypeBinderSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ForeignKeyOneToOneBinderSpec.groovy
create mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/GrailsPropertyBinderFixtures.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/GrailsPropertyBinderSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/IdentityBinderSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ManyToOneBinderSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ManyToOneValuesBinderSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/NaturalIdentifierBinderSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/OneToOneBinderSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/OrderByClauseBuilderSpec.groovy
copy grails-data-mongodb/core/src/test/groovy/grails/gorm/tests/Plant.groovy => grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/PropertyBinderFixtures.groovy (52%)
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/PropertyBinderSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/PropertyFromValueCreatorSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/SimpleIdBinderSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/SimpleValueBinderSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/SimpleValueColumnBinderSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/SimpleValueColumnFetcherSpec.groovy
copy grails-data-neo4j/core/src/test/groovy/grails/gorm/tests/Pet.groovy => grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/VersionBinderFixtures.groovy (52%)
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/VersionBinderSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ClassPropertiesBinderSpec.groovy
copy grails-data-hibernate5/core/src/test/groovy/grails/gorm/tests/entities/Club.groovy => grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ComponentUpdaterFixtures.groovy (59%)
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ComponentUpdaterSpec.groovy
copy grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/{connections/MultiTenantPublisher.groovy => cfg/domainbinding/binder/ConfiguredDiscriminatorBinderFixtures.groovy} (70%)
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ConfiguredDiscriminatorBinderSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/DefaultDiscriminatorBinderSpec.groovy
copy grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/{connections/MultiTenantPublisher.groovy => cfg/domainbinding/binder/DiscriminatorPropertyBinderFixtures.groovy} (70%)
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/DiscriminatorPropertyBinderSpec.groovy
copy grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/{connections/MultiTenantBook.groovy => cfg/domainbinding/binder/JoinedSubClassBinderFixtures.groovy} (66%)
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/JoinedSubClassBinderSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/RootBinderSpec.groovy
copy grails-data-neo4j/core/src/test/groovy/grails/gorm/tests/Pet.groovy => grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/RootPersistentClassCommonValuesBinderFixtures.groovy (56%)
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/RootPersistentClassCommonValuesBinderSpec.groovy
copy grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/{connections/MultiTenantBook.groovy => cfg/domainbinding/binder/SingleTableSubclassBinderFixtures.groovy} (61%)
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SingleTableSubclassBinderSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SubClassBinderSpec.groovy
copy grails-data-hibernate7/core/src/test/groovy/{grails/unbootable/ManyToManyWithoutOwnerDomains.groovy => org/grails/orm/hibernate/cfg/domainbinding/binder/SubclassMappingBinderFixtures.groovy} (54%)
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SubclassMappingBinderSpec.groovy
copy grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/{connections/MultiTenantBook.groovy => cfg/domainbinding/binder/UnionSubclassBinderFixtures.groovy} (64%)
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/UnionSubclassBinderSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/collectionType/BagCollectionTypeSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/collectionType/CollectionHolderSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/collectionType/ListCollectionTypeSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/collectionType/MapCollectionTypeSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/collectionType/SetCollectionTypeSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/collectionType/SortedSetCollectionTypeSpec.groovy
rename grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/{GrailsDomainBinderOptionDefectSpec.groovy => ColumnOptionSpec.groovy} (75%)
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainBinderCompositeIdDefectSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainBinderEmbeddedCollectionDefectSpec.groovy
rename grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/{ManyToManyOwnershipDefectSpec.groovy => ManyToManyOwnershipSpec.groovy} (80%)
create mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/PropertyAccessorNameSpec.groovy
rename grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/{BasicCollectionKeyDefectSpec.groovy => UnidirectionalBasicCollectionsSpec.groovy} (81%)
rename grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/{EntityCollectionKeyDefectSpec.groovy => UnidirectionalEntityCollectionsSpec.groovy} (74%)
create mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/BasicCollectionElementBinderFixtures.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/BasicCollectionElementBinderSpec.groovy
copy grails-data-hibernate7/core/src/{main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/GrailsSecondPass.groovy => test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/BidirectionalMapElementBinderFixtures.groovy} (61%)
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/BidirectionalMapElementBinderSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/BidirectionalOneToManyLinkerSpec.groovy
create mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionKeyBinderFixtures.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionKeyBinderSpec.groovy
copy grails-data-hibernate7/core/src/test/groovy/{grails/unbootable/ManyToManyWithoutOwnerDomains.groovy => org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionKeyColumnUpdaterFixtures.groovy} (54%)
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionKeyColumnUpdaterSpec.groovy
create mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionSecondPassBinderFixtures.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionSecondPassBinderSpec.groovy
copy grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/{connections/MultiTenantBook.groovy => cfg/domainbinding/secondpass/CollectionWithJoinTableBinderFixtures.groovy} (61%)
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionWithJoinTableBinderSpec.groovy
copy grails-data-neo4j/core/src/test/groovy/grails/gorm/tests/Pet.groovy => grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/DependentKeyValueBinderFixtures.groovy (51%)
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/DependentKeyValueBinderSpec.groovy
create mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/HibernateToManyEntityOrderByBinderFixtures.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/HibernateToManyEntityOrderByBinderSpec.groovy
create mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/ListSecondPassBinderFixtures.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/ListSecondPassBinderSpec.groovy
copy grails-data-hibernate7/{dbmigration/src/test/groovy/liquibase/ext/hibernate/snapshot/AuctionEntities.groovy => core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/ManyToOneElementBinderFixtures.groovy} (55%)
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/ManyToOneElementBinderSpec.groovy
rename grails-data-hibernate7/core/src/{main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/GrailsSecondPass.groovy => test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/MapSecondPassBinderFixtures.groovy} (55%)
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/MapSecondPassBinderSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/PrimaryKeyValueCreatorSpec.groovy
create mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/ToManyEntityMultiTenantFilterBinderFixtures.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/ToManyEntityMultiTenantFilterBinderSpec.groovy
copy grails-data-mongodb/core/src/test/groovy/grails/gorm/tests/Face.groovy => grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/UnidirectionalOneToManyBinderFixtures.groovy (66%)
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/UnidirectionalOneToManyBinderSpec.groovy
copy grails-data-neo4j/core/src/test/groovy/grails/gorm/tests/Pet.groovy => grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/UnidirectionalOneToManyInverseValuesBinderFixtures.groovy (58%)
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/UnidirectionalOneToManyInverseValuesBinderSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/GrailsPropertyResolverSpec.groovy
delete mode 100644 grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/MultiTenantFilterBinderSpec.groovy
(grails-core) 06/06: test(hibernate7): state the Envers audit columns and revision rows native binding gives, as measured
Posted by bo...@apache.org.
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 22d431010ea77ee989580371fbff8cd3072e8a3c
Author: Walter Duque de Estrada <wb...@mac.com>
AuthorDate: Fri Oct 9 18:55:11 2026 -0500
test(hibernate7): state the Envers audit columns and revision rows native binding gives, as measured
The literals that 955a1dfe64 wrote into GeneratedModeEnversSpec when it dropped the classic
half of the spec were not captured from a run: that commit's verification never executed the
spec, and the full module run of the deletion step failed three of its features. The values
were therefore measured at eb82a95c44, the step 2 tip, in a throwaway worktree, native default
and classic binding both, and are identical to HEAD's:
- envers_book_aud: [class, genre, id, pages, rev, revtype, title, version] natively (classic
had secret in addition, the @NotAudited field Envers read through the getter); class and
genre are the discriminator and the subclass column of the single-table hierarchy
EnversNovel extends EnversBook, which shares the audit table
- the version written at the revisions of EnversVersioned and EnversCustomVersion:
[[0, 0], [1, 1], [1, 2], [2, null]], null at the DEL revision because Envers stores no
property data there unless store_data_at_delete is set, in both bindings
- the columns of the other audit tables: [id, name, rev, revtype, version],
[id, name, rev, revtype] and [id, lock_no, name, rev, revtype], the same in both bindings
So the deletion of the classic binder changed no Envers behaviour; the spec now states the
measured values. The dbmigration module passes (109 tests, 93 CLI tests).
Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
---
.../databasemigration/generated/GeneratedModeEnversSpec.groovy | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/grails-data-hibernate7/dbmigration/src/test/groovy/org/grails/plugins/databasemigration/generated/GeneratedModeEnversSpec.groovy b/grails-data-hibernate7/dbmigration/src/test/groovy/org/grails/plugins/databasemigration/generated/GeneratedModeEnversSpec.groovy
index bebbc6c6ab..5c3500ca3c 100644
--- a/grails-data-hibernate7/dbmigration/src/test/groovy/org/grails/plugins/databasemigration/generated/GeneratedModeEnversSpec.groovy
+++ b/grails-data-hibernate7/dbmigration/src/test/groovy/org/grails/plugins/databasemigration/generated/GeneratedModeEnversSpec.groovy
@@ -130,7 +130,7 @@ class GeneratedModeEnversSpec extends Specification {
['hibernate.additionalProperties': ['org.hibernate.envers.do_not_audit_optimistic_locking_field': 'false']]))
then: 'the annotation is on the field Envers reads (the classic binding of Grails 8 audited the property, since Envers read the getter), and the version is audited as it was then'
- generated['envers_book_aud'] == ['id', 'pages', 'rev', 'revtype', 'title', 'version']
+ generated['envers_book_aud'] == ['class', 'genre', 'id', 'pages', 'rev', 'revtype', 'title', 'version']
and: 'Envers\' own setting, which a user can still set, gives the same'
generatedWithVersion['envers_book_aud'].contains('version')
@@ -188,14 +188,14 @@ class GeneratedModeEnversSpec extends Specification {
then: 'the audit table has the columns of the entity, the revision and the revision type'
generated.columns*.getAt(0) == columns
- and: 'the version written at each revision is the one of the row then'
+ and: 'the version written at each revision is the one of the row then, and null at the deletion (Envers stores no data at a DEL revision by default), as with classic binding'
generated.rows == rows
where:
type | table | versionColumn | columns | rows
- EnversVersioned | 'envers_versioned_aud' | 'version' | ['id', 'name', 'rev', 'revtype', 'version'] | [[0, 0], [1, 1], [1, 2], [2, 2]]
+ EnversVersioned | 'envers_versioned_aud' | 'version' | ['id', 'name', 'rev', 'revtype', 'version'] | [[0, 0], [1, 1], [1, 2], [2, null]]
EnversUnversioned | 'envers_unversioned_aud' | null | ['id', 'name', 'rev', 'revtype'] | null
- EnversCustomVersion | 'envers_custom_version_aud' | 'lock_no' | ['id', 'lock_no', 'name', 'rev', 'revtype'] | [[0, 0], [1, 1], [1, 2], [2, 2]]
+ EnversCustomVersion | 'envers_custom_version_aud' | 'lock_no' | ['id', 'lock_no', 'name', 'rev', 'revtype'] | [[0, 0], [1, 1], [1, 2], [2, null]]
}
private static Map shelfHistory() {
(grails-core) 02/06: refactor(hibernate7): native domain binding is the only binding, the setting that selected the classic one is ignored with a warning
Posted by bo...@apache.org.
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 955a1dfe6448f069bdb7bc6990a828d580ec8f52
Author: Walter Duque de Estrada <wb...@mac.com>
AuthorDate: Fri Oct 9 17:41:05 2026 -0500
refactor(hibernate7): native domain binding is the only binding, the setting that selected the classic one is ignored with a warning
hibernate.generatedDomainClasses selected the classic domain binder of Grails 8 when set to
false. The classic binder is being deleted, so the switch goes first: HibernateMappingContextConfiguration
always binds through the generated classes, HibernateConnectionSourceSettings has no such field
and the test-only JVM property grails.hibernate.classicDomainBinding is gone with it. An
application upgraded from Grails 8 that still sets the key, with either value or on a named
data source, boots natively and HibernateConnectionSourceFactory logs once per data source that
the setting is no longer used (GeneratedDomainClassesSettingSpec). The configuration metadata
keeps the key as deprecated at level error, so an IDE flags it.
The test infrastructure loses its two modes: the TCK manager's CLASSIC_MODE_PROPERTY and
registerGeneratedDomainClasses, the Gradle property grails.test.classicDomainBinding and the
classic-only exclusion, and GeneratedDomainClassesWidenedSpecs, whose 94 subclasses only ran
their parents natively while classic was the default and now duplicated them. The two
dbmigration specs that booted both bindings state the native snapshot, change log and Envers
audit tables literally.
Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
---
gradle/hibernate7-test-config.gradle | 15 -
grails-data-hibernate7/README.md | 9 -
.../HibernateMappingContextConfiguration.groovy | 74 +-
.../HibernateConnectionSourceFactory.groovy | 27 +-
.../HibernateConnectionSourceSettings.groovy | 9 -
.../additional-spring-configuration-metadata.json | 7 +-
.../gorm/tests/HibernateGormDatastoreSpec.groovy | 11 -
...neratedDomainClassesAnnotatedClassesSpec.groovy | 9 +-
.../GeneratedDomainClassesBootSpec.groovy | 9 +-
.../GeneratedDomainClassesCompositeIdSpec.groovy | 2 +-
.../GeneratedDomainClassesConverterSpec.groovy | 2 +-
.../generated/GeneratedDomainClassesDdlSpec.groovy | 2 +-
.../GeneratedDomainClassesExtraLazySpec.groovy | 2 +-
.../GeneratedDomainClassesLazyEmbeddedSpec.groovy | 2 +-
.../GeneratedDomainClassesQuerySpec.groovy | 2 +-
.../generated/GeneratedDomainClassesSpec.groovy | 2 +-
.../GeneratedDomainClassesWidenedSpecs.groovy | 779 ---------------------
.../core/GrailsDataHibernate7TckManager.groovy | 26 -
.../orm/hibernate/UserTypeMappingSpec.groovy | 2 +-
...vy => GeneratedDomainClassesSettingSpec.groovy} | 70 +-
...HibernateMappingContextConfigurationSpec.groovy | 13 +-
.../HibernateConnectionSourceSettingsSpec.groovy | 84 +--
.../generated/GeneratedModeEnversSpec.groovy | 103 +--
.../generated/GeneratedModeSnapshotSpec.groovy | 90 +--
24 files changed, 170 insertions(+), 1181 deletions(-)
diff --git a/gradle/hibernate7-test-config.gradle b/gradle/hibernate7-test-config.gradle
index 25ea89a0b2..c5b100edf8 100644
--- a/gradle/hibernate7-test-config.gradle
+++ b/gradle/hibernate7-test-config.gradle
@@ -46,21 +46,6 @@ tasks.withType(Test).configureEach {
useJUnitPlatform()
- // Native domain binding (hibernate.generatedDomainClasses, on by default) is what the suite runs by default.
- // -Pgrails.test.classicDomainBinding=true boots every datastore that does not set the key itself through the classic
- // domain binder instead (system property grails.hibernate.classicDomainBinding, read by the settings default and by the
- // TCK manager). Specs that exercise the classic binder's internals only make sense in that run and are listed, one
- // class name per line, in the module's classic-only-specs.txt: the default run excludes them, the classic run runs them.
- if (providers.gradleProperty('grails.test.classicDomainBinding').map { it.toBoolean() }.getOrElse(false)) {
- systemProperty('grails.hibernate.classicDomainBinding', 'true')
- } else {
- File classicOnly = project.file('classic-only-specs.txt')
- if (classicOnly.exists()) {
- classicOnly.readLines().collect { it.trim() }.findAll { it && !it.startsWith('#') }.each { String pattern ->
- filter.excludeTestsMatching(pattern)
- }
- }
- }
// The differential specs compare native domain binding against what the classic binder produced, recorded under
// src/test/resources/classic-oracle/. By default they read the recorded files and do not boot the classic binder.
// -Pgrails.test.verifyClassicOracle=true boots it too and asserts it still produces exactly the recorded data;
diff --git a/grails-data-hibernate7/README.md b/grails-data-hibernate7/README.md
index 9484b9f4e7..dcfea0c232 100644
--- a/grails-data-hibernate7/README.md
+++ b/grails-data-hibernate7/README.md
@@ -53,15 +53,6 @@ Registered via `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfi
A Grails CLI SPI hook (`org.grails.cli.compiler.CompilerAutoConfiguration`) that detects `@Entity` classes in Grails scripts and automatically adds the `grails-data-hibernate7-core` dependency and `grails.gorm.*` imports to the compilation context.
Registered via `META-INF/services/org.grails.cli.compiler.CompilerAutoConfiguration`.
-## Running the suite with the classic domain binder (contributors)
-
-Native domain binding is the default (`hibernate.generatedDomainClasses` defaults to `true`), so the core suite boots every datastore the
-TCK manager builds natively. `./gradlew -Pgrails.test.classicDomainBinding=true :grails-data-hibernate7-core:test` boots them through the
-deprecated classic binder instead (the Gradle property sets the JVM property `grails.hibernate.classicDomainBinding`, which the settings
-default and the TCK manager read; a spec that sets `hibernate.generatedDomainClasses` itself is not affected). The specs listed in
-`core/classic-only-specs.txt` assert facts of the classic boot model and run only in that mode; the default run excludes them. Both modes
-are wired in `gradle/hibernate7-test-config.gradle`.
-
## Differential specs and the frozen classic oracle (contributors)
Native domain binding (`hibernate.generatedDomainClasses`, `GrailsDomainGenerator`) is checked against what the classic domain binder
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/HibernateMappingContextConfiguration.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/HibernateMappingContextConfiguration.groovy
index 592223712f..bf46fb0685 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/HibernateMappingContextConfiguration.groovy
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/HibernateMappingContextConfiguration.groovy
@@ -43,8 +43,6 @@ import org.hibernate.cfg.JdbcSettings
import org.hibernate.context.spi.CurrentSessionContext
import org.hibernate.internal.util.config.ConfigurationHelper
import org.hibernate.service.ServiceRegistry
-import org.slf4j.Logger
-import org.slf4j.LoggerFactory
import org.springframework.beans.BeansException
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
@@ -89,17 +87,6 @@ class HibernateMappingContextConfiguration extends Configuration
private static final long serialVersionUID = -7115087342689305517L
- private static final Logger LOG = LoggerFactory.getLogger(HibernateMappingContextConfiguration)
-
- /**
- * The warning logged once per session factory when the classic domain binding is selected.
- */
- static final String CLASSIC_DOMAIN_BINDING_DEPRECATED =
- 'Classic domain binding is deprecated and will be removed: hibernate.generatedDomainClasses is false ' +
- 'for data source [%s]. Native domain binding, the default, binds the domain classes with Hibernate\'s own ' +
- 'annotation binder; remove the setting, or set it to true, after reviewing the Native Domain Binding chapter ' +
- 'of the GORM for Hibernate 7 manual.'
-
private static final String RESOURCE_PATTERN = '/**/*.class'
private static final TypeFilter[] ENTITY_TYPE_FILTERS = [
@@ -123,26 +110,6 @@ class HibernateMappingContextConfiguration extends Configuration
private transient ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver()
private transient NamingStrategyProvider namingStrategyProvider = new NamingStrategyProvider()
protected GrailsBytecodeProvider bytecodeProvider
- private boolean generatedDomainClasses = true
-
- /**
- * Whether Hibernate's annotation binder binds classes generated from the GORM mapping (native domain binding, the
- * default) instead of the classic domain binder building Hibernate's boot model by hand. The real domain classes are
- * still what is persisted and loaded.
- *
- * <p>Set it before the annotated classes are added: with the switch on, {@link #addAnnotatedClass} keeps the GORM entities
- * that are not JPA entities away from Hibernate's own sources (see there).</p>
- *
- * @param generatedDomainClasses {@code true} (the default) to bind generated classes; {@code false} for the classic
- * domain binder, which is deprecated and will be removed
- */
- void setGeneratedDomainClasses(boolean generatedDomainClasses) {
- this.generatedDomainClasses = generatedDomainClasses
- }
-
- boolean isGeneratedDomainClasses() {
- return generatedDomainClasses
- }
void setBytecodeProvider(GrailsBytecodeProvider bytecodeProvider) {
this.bytecodeProvider = bytecodeProvider
@@ -229,16 +196,15 @@ class HibernateMappingContextConfiguration extends Configuration
}
/**
- * Registers the class for the mapping context and hands it to Hibernate's own sources. With
- * {@link #setGeneratedDomainClasses generated domain classes} a GORM entity that is not a JPA entity is not handed to
- * Hibernate: the class generated for it has the same name, and Hibernate keeps the first class it is given for a name, so
- * the real class, which Hibernate cannot read as an entity, would hide the generated one and leave the entity unmapped.
- * The entity is bound through the mapping context as usual.
+ * Registers the class for the mapping context and hands it to Hibernate's own sources. A GORM entity that is not a JPA
+ * entity is not handed to Hibernate: the class generated for it has the same name, and Hibernate keeps the first class it
+ * is given for a name, so the real class, which Hibernate cannot read as an entity, would hide the generated one and leave
+ * the entity unmapped. The entity is bound through the mapping context as usual.
*/
@Override
Configuration addAnnotatedClass(Class annotatedClass) {
additionalClasses.add(annotatedClass)
- if (generatedDomainClasses && GormEntity.isAssignableFrom(annotatedClass) && !annotatedClass.isAnnotationPresent(Entity)) {
+ if (GormEntity.isAssignableFrom(annotatedClass) && !annotatedClass.isAnnotationPresent(Entity)) {
return this
}
return super.addAnnotatedClass(annotatedClass)
@@ -353,11 +319,7 @@ class HibernateMappingContextConfiguration extends Configuration
persistentEntity.setDataSourceName(dataSourceName)
}
- if (!generatedDomainClasses) {
- LOG.warn(String.format(CLASSIC_DOMAIN_BINDING_DEPRECATED, dataSourceName))
- }
- final GeneratedDomainClassBinder generatedBinder =
- generatedDomainClasses ? new GeneratedDomainClassBinder(dataSourceName, appClassLoader) : null
+ final GeneratedDomainClassBinder generatedBinder = new GeneratedDomainClassBinder(dataSourceName, appClassLoader)
final GrailsDomainBinder domainBinder = new GrailsDomainBinder(
dataSourceName,
sessionFactoryBeanName,
@@ -368,15 +330,11 @@ class HibernateMappingContextConfiguration extends Configuration
addAnnotatedClasses(annotatedClasses.toArray(new Class[0]))
- ClassLoaderService classLoaderService = newClassLoaderService(
- generatedBinder != null ? generatedBinder.classLoader : appClassLoader, domainBinder, generatedBinder)
- if (generatedBinder != null) {
- // the mappings are bound against the generated classes; once they are bound, the same names resolve to the real ones
- GeneratedDomainClassLoaderService switching = new GeneratedDomainClassLoaderService(
- classLoaderService, new ClassLoaderServiceImpl(appClassLoader))
- generatedBinder.classLoaderService = switching
- classLoaderService = switching
- }
+ // the mappings are bound against the generated classes; once they are bound, the same names resolve to the real ones
+ GeneratedDomainClassLoaderService classLoaderService = new GeneratedDomainClassLoaderService(
+ newClassLoaderService(generatedBinder.classLoader, domainBinder, generatedBinder),
+ new ClassLoaderServiceImpl(appClassLoader))
+ generatedBinder.classLoaderService = classLoaderService
EventListenerIntegrator eventListenerIntegrator =
new EventListenerIntegrator(hibernateEventListeners, eventListeners)
BootstrapServiceRegistry bootstrapServiceRegistry = createBootstrapServiceRegistryBuilder()
@@ -388,10 +346,10 @@ class HibernateMappingContextConfiguration extends Configuration
StandardServiceRegistryBuilder standardServiceRegistryBuilder =
createStandardServiceRegistryBuilder(bootstrapServiceRegistry).applySettings((Map) properties)
- if (generatedBinder != null && !properties.containsKey(ENVERS_DO_NOT_AUDIT_OPTIMISTIC_LOCKING_FIELD)) {
- // Binder mode never marks the version as one for Envers, which therefore audits it as a plain property and the
- // audit tables of an existing application have the column. A generated entity carries a JPA @Version, which
- // Envers skips by default. A value the user sets always wins.
+ if (!properties.containsKey(ENVERS_DO_NOT_AUDIT_OPTIMISTIC_LOCKING_FIELD)) {
+ // The classic binding of Grails 8 never marked the version as one for Envers, which therefore audited it as a
+ // plain property, and the audit tables of an existing application have the column. A generated entity carries
+ // a JPA @Version, which Envers skips by default. A value the user sets always wins.
standardServiceRegistryBuilder.applySetting(ENVERS_DO_NOT_AUDIT_OPTIMISTIC_LOCKING_FIELD, FALSE_LITERAL)
}
@@ -439,7 +397,7 @@ class HibernateMappingContextConfiguration extends Configuration
}
// Hibernate asks for these once the metadata is complete; the generated-class binder points the bound
// entities at the real classes then
- if (generatedBinder != null && SessionFactoryBuilderFactory.isAssignableFrom(serviceContract)) {
+ if (SessionFactoryBuilderFactory.isAssignableFrom(serviceContract)) {
List<S> factories = new ArrayList<>(super.loadJavaServices(serviceContract))
factories.add((S) generatedBinder)
return factories
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/connections/HibernateConnectionSourceFactory.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/connections/HibernateConnectionSourceFactory.groovy
index 59eb9c08b6..44fa46808c 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/connections/HibernateConnectionSourceFactory.groovy
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/connections/HibernateConnectionSourceFactory.groovy
@@ -24,6 +24,8 @@ import org.hibernate.Interceptor
import org.hibernate.SessionFactory
import org.hibernate.boot.model.naming.PhysicalNamingStrategy
import org.hibernate.cfg.Configuration
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
import org.springframework.beans.BeanUtils
import org.springframework.beans.BeansException
import org.springframework.context.ApplicationContext
@@ -65,6 +67,19 @@ class HibernateConnectionSourceFactory
extends AbstractConnectionSourceFactory<SessionFactory, HibernateConnectionSourceSettings>
implements ApplicationContextAware, MessageSourceAware {
+ private static final Logger LOG = LoggerFactory.getLogger(HibernateConnectionSourceFactory)
+
+ /**
+ * The setting that selected the classic domain binding of Grails 8. It is no longer read: native domain binding is the
+ * only binding. An application that still sets it is told so once, at startup, and boots natively.
+ */
+ static final String GENERATED_DOMAIN_CLASSES_SETTING = 'hibernate.generatedDomainClasses'
+
+ static final String GENERATED_DOMAIN_CLASSES_SETTING_IGNORED =
+ 'The setting [%s] is no longer used: native domain binding is the only binding of GORM for Hibernate 7. ' +
+ 'Remove the setting. The Native Domain Binding chapter of the GORM for Hibernate 7 manual lists what changed ' +
+ 'from the classic binding of Grails 8.'
+
static {
// use Slf4j logging by default
System.setProperty('org.jboss.logging.provider', 'slf4j')
@@ -176,7 +191,6 @@ class HibernateConnectionSourceFactory
HibernateMappingContextConfiguration configuration = resolveConfiguration(hibernateSettings.configClass)
configuration.setBytecodeProvider(this.bytecodeProvider)
configuration.setDataSourceName(name)
- configuration.setGeneratedDomainClasses(hibernateSettings.generatedDomainClasses)
configuration.properties.put('jakarta.persistence.nonJtaDataSource', dataSourceConnectionSource.source)
if (applicationContext != null) {
configuration.setApplicationContext(applicationContext)
@@ -299,6 +313,7 @@ class HibernateConnectionSourceFactory
@Override
protected <F extends ConnectionSourceSettings> HibernateConnectionSourceSettings buildSettings(
String name, PropertyResolver configuration, F fallbackSettings, boolean isDefaultDataSource) {
+ warnAboutIgnoredSetting(configuration, isDefaultDataSource ? '' : "${Settings.SETTING_DATASOURCES}.${name}".toString())
if (isDefaultDataSource) {
String qualified = "${Settings.SETTING_DATASOURCES}.${Settings.SETTING_DATASOURCE}"
HibernateConnectionSourceSettings settings =
@@ -313,6 +328,16 @@ class HibernateConnectionSourceFactory
return buildSettingsWithPrefix(configuration, fallbackSettings, "${Settings.SETTING_DATASOURCES}.${name}")
}
+ /**
+ * Logs once per data source that the setting of Grails 8 selecting the classic domain binding is ignored.
+ */
+ private static void warnAboutIgnoredSetting(PropertyResolver configuration, String prefix) {
+ String key = prefix.isEmpty() ? GENERATED_DOMAIN_CLASSES_SETTING : "${prefix}.${GENERATED_DOMAIN_CLASSES_SETTING}".toString()
+ if (configuration.containsProperty(key)) {
+ LOG.warn(String.format(GENERATED_DOMAIN_CLASSES_SETTING_IGNORED, key))
+ }
+ }
+
private <F extends ConnectionSourceSettings> HibernateConnectionSourceSettings buildSettingsWithPrefix(
PropertyResolver configuration, F fallbackSettings, String prefix) {
DataSourceSettings dsFallback = extractDataSourceFallback(fallbackSettings)
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/connections/HibernateConnectionSourceSettings.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/connections/HibernateConnectionSourceSettings.groovy
index 4423755392..bdda449beb 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/connections/HibernateConnectionSourceSettings.groovy
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/connections/HibernateConnectionSourceSettings.groovy
@@ -90,15 +90,6 @@ class HibernateConnectionSourceSettings extends ConnectionSourceSettings {
*/
boolean hibernateDirtyChecking = false
- // the JVM-wide system property switches the default off to run an existing test suite through the classic domain binder; a configured value wins
- /**
- * Whether Hibernate's annotation binder binds classes generated from the GORM mapping (native domain binding),
- * instead of the classic domain binder building Hibernate's boot model by hand. The application's real domain
- * classes are still what is persisted and loaded. On by default. {@code false} selects the classic domain
- * binding, which is deprecated and will be removed.
- */
- boolean generatedDomainClasses = !Boolean.getBoolean('grails.hibernate.classicDomainBinding')
-
/**
* Cache settings
*/
diff --git a/grails-data-hibernate7/core/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/grails-data-hibernate7/core/src/main/resources/META-INF/additional-spring-configuration-metadata.json
index f8c04ecacf..904cdce1cc 100644
--- a/grails-data-hibernate7/core/src/main/resources/META-INF/additional-spring-configuration-metadata.json
+++ b/grails-data-hibernate7/core/src/main/resources/META-INF/additional-spring-configuration-metadata.json
@@ -31,8 +31,11 @@
{
"name": "hibernate.generatedDomainClasses",
"type": "java.lang.Boolean",
- "description": "Whether Hibernate's own annotation binder binds the domain classes (native domain binding). When false, GORM's classic domain binder builds the Hibernate mapping itself; classic domain binding is deprecated and will be removed. See Native Domain Binding in the GORM for Hibernate 7 manual.",
- "defaultValue": true
+ "description": "No longer used. Native domain binding (Hibernate's own annotation binder over classes generated from the GORM mapping) is the only binding; the classic domain binding of Grails 8 was removed. The setting is ignored with a warning at startup. See Native Domain Binding in the GORM for Hibernate 7 manual.",
+ "deprecation": {
+ "level": "error",
+ "reason": "The classic domain binding was removed; native domain binding is the only binding."
+ }
},
{
"name": "hibernate.grails.proxy.lazy_to_string",
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/HibernateGormDatastoreSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/HibernateGormDatastoreSpec.groovy
index 382f2257dd..a154d07667 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/HibernateGormDatastoreSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/HibernateGormDatastoreSpec.groovy
@@ -70,17 +70,6 @@ class HibernateGormDatastoreSpec extends GrailsDataTckSpec<GrailsDataHibernate7T
]
}
- /**
- * Registers the domain classes like {@code manager.registerDomainClasses(...)}, and boots the datastore through the
- * generated-domain-class path ({@code hibernate.generatedDomainClasses}) whatever mode the suite runs in: Hibernate's
- * annotation binder binds classes generated from the GORM mapping while sessions keep persisting and loading the real
- * domain classes. {@code registerDomainClasses} boots through the mode of the suite, native by default and the classic
- * domain binder with {@code -Pgrails.test.classicDomainBinding=true}.
- */
- void registerGeneratedDomainClasses(Class... classes) {
- manager.registerGeneratedDomainClasses(classes)
- }
-
void cleanup() {
// Each registry from getCollector() runs its own JDBC connection pool, whose validation
// thread keeps the registry and everything it references alive until it is destroyed.
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesAnnotatedClassesSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesAnnotatedClassesSpec.groovy
index bd86591f5c..20350f8919 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesAnnotatedClassesSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesAnnotatedClassesSpec.groovy
@@ -37,11 +37,10 @@ class GeneratedDomainClassesAnnotatedClassesSpec extends Specification {
@AutoCleanup
HibernateDatastore datastore = new HibernateDatastore(
DatastoreUtils.createPropertyResolver([
- 'hibernate.generatedDomainClasses': true,
- 'hibernate.annotatedClasses' : [GdcAnnotatedThing],
- 'dataSource.url' : 'jdbc:h2:mem:gdcAnnotatedClasses;LOCK_TIMEOUT=10000',
- 'dataSource.dbCreate' : 'create-drop',
- 'hibernate.hbm2ddl.auto' : 'create-drop',
+ 'hibernate.annotatedClasses': [GdcAnnotatedThing],
+ 'dataSource.url' : 'jdbc:h2:mem:gdcAnnotatedClasses;LOCK_TIMEOUT=10000',
+ 'dataSource.dbCreate' : 'create-drop',
+ 'hibernate.hbm2ddl.auto' : 'create-drop',
]),
GdcConstructorThing)
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesBootSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesBootSpec.groovy
index 6956b230e1..00dcbdba23 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesBootSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesBootSpec.groovy
@@ -26,17 +26,16 @@ import org.grails.datastore.mapping.core.DatastoreUtils
import org.grails.orm.hibernate.HibernateDatastore
/**
- * What boots through the generated classes (an entity with a composite identifier), with the setting stated and with the defaults.
+ * What boots through the generated classes (an entity with a composite identifier), with a data source stated and with the defaults.
*/
class GeneratedDomainClassesBootSpec extends Specification {
- def "a composite identifier boots through the generated classes, and the entity has no identifier property of its own"() {
+ def "a composite identifier boots, and the entity has no identifier property of its own"() {
when:
HibernateDatastore datastore = new HibernateDatastore(
DatastoreUtils.createPropertyResolver([
- 'dataSource.url' : 'jdbc:h2:mem:gdcBoot;LOCK_TIMEOUT=10000',
- 'dataSource.dbCreate' : 'create-drop',
- 'hibernate.generatedDomainClasses': true,
+ 'dataSource.url' : 'jdbc:h2:mem:gdcBoot;LOCK_TIMEOUT=10000',
+ 'dataSource.dbCreate': 'create-drop',
]), GdcComposite)
EntityPersister persister = datastore.sessionFactory.mappingMetamodel.getEntityDescriptor(GdcComposite)
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCompositeIdSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCompositeIdSpec.groovy
index fa7a87259c..dc9de8de69 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCompositeIdSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCompositeIdSpec.groovy
@@ -35,7 +35,7 @@ import org.hibernate.persister.entity.EntityPersister
class GeneratedDomainClassesCompositeIdSpec extends HibernateGormDatastoreSpec {
void setupSpec() {
- registerGeneratedDomainClasses(
+ manager.registerDomainClasses(
GdcCidItem, GdcCidSpecial, GdcCidOwner, GdcCidPart, GdcCidRef, GdcCidBox, GdcCidThing, GdcCidSequenced)
}
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesConverterSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesConverterSpec.groovy
index 7f13c4d7ed..654ced9595 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesConverterSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesConverterSpec.groovy
@@ -29,7 +29,7 @@ import grails.persistence.Entity
class GeneratedDomainClassesConverterSpec extends HibernateGormDatastoreSpec {
void setupSpec() {
- registerGeneratedDomainClasses(GdcConverted)
+ manager.registerDomainClasses(GdcConverted)
}
def "the converted columns hold the converted values and the properties read back"() {
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesDdlSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesDdlSpec.groovy
index 4f35fb6063..e87dbf377a 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesDdlSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesDdlSpec.groovy
@@ -34,7 +34,7 @@ import org.hibernate.mapping.RootClass
class GeneratedDomainClassesDdlSpec extends HibernateGormDatastoreSpec {
void setupSpec() {
- registerGeneratedDomainClasses(GddVehicle, GddCar, GddTruck, GddStudent, GddSchool, GddTeacher, GddBadge, GddToken, GddMember, GddAccount, GddPair, GddEdition, GddImprint, GddSequenced)
+ manager.registerDomainClasses(GddVehicle, GddCar, GddTruck, GddStudent, GddSchool, GddTeacher, GddBadge, GddToken, GddMember, GddAccount, GddPair, GddEdition, GddImprint, GddSequenced)
}
private List<String> checkClauses(String table) {
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesExtraLazySpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesExtraLazySpec.groovy
index 06e87a6707..eb12d8cd90 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesExtraLazySpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesExtraLazySpec.groovy
@@ -31,7 +31,7 @@ import org.hibernate.persister.collection.CollectionPersister
class GeneratedDomainClassesExtraLazySpec extends HibernateGormDatastoreSpec {
void setupSpec() {
- registerGeneratedDomainClasses(GdcLazyOwner, GdcLazyItem, GdcLazyTagged, GdcPlainOwner)
+ manager.registerDomainClasses(GdcLazyOwner, GdcLazyItem, GdcLazyTagged, GdcPlainOwner)
}
private static CollectionPersister persister(def sessionFactory, Class owner, String property) {
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesLazyEmbeddedSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesLazyEmbeddedSpec.groovy
index e723f88e29..da9d8ea7a1 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesLazyEmbeddedSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesLazyEmbeddedSpec.groovy
@@ -30,7 +30,7 @@ import org.hibernate.mapping.PersistentClass
class GeneratedDomainClassesLazyEmbeddedSpec extends HibernateGormDatastoreSpec {
void setupSpec() {
- registerGeneratedDomainClasses(GdcLazyHome, GdcPlainHome)
+ manager.registerDomainClasses(GdcLazyHome, GdcPlainHome)
}
def "an embedded property mapped lazy is a lazy property of the bound entity, one mapped by default is not"() {
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesQuerySpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesQuerySpec.groovy
index d0bc8d7067..13425a7535 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesQuerySpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesQuerySpec.groovy
@@ -29,7 +29,7 @@ import org.apache.grails.data.testing.tck.domains.Person
class GeneratedDomainClassesQuerySpec extends HibernateQuerySpec {
void setupSpec() {
- registerGeneratedDomainClasses()
+ manager.registerDomainClasses()
}
def "the inherited features run against the generated mapping"() {
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesSpec.groovy
index 240c08819b..91261c09c0 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesSpec.groovy
@@ -36,7 +36,7 @@ import org.hibernate.persister.entity.EntityPersister
class GeneratedDomainClassesSpec extends HibernateGormDatastoreSpec {
void setupSpec() {
- registerGeneratedDomainClasses(GdcAuthor, GdcBook, GdcNovel)
+ manager.registerDomainClasses(GdcAuthor, GdcBook, GdcNovel)
}
private GdcBook savedBook(String title = 'Dune', GdcAuthor author = new GdcAuthor(name: 'Herbert').save(flush: true)) {
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesWidenedSpecs.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesWidenedSpecs.groovy
deleted file mode 100644
index affcc3f150..0000000000
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesWidenedSpecs.groovy
+++ /dev/null
@@ -1,779 +0,0 @@
-/*
- * 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 grails.gorm.tests.AddToManagedEntitySpec
-import grails.gorm.tests.AutoTimestampSpec
-import grails.gorm.tests.CascadeToBidirectionalAsssociationSpec
-import grails.gorm.tests.CountByWithEmbeddedSpec
-import grails.gorm.tests.EnumMappingSpec
-import grails.gorm.tests.FetchJoinSpec
-import grails.gorm.tests.Hibernate7OptimisticLockingSpec
-import grails.gorm.tests.HibernateGetAllConvertibleIdSpec
-import grails.gorm.tests.HibernateValidationSpec
-import grails.gorm.tests.Issue16349Spec
-import grails.gorm.tests.LastUpdateWithDynamicUpdateSpec
-import grails.gorm.tests.ManagedEntitySaveSpec
-import grails.gorm.tests.ManyToOneSpec
-import grails.gorm.tests.MultiColumnUniqueConstraintSpec
-import grails.gorm.tests.PagedResultListSpec
-import grails.gorm.tests.RLikeSpec
-import grails.gorm.tests.ReadOperationSpec
-import grails.gorm.tests.SizeConstraintSpec
-import grails.gorm.tests.SortArgumentValidationSpec
-import grails.gorm.tests.TablePerSubClassAndEmbeddedSpec
-import grails.gorm.tests.ToOneProxySpec
-import grails.gorm.tests.WhereQueryWithAssociationSortSpec
-import grails.gorm.tests.autoimport.AutoImportSpec
-import grails.gorm.tests.belongsto.BidirectionalOneToOneWithUniqueSpec
-import grails.gorm.tests.detachedcriteria.DetachCriteriaSubquerySpec
-import grails.gorm.tests.detachedcriteria.DetachedCriteriaCountSpec
-import grails.gorm.tests.detachedcriteria.DetachedCriteriaJoinSpec
-import grails.gorm.tests.detachedcriteria.DetachedCriteriaProjectionSpec
-import grails.gorm.tests.dirtychecking.DirtyCheckingSpecHibernate7
-import grails.gorm.tests.dirtychecking.HibernateDirtyCheckingSpec
-import grails.gorm.tests.hasmany.ListCollectionSpec
-import grails.gorm.tests.hasmany.TwoUnidirectionalHasManySpec
-import grails.gorm.tests.hibernatequery.HibernateAssociationQuerySpec
-import grails.gorm.tests.inheritance.IntermediateSubclassQuerySpec
-import grails.gorm.tests.inheritance.SubclassToOneProxySpec
-import grails.gorm.tests.inheritance.TablePerConcreteClassAndDateCreatedSpec
-import grails.gorm.tests.inheritance.TablePerConcreteClassImportedSpec
-import grails.gorm.tests.mappedby.MultipleOneToOneSpec
-import grails.gorm.tests.proxy.ByteBuddyProxySpec
-import grails.gorm.tests.proxy.Hibernate7GroovyProxySpec
-import grails.gorm.tests.traits.InterfacePropertySpec
-import grails.gorm.tests.validation.BeanValidationSpec
-import grails.gorm.tests.validation.DeepValidationSpec
-import grails.gorm.tests.validation.UniqueWithHasOneSpec
-import org.apache.grails.data.testing.tck.tests.AttachMethodSpec
-import org.apache.grails.data.testing.tck.tests.CircularOneToManySpec
-import org.apache.grails.data.testing.tck.tests.CommonTypesPersistenceSpec
-import org.apache.grails.data.testing.tck.tests.ConstraintsSpec
-import org.apache.grails.data.testing.tck.tests.CriteriaBuilderSpec
-import org.apache.grails.data.testing.tck.tests.CrudOperationsSpec
-import org.apache.grails.data.testing.tck.tests.DeleteAllSpec
-import org.apache.grails.data.testing.tck.tests.DetachedCriteriaSpec
-import org.apache.grails.data.testing.tck.tests.DirtyCheckingSpec
-import org.apache.grails.data.testing.tck.tests.DisableAutotimeStampSpec
-import org.apache.grails.data.testing.tck.tests.DomainEventsSpec
-import org.apache.grails.data.testing.tck.tests.EnumSpec
-import org.apache.grails.data.testing.tck.tests.FindByExampleSpec
-import org.apache.grails.data.testing.tck.tests.FindByMethodSpec
-import org.apache.grails.data.testing.tck.tests.FindOrCreateWhereSpec
-import org.apache.grails.data.testing.tck.tests.FindOrSaveWhereSpec
-import org.apache.grails.data.testing.tck.tests.FindWhereSpec
-import org.apache.grails.data.testing.tck.tests.FirstAndLastMethodSpec
-import org.apache.grails.data.testing.tck.tests.GormEnhancerSpec
-import org.apache.grails.data.testing.tck.tests.GormValidateableSpec
-import org.apache.grails.data.testing.tck.tests.InheritanceSpec
-import org.apache.grails.data.testing.tck.tests.ListOrderBySpec
-import org.apache.grails.data.testing.tck.tests.NegationSpec
-import org.apache.grails.data.testing.tck.tests.NotInListSpec
-import org.apache.grails.data.testing.tck.tests.NullValueEqualSpec
-import org.apache.grails.data.testing.tck.tests.OneToManySpec
-import org.apache.grails.data.testing.tck.tests.OneToOneSpec
-import org.apache.grails.data.testing.tck.tests.OptimisticLockingSpec
-import org.apache.grails.data.testing.tck.tests.OrderBySpec
-import org.apache.grails.data.testing.tck.tests.PagedResultSpec
-import org.apache.grails.data.testing.tck.tests.PersistenceEventListenerSpec
-import org.apache.grails.data.testing.tck.tests.ProxyInitializationSpec
-import org.apache.grails.data.testing.tck.tests.ProxyLoadingSpec
-import org.apache.grails.data.testing.tck.tests.QueryAfterPropertyChangeSpec
-import org.apache.grails.data.testing.tck.tests.QueryByAssociationSpec
-import org.apache.grails.data.testing.tck.tests.QueryByNullSpec
-import org.apache.grails.data.testing.tck.tests.QueryEventsSpec
-import org.apache.grails.data.testing.tck.tests.RangeQuerySpec
-import org.apache.grails.data.testing.tck.tests.SaveAllSpec
-import org.apache.grails.data.testing.tck.tests.SessionPropertiesSpec
-import org.apache.grails.data.testing.tck.tests.SizeQuerySpec
-import org.apache.grails.data.testing.tck.tests.StaticCompiledCriteriaSpec
-import org.apache.grails.data.testing.tck.tests.UniqueConstraintSpec
-import org.apache.grails.data.testing.tck.tests.UpdateWithProxyPresentSpec
-import org.apache.grails.data.testing.tck.tests.ValidationSpec
-import org.apache.grails.data.testing.tck.tests.WhereLazySpec
-import org.apache.grails.data.testing.tck.tests.WhereQueryEmbeddedSpec
-import org.apache.grails.data.testing.tck.tests.WhereQueryIssueVerificationSpec
-import org.apache.grails.data.testing.tck.tests.WhereQueryLeftJoinSpec
-import org.apache.grails.data.testing.tck.tests.WithTransactionSpec
-
-/**
- * Existing specs of the module and of the TCK run unchanged against a datastore booted through the generated-domain-class
- * path: each subclass inherits every feature of its parent and only switches the harness to
- * {@code registerGeneratedDomainClasses}. The domain classes the parent registered are the ones that are generated.
- */
-
-class GeneratedAddToManagedEntitySpec extends AddToManagedEntitySpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedAutoTimestampSpec extends AutoTimestampSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedCascadeToBidirectionalAsssociationSpec extends CascadeToBidirectionalAsssociationSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedCountByWithEmbeddedSpec extends CountByWithEmbeddedSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedEnumMappingSpec extends EnumMappingSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedFetchJoinSpec extends FetchJoinSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedHibernate7OptimisticLockingSpec extends Hibernate7OptimisticLockingSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedHibernateValidationSpec extends HibernateValidationSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedLastUpdateWithDynamicUpdateSpec extends LastUpdateWithDynamicUpdateSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedManagedEntitySaveSpec extends ManagedEntitySaveSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedManyToOneSpec extends ManyToOneSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedReadOperationSpec extends ReadOperationSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedTablePerSubClassAndEmbeddedSpec extends TablePerSubClassAndEmbeddedSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedToOneProxySpec extends ToOneProxySpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedDetachCriteriaSubquerySpec extends DetachCriteriaSubquerySpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedDetachedCriteriaCountSpec extends DetachedCriteriaCountSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedDetachedCriteriaJoinSpec extends DetachedCriteriaJoinSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedDetachedCriteriaProjectionSpec extends DetachedCriteriaProjectionSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedDirtyCheckingSpecHibernate7 extends DirtyCheckingSpecHibernate7 {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedHibernateDirtyCheckingSpec extends HibernateDirtyCheckingSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedListCollectionSpec extends ListCollectionSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedIntermediateSubclassQuerySpec extends IntermediateSubclassQuerySpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedSubclassToOneProxySpec extends SubclassToOneProxySpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedByteBuddyProxySpec extends ByteBuddyProxySpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedHibernate7GroovyProxySpec extends Hibernate7GroovyProxySpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedAttachMethodSpec extends AttachMethodSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedCircularOneToManySpec extends CircularOneToManySpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedCommonTypesPersistenceSpec extends CommonTypesPersistenceSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedCriteriaBuilderSpec extends CriteriaBuilderSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedCrudOperationsSpec extends CrudOperationsSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedDeleteAllSpec extends DeleteAllSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedDetachedCriteriaSpec extends DetachedCriteriaSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedDirtyCheckingSpec extends DirtyCheckingSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedDomainEventsSpec extends DomainEventsSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedEnumSpec extends EnumSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedFindByExampleSpec extends FindByExampleSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedFindByMethodSpec extends FindByMethodSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedFindWhereSpec extends FindWhereSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedInheritanceSpec extends InheritanceSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedListOrderBySpec extends ListOrderBySpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedNegationSpec extends NegationSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedNotInListSpec extends NotInListSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedOneToManySpec extends OneToManySpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedOneToOneSpec extends OneToOneSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedOrderBySpec extends OrderBySpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedPagedResultSpec extends PagedResultSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedPersistenceEventListenerSpec extends PersistenceEventListenerSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedProxyInitializationSpec extends ProxyInitializationSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedProxyLoadingSpec extends ProxyLoadingSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedQueryAfterPropertyChangeSpec extends QueryAfterPropertyChangeSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedQueryByAssociationSpec extends QueryByAssociationSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedQueryByNullSpec extends QueryByNullSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedRangeQuerySpec extends RangeQuerySpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedSaveAllSpec extends SaveAllSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedUpdateWithProxyPresentSpec extends UpdateWithProxyPresentSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedValidationSpec extends ValidationSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedWhereLazySpec extends WhereLazySpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedWithTransactionSpec extends WithTransactionSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedHibernateGetAllConvertibleIdSpec extends HibernateGetAllConvertibleIdSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-
-class GeneratedMultiColumnUniqueConstraintSpec extends MultiColumnUniqueConstraintSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedPagedResultListSpec extends PagedResultListSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedRLikeSpec extends RLikeSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedSizeConstraintSpec extends SizeConstraintSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedSortArgumentValidationSpec extends SortArgumentValidationSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedWhereQueryWithAssociationSortSpec extends WhereQueryWithAssociationSortSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedAutoImportSpec extends AutoImportSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedBidirectionalOneToOneWithUniqueSpec extends BidirectionalOneToOneWithUniqueSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedTwoUnidirectionalHasManySpec extends TwoUnidirectionalHasManySpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedHibernateAssociationQuerySpec extends HibernateAssociationQuerySpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedTablePerConcreteClassAndDateCreatedSpec extends TablePerConcreteClassAndDateCreatedSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedTablePerConcreteClassImportedSpec extends TablePerConcreteClassImportedSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedMultipleOneToOneSpec extends MultipleOneToOneSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedInterfacePropertySpec extends InterfacePropertySpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedBeanValidationSpec extends BeanValidationSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedDeepValidationSpec extends DeepValidationSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedUniqueWithHasOneSpec extends UniqueWithHasOneSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedConstraintsSpec extends ConstraintsSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedDisableAutotimeStampSpec extends DisableAutotimeStampSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedFindOrCreateWhereSpec extends FindOrCreateWhereSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedFindOrSaveWhereSpec extends FindOrSaveWhereSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedFirstAndLastMethodSpec extends FirstAndLastMethodSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedGormEnhancerSpec extends GormEnhancerSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedGormValidateableSpec extends GormValidateableSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedNullValueEqualSpec extends NullValueEqualSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedOptimisticLockingSpec extends OptimisticLockingSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedQueryEventsSpec extends QueryEventsSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedSessionPropertiesSpec extends SessionPropertiesSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedSizeQuerySpec extends SizeQuerySpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedStaticCompiledCriteriaSpec extends StaticCompiledCriteriaSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedUniqueConstraintSpec extends UniqueConstraintSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedWhereQueryEmbeddedSpec extends WhereQueryEmbeddedSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedWhereQueryIssueVerificationSpec extends WhereQueryIssueVerificationSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedWhereQueryLeftJoinSpec extends WhereQueryLeftJoinSpec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
-
-class GeneratedIssue16349Spec extends Issue16349Spec {
-
- void setupSpec() {
- manager.registerGeneratedDomainClasses()
- }
-}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/apache/grails/data/hibernate7/core/GrailsDataHibernate7TckManager.groovy b/grails-data-hibernate7/core/src/test/groovy/org/apache/grails/data/hibernate7/core/GrailsDataHibernate7TckManager.groovy
index 6edf0bda0c..676afe0931 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/apache/grails/data/hibernate7/core/GrailsDataHibernate7TckManager.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/apache/grails/data/hibernate7/core/GrailsDataHibernate7TckManager.groovy
@@ -56,29 +56,6 @@ class GrailsDataHibernate7TckManager extends GrailsDataTckManager {
ConfigObject grailsConfig = new ConfigObject()
boolean isTransactional = true
- /**
- * System property that boots every datastore through the classic domain binder
- * ({@code hibernate.generatedDomainClasses: false}). Native domain binding is the default; the Gradle property
- * {@code -Pgrails.test.classicDomainBinding=true} sets this property on the test JVM, which runs the whole module suite
- * in classic mode. The datastores this manager builds read it, and so does the default of
- * {@code HibernateConnectionSourceSettings}, which covers the specs that build their own {@code HibernateDatastore}
- * without setting {@code hibernate.generatedDomainClasses} themselves.
- */
- static final String CLASSIC_MODE_PROPERTY = 'grails.hibernate.classicDomainBinding'
-
- boolean generatedDomainClasses = !Boolean.getBoolean(CLASSIC_MODE_PROPERTY)
-
- /**
- * Registers the classes like {@link #registerDomainClasses} and boots the datastore through the generated-domain-class
- * path whatever mode the suite runs in: Hibernate's annotation binder binds classes generated from the GORM mapping,
- * and the real domain classes are what sessions persist and load. {@code registerDomainClasses} boots through the
- * mode of the suite: native by default, the classic domain binder with {@link #CLASSIC_MODE_PROPERTY}.
- */
- void registerGeneratedDomainClasses(Class... classes) {
- generatedDomainClasses = true
- registerDomainClasses(classes)
- }
-
@Override
void setup(Class<? extends Specification> spec) {
cleanRegistry()
@@ -90,7 +67,6 @@ class GrailsDataHibernate7TckManager extends GrailsDataTckManager {
grailsApplication = new DefaultGrailsApplication(domainClasses as Class[], new GroovyClassLoader(GrailsDataHibernate7TckManager.getClassLoader()))
grailsConfig.dataSource.dbCreate = "create-drop"
grailsConfig.hibernate.proxy_factory_class = "org.grails.orm.hibernate.proxy.ByteBuddyGroovyProxyFactory"
- grailsConfig.hibernate.generatedDomainClasses = generatedDomainClasses
grailsConfig.'grails.gorm.default.mapping' = {
id generator: 'identity'
}
@@ -178,7 +154,6 @@ class GrailsDataHibernate7TckManager extends GrailsDataTckManager {
'hibernate.cache.queries' : 'true',
'hibernate.hbm2ddl.auto' : 'create-drop',
'hibernate.proxy_factory_class' : 'org.grails.orm.hibernate.proxy.ByteBuddyGroovyProxyFactory',
- 'hibernate.generatedDomainClasses' : generatedDomainClasses,
'grails.gorm.default.mapping' : {
id generator: 'identity'
},
@@ -224,7 +199,6 @@ class GrailsDataHibernate7TckManager extends GrailsDataTckManager {
'hibernate.cache.queries' : 'true',
'hibernate.hbm2ddl.auto' : 'create-drop',
'hibernate.proxy_factory_class' : 'org.grails.orm.hibernate.proxy.ByteBuddyGroovyProxyFactory',
- 'hibernate.generatedDomainClasses' : generatedDomainClasses,
'grails.gorm.default.mapping' : {
id generator: 'identity'
},
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/UserTypeMappingSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/UserTypeMappingSpec.groovy
index 92b68c1cf8..f0534d9ba5 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/UserTypeMappingSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/UserTypeMappingSpec.groovy
@@ -131,7 +131,7 @@ class UserTypeMappingSpec extends Specification {
private static String typeNameOf(HibernateDatastore datastore, Class entity) {
SimpleValue value = datastore.metadata.getEntityBinding(entity.name).getProperty('active').value as SimpleValue
- // the domain binder states the type by name, Hibernate's annotation binder (hibernate.generatedDomainClasses) by the type it resolves
+ // Hibernate's annotation binder states the type it resolves, not a name (the classic binder of Grails 8 stated the name)
value.typeName ?: resolvedTypeName(value.type)
}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/ClassicDomainBindingDeprecationSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/GeneratedDomainClassesSettingSpec.groovy
similarity index 55%
rename from grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/ClassicDomainBindingDeprecationSpec.groovy
rename to grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/GeneratedDomainClassesSettingSpec.groovy
index 9029f3059d..2b3057b14a 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/ClassicDomainBindingDeprecationSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/GeneratedDomainClassesSettingSpec.groovy
@@ -28,16 +28,16 @@ import spock.lang.Specification
import java.nio.charset.StandardCharsets
/**
- * Native domain binding is the default. An application that still selects the classic domain binder with
- * {@code hibernate.generatedDomainClasses: false} boots, and is told once per data source, at startup, that the classic
- * binding is deprecated and will be removed. The test JVM logs through slf4j-simple, which writes to {@code System.err},
- * so the warning is read from there. The entity is an existing fixture, so the scanned entity set of the differential
- * specs is unchanged.
+ * Native domain binding is the only binding. An application upgraded from Grails 8 that still sets
+ * {@code hibernate.generatedDomainClasses}, with either value, boots natively and is told once per data source, at startup,
+ * that the setting is no longer used. The test JVM logs through slf4j-simple, which writes to {@code System.err}, so the
+ * warning is read from there. The entity is an existing fixture, so the scanned entity set of the differential specs is
+ * unchanged.
*/
-class ClassicDomainBindingDeprecationSpec extends Specification {
+class GeneratedDomainClassesSettingSpec extends Specification {
- private static final String WARNING = 'Classic domain binding is deprecated and will be removed: ' +
- 'hibernate.generatedDomainClasses is false for data source [default]'
+ private static final String WARNING = 'The setting [hibernate.generatedDomainClasses] is no longer used: ' +
+ 'native domain binding is the only binding of GORM for Hibernate 7'
@AutoCleanup
HibernateDatastore datastore
@@ -48,7 +48,7 @@ class ClassicDomainBindingDeprecationSpec extends Specification {
System.setErr(new PrintStream(captured, true, StandardCharsets.UTF_8.name()))
try {
datastore = new HibernateDatastore(DatastoreUtils.createPropertyResolver([
- 'dataSource.url' : "jdbc:h2:mem:classicDeprecation${System.nanoTime()};LOCK_TIMEOUT=10000".toString(),
+ 'dataSource.url' : "jdbc:h2:mem:generatedSetting${System.nanoTime()};LOCK_TIMEOUT=10000".toString(),
'dataSource.dbCreate' : 'create-drop',
'dataSource.dialect' : H2Dialect.name,
'hibernate.hbm2ddl.auto' : 'create-drop',
@@ -61,40 +61,48 @@ class ClassicDomainBindingDeprecationSpec extends Specification {
return captured.toString(StandardCharsets.UTF_8.name())
}
- void "selecting the classic domain binder logs that it is deprecated and will be removed"() {
- when:
- String log = bootAndCaptureLog(['hibernate.generatedDomainClasses': false])
-
- then: 'the warning names the setting and the data source, and the application still works'
- log.contains('WARN')
- log.contains(WARNING)
- log.contains('remove the setting, or set it to true')
- DomainOne.withTransaction {
- new DomainOne(controller: 'book', action: 'classic').save(flush: true, failOnError: true)
+ private static boolean persists() {
+ return DomainOne.withTransaction {
+ new DomainOne(controller: 'book', action: 'native').save(flush: true, failOnError: true)
DomainOne.count() == 1
}
}
- void "the default, native domain binding, starts without the warning"() {
- given: 'the suite may run through the classic binder as a whole, which makes the classic binder the default'
- boolean classicSuite = Boolean.getBoolean('grails.hibernate.classicDomainBinding')
+ void "a setting that selected the classic binding (#value) is ignored with one warning, and the application boots natively"() {
+ when:
+ String log = bootAndCaptureLog(['hibernate.generatedDomainClasses': value])
+ then: 'the warning names the setting and says what to do, once'
+ log.contains('WARN')
+ log.count(WARNING) == 1
+ log.contains('Remove the setting')
+
+ and: 'the entity is bound under its own name and works'
+ datastore.sessionFactory.mappingMetamodel.getEntityDescriptor(DomainOne).entityName == DomainOne.name
+ persists()
+
+ where:
+ value << [false, true, 'false']
+ }
+
+ void "the setting of a named data source is reported with its own key"() {
when:
- String log = bootAndCaptureLog([:])
+ String log = bootAndCaptureLog([
+ 'dataSources.second.url' : "jdbc:h2:mem:generatedSettingSecond${System.nanoTime()};LOCK_TIMEOUT=10000".toString(),
+ 'dataSources.second.hibernate.generatedDomainClasses': false,
+ ])
then:
- log.contains(WARNING) == classicSuite
- DomainOne.withTransaction {
- new DomainOne(controller: 'book', action: 'native').save(flush: true, failOnError: true)
- DomainOne.count() == 1
- }
+ log.contains('The setting [dataSources.second.hibernate.generatedDomainClasses] is no longer used')
+ !log.contains(WARNING)
}
- void "selecting native domain binding explicitly starts without the warning"() {
+ void "an application that does not set it starts without the warning"() {
when:
- String log = bootAndCaptureLog(['hibernate.generatedDomainClasses': true])
+ String log = bootAndCaptureLog([:])
then:
- !log.contains(WARNING)
+ !log.contains('no longer used')
+ persists()
}
}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/HibernateMappingContextConfigurationSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/HibernateMappingContextConfigurationSpec.groovy
index 7dc855dd61..a827caefa5 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/HibernateMappingContextConfigurationSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/HibernateMappingContextConfigurationSpec.groovy
@@ -49,18 +49,9 @@ class HibernateMappingContextConfigurationSpec extends Specification {
config.dataSourceName == 'default'
}
- def "native domain binding is on by default and the classic domain binder can be selected"() {
- given:
- def config = new HibernateMappingContextConfiguration()
-
+ def "the configuration has no switch of the domain binding"() {
expect:
- config.generatedDomainClasses
-
- when:
- config.setGeneratedDomainClasses(false)
-
- then:
- !config.generatedDomainClasses
+ !new HibernateMappingContextConfiguration().hasProperty('generatedDomainClasses')
}
def "setBytecodeProvider stores the provider and getGrailsBytecodeProvider returns it"() {
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/connections/HibernateConnectionSourceSettingsSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/connections/HibernateConnectionSourceSettingsSpec.groovy
index 576e6f50cc..f729b7594b 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/connections/HibernateConnectionSourceSettingsSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/connections/HibernateConnectionSourceSettingsSpec.groovy
@@ -119,82 +119,18 @@ class HibernateConnectionSourceSettingsSpec extends Specification {
listeners['create-onflush'].is(onFlushListener)
}
- void "native domain binding is on by default and the classic domain binder can be selected"() {
- given:
- String property = 'grails.hibernate.classicDomainBinding'
- String previous = System.clearProperty(property)
-
- when:
- def settings = new HibernateConnectionSourceSettings()
-
- then:
- settings.hibernate.generatedDomainClasses
-
- when:
- settings.hibernate.generatedDomainClasses = false
-
- then:
- !settings.hibernate.generatedDomainClasses
-
- cleanup:
- if (previous != null) {
- System.setProperty(property, previous)
- }
- }
-
- void "a configured hibernate.generatedDomainClasses value is what the built settings hold"() {
- given:
- String property = 'grails.hibernate.classicDomainBinding'
- String previous = System.clearProperty(property)
-
+ void "the settings have no switch of the domain binding: hibernate.generatedDomainClasses is not a setting and is ignored when configured"() {
when:
HibernateConnectionSourceSettings settings = new HibernateConnectionSourceSettingsBuilder(
- DatastoreUtils.createPropertyResolver(['hibernate.generatedDomainClasses': configured])).build()
+ DatastoreUtils.createPropertyResolver(['hibernate.generatedDomainClasses': false, 'hibernate.flush.mode': 'commit'])).build()
then:
- settings.hibernate.generatedDomainClasses == expected
-
- cleanup:
- if (previous != null) {
- System.setProperty(property, previous)
- }
-
- where:
- configured | expected
- false | false
- 'false' | false
- true | true
+ !settings.hibernate.hasProperty('generatedDomainClasses')
+ settings.hibernate.flush.mode.toString() == 'COMMIT'
}
- void "the JVM-wide system property switches the default to the classic domain binder, and a configured value wins"() {
- given:
- String property = 'grails.hibernate.classicDomainBinding'
- String previous = System.getProperty(property)
- System.setProperty(property, 'true')
-
- when:
- def settings = new HibernateConnectionSourceSettings()
-
- then:
- !settings.hibernate.generatedDomainClasses
-
- when:
- settings.hibernate.generatedDomainClasses = true
-
- then:
- settings.hibernate.generatedDomainClasses
-
- cleanup:
- if (previous == null) {
- System.clearProperty(property)
- } else {
- System.setProperty(property, previous)
- }
- }
-
- void "the published configuration metadata states the default of hibernate.generatedDomainClasses"() {
+ void "the published configuration metadata lists hibernate.generatedDomainClasses as removed, so an IDE flags it"() {
given: 'the metadata an IDE shows for the key'
- String previous = System.clearProperty('grails.hibernate.classicDomainBinding')
URL metadata = HibernateConnectionSourceSettings.getResource('/META-INF/additional-spring-configuration-metadata.json')
Map property = ((List<Map>) ((Map) new JsonSlurper().parse(metadata)).get('properties')).find {
it.get('name') == 'hibernate.generatedDomainClasses'
@@ -202,13 +138,9 @@ class HibernateConnectionSourceSettingsSpec extends Specification {
expect:
property != null
- property.get('defaultValue') == new HibernateConnectionSourceSettings().hibernate.generatedDomainClasses
- (property.get('description') as String).contains('deprecated')
-
- cleanup:
- if (previous != null) {
- System.setProperty('grails.hibernate.classicDomainBinding', previous)
- }
+ !property.containsKey('defaultValue')
+ ((Map) property.get('deprecation')).get('level') == 'error'
+ (property.get('description') as String).contains('No longer used')
}
void "test toProperties with dirty checking and custom config"() {
diff --git a/grails-data-hibernate7/dbmigration/src/test/groovy/org/grails/plugins/databasemigration/generated/GeneratedModeEnversSpec.groovy b/grails-data-hibernate7/dbmigration/src/test/groovy/org/grails/plugins/databasemigration/generated/GeneratedModeEnversSpec.groovy
index d7810c12af..bebbc6c6ab 100644
--- a/grails-data-hibernate7/dbmigration/src/test/groovy/org/grails/plugins/databasemigration/generated/GeneratedModeEnversSpec.groovy
+++ b/grails-data-hibernate7/dbmigration/src/test/groovy/org/grails/plugins/databasemigration/generated/GeneratedModeEnversSpec.groovy
@@ -30,7 +30,6 @@ import org.hibernate.envers.NotAudited
import org.hibernate.envers.RevisionType
import org.hibernate.mapping.Table
import spock.lang.AutoCleanup
-import spock.lang.PendingFeature
import spock.lang.Specification
import org.grails.orm.hibernate.HibernateDatastore
@@ -39,23 +38,22 @@ import org.grails.orm.hibernate.HibernateDatastore
* Hibernate Envers over the generated domain classes. Envers builds its audit mappings from the entities bound when its
* contributor runs, reading the annotations of the bound classes, so the generated classes are bound before it and carry
* the Envers annotations of the domain classes. The audit tables, the revisions and the instances the audit queries return
- * are those of binder mode, with the differences that are named in the features below.
+ * are those the classic binding of Grails 8 gave, with the differences that are named in the features below.
*/
class GeneratedModeEnversSpec extends Specification {
@AutoCleanup
HibernateDatastore datastore
- private HibernateDatastore boot(boolean generated, List<Class> classes, Map extra = [:]) {
+ private HibernateDatastore boot(List<Class> classes, Map extra = [:]) {
datastore?.close()
datastore = new HibernateDatastore([
- 'dataSource.url' : "jdbc:h2:mem:enversSpec${generated}${System.nanoTime()};LOCK_TIMEOUT=10000;DB_CLOSE_DELAY=-1".toString(),
- 'dataSource.dialect' : H2Dialect.name,
- 'dataSource.dbCreate' : 'create-drop',
- 'hibernate.hbm2ddl.auto' : 'create',
- 'hibernate.cache.queries' : 'false',
- 'hibernate.cache.use_query_cache' : 'false',
- 'hibernate.generatedDomainClasses': generated,
+ 'dataSource.url' : "jdbc:h2:mem:enversSpec${System.nanoTime()};LOCK_TIMEOUT=10000;DB_CLOSE_DELAY=-1".toString(),
+ 'dataSource.dialect' : H2Dialect.name,
+ 'dataSource.dbCreate' : 'create-drop',
+ 'hibernate.hbm2ddl.auto' : 'create',
+ 'hibernate.cache.queries' : 'false',
+ 'hibernate.cache.use_query_cache': 'false',
] + extra, classes as Class[])
return datastore
}
@@ -105,12 +103,12 @@ class GeneratedModeEnversSpec extends Specification {
return result
}
- def "an audited domain class has audit tables, revisions and audit queries that return real instances in generated mode"() {
+ def "an audited domain class has audit tables, revisions and audit queries that return real instances"() {
given:
- HibernateDatastore generated = boot(true, [EnversBook, EnversNovel])
+ HibernateDatastore generated = boot([EnversBook, EnversNovel])
expect: 'the audit tables are mapped'
- columnsByTable(generated).keySet().containsAll(['envers_book_aud', 'revinfo'])
+ columnsByTable(generated).keySet().containsAll(['envers_book', 'envers_book_aud', 'revinfo'])
when:
Map history = bookHistory()
@@ -125,52 +123,23 @@ class GeneratedModeEnversSpec extends Specification {
history.atRevision.collect { it[0] }.toSet() == ['EnversBook', 'EnversNovel'].toSet()
}
- def "generated mode audits the same entities and writes the same revisions as binder mode"() {
- when:
- HibernateDatastore binderDatastore = boot(false, [EnversBook, EnversNovel])
- Map binderTables = columnsByTable(binderDatastore)
- Map binderHistory = bookHistory()
- HibernateDatastore generatedDatastore = boot(true, [EnversBook, EnversNovel])
- Map generatedTables = columnsByTable(generatedDatastore)
- Map generatedHistory = bookHistory()
-
- then: 'the same tables exist'
- binderTables.keySet() == generatedTables.keySet()
-
- and: 'the audited entities are bound alike and the revision tables are equal'
- binderTables.findAll { String name, List<String> columns -> !name.endsWith('_aud') } ==
- generatedTables.findAll { String name, List<String> columns -> !name.endsWith('_aud') }
-
- and: 'the audit table of the entity differs only in the columns named in the next feature'
- binderTables['envers_book_aud'] - generatedTables['envers_book_aud'] == ['secret']
- generatedTables['envers_book_aud'] - binderTables['envers_book_aud'] == []
-
- and: 'the revisions and the audit queries return the same'
- binderHistory == generatedHistory
- }
-
def "a field level @NotAudited and the optimistic locking version are honoured the way Envers does for annotated entities"() {
when:
- Map binder = columnsByTable(boot(false, [EnversBook, EnversNovel]))
- Map generated = columnsByTable(boot(true, [EnversBook, EnversNovel]))
- Map generatedWithVersion = columnsByTable(boot(true, [EnversBook, EnversNovel],
+ Map generated = columnsByTable(boot([EnversBook, EnversNovel]))
+ Map generatedWithVersion = columnsByTable(boot([EnversBook, EnversNovel],
['hibernate.additionalProperties': ['org.hibernate.envers.do_not_audit_optimistic_locking_field': 'false']]))
- then: 'binder mode audits both, because Envers reads the getter of a property accessed property and the Groovy field is the one annotated, and the version has no @Version annotation to recognise'
- binder['envers_book_aud'].containsAll(['secret', 'version'])
-
- and: 'generated mode puts the annotation on the field Envers reads, and audits the version as binder mode does'
- !generated['envers_book_aud'].contains('secret')
- generated['envers_book_aud'].contains('version')
+ then: 'the annotation is on the field Envers reads (the classic binding of Grails 8 audited the property, since Envers read the getter), and the version is audited as it was then'
+ generated['envers_book_aud'] == ['id', 'pages', 'rev', 'revtype', 'title', 'version']
and: 'Envers\' own setting, which a user can still set, gives the same'
generatedWithVersion['envers_book_aud'].contains('version')
!generatedWithVersion['envers_book_aud'].contains('secret')
}
- def "a user value of the Envers optimistic locking setting wins over the generated mode default"() {
+ def "a user value of the Envers optimistic locking setting wins over the default"() {
when:
- Map generated = columnsByTable(boot(true, [EnversVersioned],
+ Map generated = columnsByTable(boot([EnversVersioned],
['hibernate.additionalProperties': ['org.hibernate.envers.do_not_audit_optimistic_locking_field': 'true']]))
then:
@@ -210,28 +179,23 @@ class GeneratedModeEnversSpec extends Specification {
}
}
- def "the audit table and its rows carry the optimistic locking version as in binder mode for #type.simpleName"() {
+ def "the audit table and its rows carry the optimistic locking version as with classic binding for #type.simpleName"() {
when:
- HibernateDatastore binderDatastore = boot(false, [type])
- changeTwice(type, 'name')
- Map binder = versionAudit(binderDatastore, table, versionColumn)
- HibernateDatastore generatedDatastore = boot(true, [type])
+ HibernateDatastore generatedDatastore = boot([type])
changeTwice(type, 'name')
Map generated = versionAudit(generatedDatastore, table, versionColumn)
- then: 'the audit table has the same columns, types and nullability'
- binder.columns == generated.columns
- binder.columns*.getAt(0).contains(versionColumn) == hasVersion
+ then: 'the audit table has the columns of the entity, the revision and the revision type'
+ generated.columns*.getAt(0) == columns
- and: 'the version written at each revision is the same'
- binder.rows == generated.rows
- !hasVersion || binder.rows*.getAt(1).any { it != null }
+ and: 'the version written at each revision is the one of the row then'
+ generated.rows == rows
where:
- type | table | versionColumn | hasVersion
- EnversVersioned | 'envers_versioned_aud' | 'version' | true
- EnversUnversioned | 'envers_unversioned_aud' | null | false
- EnversCustomVersion | 'envers_custom_version_aud' | 'lock_no' | true
+ type | table | versionColumn | columns | rows
+ EnversVersioned | 'envers_versioned_aud' | 'version' | ['id', 'name', 'rev', 'revtype', 'version'] | [[0, 0], [1, 1], [1, 2], [2, 2]]
+ EnversUnversioned | 'envers_unversioned_aud' | null | ['id', 'name', 'rev', 'revtype'] | null
+ EnversCustomVersion | 'envers_custom_version_aud' | 'lock_no' | ['id', 'lock_no', 'name', 'rev', 'revtype'] | [[0, 0], [1, 1], [1, 2], [2, 2]]
}
private static Map shelfHistory() {
@@ -261,9 +225,9 @@ class GeneratedModeEnversSpec extends Specification {
return result
}
- def "a hasMany collection of audited entities is audited in generated mode"() {
+ def "a hasMany collection of audited entities is audited (the classic binding of Grails 8 failed to boot it)"() {
given:
- boot(true, [EnversShelf, EnversItem])
+ boot([EnversShelf, EnversItem])
when:
Map history = shelfHistory()
@@ -274,15 +238,6 @@ class GeneratedModeEnversSpec extends Specification {
history.itemLabels == [['a', 'b'], ['a', 'b', 'c']]
history.itemClasses == ['EnversItem'].toSet()
}
-
- @PendingFeature(reason = 'binder mode: Envers builds the audit mapping of a hasMany collection before the domain binder has run its second passes and fails with a NullPointerException on the missing collection key')
- def "a hasMany collection of audited entities is audited in binder mode"() {
- given:
- boot(false, [EnversShelf, EnversItem])
-
- expect:
- shelfHistory().itemLabels == [['a', 'b'], ['a', 'b', 'c']]
- }
}
@Audited
diff --git a/grails-data-hibernate7/dbmigration/src/test/groovy/org/grails/plugins/databasemigration/generated/GeneratedModeSnapshotSpec.groovy b/grails-data-hibernate7/dbmigration/src/test/groovy/org/grails/plugins/databasemigration/generated/GeneratedModeSnapshotSpec.groovy
index 08bbd05a20..4a20d6a96d 100644
--- a/grails-data-hibernate7/dbmigration/src/test/groovy/org/grails/plugins/databasemigration/generated/GeneratedModeSnapshotSpec.groovy
+++ b/grails-data-hibernate7/dbmigration/src/test/groovy/org/grails/plugins/databasemigration/generated/GeneratedModeSnapshotSpec.groovy
@@ -45,16 +45,14 @@ import org.hibernate.boot.spi.MetadataImplementor
import org.hibernate.dialect.H2Dialect
import spock.lang.AutoCleanup
import spock.lang.Specification
-import spock.lang.Unroll
import org.grails.orm.hibernate.HibernateDatastore
import org.grails.plugins.databasemigration.liquibase.GormDatabase
/**
* The Liquibase snapshot and the changelog that dbm-gorm-diff and dbm-generate-gorm-changelog build from the Hibernate
- * mapping model are the same whether the domain binder or the generated domain classes bound it: tables, columns and
- * their types, primary keys, foreign keys, unique constraints, indexes and sequences. The differences that remain are
- * the known ones of the generated mode, each pinned by its own feature.
+ * mapping model: tables, columns and their types, primary keys, foreign keys, unique constraints, indexes and sequences.
+ * They are the ones the classic binding of Grails 8 gave, but for the known differences each pinned by its own feature.
*/
class GeneratedModeSnapshotSpec extends Specification {
@@ -66,13 +64,12 @@ class GeneratedModeSnapshotSpec extends Specification {
@AutoCleanup
HibernateDatastore datastore
- private GormDatabase boot(boolean generated, List<Class> classes) {
+ private GormDatabase boot(List<Class> classes) {
datastore?.close()
datastore = new HibernateDatastore([
- 'dataSource.url' : "jdbc:h2:mem:snapSpec${generated}${System.nanoTime()};LOCK_TIMEOUT=10000;DB_CLOSE_DELAY=-1".toString(),
- 'dataSource.dialect' : H2Dialect.name,
- 'dataSource.dbCreate' : 'none',
- 'hibernate.generatedDomainClasses': generated,
+ 'dataSource.url' : "jdbc:h2:mem:snapSpec${System.nanoTime()};LOCK_TIMEOUT=10000;DB_CLOSE_DELAY=-1".toString(),
+ 'dataSource.dialect' : H2Dialect.name,
+ 'dataSource.dbCreate': 'none',
], classes as Class[])
return new GormDatabase(new H2Dialect(), datastore)
}
@@ -99,18 +96,6 @@ class GeneratedModeSnapshotSpec extends Specification {
return lines.sort()
}
- /**
- * The known differences that the features below pin are hidden: the order of the columns of a primary key and the
- * name Hibernate gives the unique key of a natural id.
- */
- private static List<String> withoutKnownDifferences(List<String> lines) {
- return lines.collect { String line ->
- line.replaceAll(/(?i)(on [\w.]+)\(([^)]*)\)/) { List<String> match ->
- match[1] + '(' + match[2].split(', ').toList().sort().join(', ') + ')'
- }.replaceAll(/UK[0-9a-z]{20,}/, 'UK<hash>')
- }.sort()
- }
-
private static String changeLog(GormDatabase reference) {
Class.forName('org.h2.Driver')
java.sql.Connection connection = java.sql.DriverManager.getConnection("jdbc:h2:mem:snapTarget${System.nanoTime()}", 'SA', '')
@@ -140,51 +125,40 @@ class GeneratedModeSnapshotSpec extends Specification {
}.sort()
}
- def "the Liquibase snapshot of the generated mapping equals the snapshot of the binder mapping"() {
+ def "the Liquibase snapshot of the mapping has every kind of schema object"() {
when:
- List<String> binder = snapshotLines(boot(false, ALL))
- List<String> generated = snapshotLines(boot(true, ALL))
+ List<String> generated = snapshotLines(boot(ALL))
- then: 'the snapshot has every kind of object'
+ then:
['Table', 'Column', 'PrimaryKey', 'ForeignKey', 'UniqueConstraint', 'Index', 'Sequence'].every { String type ->
- binder.any { it.startsWith(type + ' ') }
+ generated.any { it.startsWith(type + ' ') }
}
- binder.size() > 100
-
- and: 'nothing differs besides the known differences'
- withoutKnownDifferences(binder) - withoutKnownDifferences(generated) == []
- withoutKnownDifferences(generated) - withoutKnownDifferences(binder) == []
+ generated.size() > 100
}
def "the primary key of a composite identifier lists its columns in the order Hibernate sorts them, and the natural id key has Hibernate's own name"() {
when:
- List<String> binder = snapshotLines(boot(false, ALL))
- List<String> generated = snapshotLines(boot(true, ALL))
- Closure<String> primaryKey = { List<String> lines -> lines.find { it.startsWith('PrimaryKey snap_enrollmentPK') } }
- Closure<String> naturalKey = { List<String> lines ->
- (lines.find { it.startsWith('UniqueConstraint UK') && it.contains('snap_natural') } =~ /UniqueConstraint (UK\w+)/)[0][1]
- }
+ List<String> generated = snapshotLines(boot(ALL))
+ String primaryKey = generated.find { it.startsWith('PrimaryKey snap_enrollmentPK') }
+ String naturalKey = (generated.find { it.startsWith('UniqueConstraint UK') && it.contains('snap_natural') } =~ /UniqueConstraint (UK\w+)/)[0][1]
- then: 'the binder keeps the order of the mapping, Hibernate sorts the parts of the identifier'
- primaryKey(binder).contains('ON HIBERNATE.snap_enrollment(student, course)')
- primaryKey(generated).contains('ON HIBERNATE.snap_enrollment(course, student)')
+ then: 'Hibernate sorts the parts of the identifier (the classic binding of Grails 8 kept the order of the mapping)'
+ primaryKey.contains('ON HIBERNATE.snap_enrollment(course, student)')
- and: 'both name the natural id key from its table and columns'
- naturalKey(binder) != naturalKey(generated)
+ and: 'the natural id key is named from its table and columns, by Hibernate'
+ naturalKey.startsWith('UK')
+ naturalKey.length() > 20
}
- def "the changelog generated from the generated mapping equals the one generated from the binder mapping"() {
+ def "the changelog generated from the mapping creates the sequences, identities and foreign keys"() {
when:
- List<String> binder = canonicalChangeLog(changeLog(boot(false, BASE)))
- List<String> generated = canonicalChangeLog(changeLog(boot(true, BASE)))
+ List<String> generated = canonicalChangeLog(changeLog(boot(BASE)))
then:
- binder.size() > 15
- binder.any { it.contains('<createSequence') }
- binder.any { it.contains('autoIncrement="true"') }
- binder.any { it.contains('<addForeignKeyConstraint') }
- binder - generated == []
- generated - binder == []
+ generated.size() > 15
+ generated.any { it.contains('<createSequence') }
+ generated.any { it.contains('autoIncrement="true"') }
+ generated.any { it.contains('<addForeignKeyConstraint') }
}
/**
* The order of the columns of a table in the generated change log is the order Hibernate's mapping model holds them,
@@ -196,18 +170,12 @@ class GeneratedModeSnapshotSpec extends Specification {
* columns, so dbm-gorm-diff against an existing database is not affected; only a createTable change set lists them
* in the new order.
*/
- @Unroll
- def "without a schema action the columns of a table are in the order the binding created them (generated: #generated)"() {
+ def "without a schema action the columns of a table are in the order Hibernate's annotation binder created them"() {
when:
- boot(generated, [SnapAuthor, SnapBook])
-
- then:
- tableColumns('snap_book') == columns
+ boot([SnapAuthor, SnapBook])
- where:
- generated | columns
- false | ['id', 'version', 'title', 'isbn', 'author_id']
- true | ['id', 'isbn', 'title', 'version', 'author_id']
+ then: 'the classic binding of Grails 8 listed them as id, version, title, isbn, author_id'
+ tableColumns('snap_book') == ['id', 'isbn', 'title', 'version', 'author_id']
}
private List<String> tableColumns(String table) {
(grails-core) 05/06: docs(hibernate7): native domain binding is the only binding, the classic binding of Grails 8 is gone
Posted by bo...@apache.org.
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 edb22b5fec7626a6f0c8f5a95e96f84e82a310b0
Author: Walter Duque de Estrada <wb...@mac.com>
AuthorDate: Fri Oct 9 18:26:10 2026 -0500
docs(hibernate7): native domain binding is the only binding, the classic binding of Grails 8 is gone
The Native Domain Binding chapter no longer offers a fallback: it says what changed from the
classic binding of Grails 8 (the unsupported mappings, which the classic binding could not use
either, the changes in behaviour and in the schema, the Envers differences), and that the
hibernate.generatedDomainClasses setting is ignored with a warning. The configuration
reference and the Hibernate versions checklist say the same, and the 9.0.x upgrade notes
drop the temporary fallback: an application whose mappings or database need work stays on
Grails 8 until it is done. Both manuals built; the rendered pages were grepped.
Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
---
.../advancedGORMFeatures/nativeDomainBinding.adoc | 166 +++++++++------------
.../configuration/configurationReference.adoc | 2 +-
.../asciidoc/gettingStarted/hibernateVersions.adoc | 10 +-
.../src/en/guide/upgrading/upgrading90x.adoc | 45 +++---
4 files changed, 98 insertions(+), 125 deletions(-)
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 81f7a6b925..a06851e4fa 100644
--- a/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc
+++ b/grails-data-hibernate7/docs/src/docs/asciidoc/advancedGORMFeatures/nativeDomainBinding.adoc
@@ -20,39 +20,22 @@ under the License.
[[advancedGORMFeatures-nativeDomainBinding]]
== Native Domain Binding
-GORM for Hibernate 7 can bind your domain classes to Hibernate in two ways.
+GORM for Hibernate 7 binds your domain classes to Hibernate natively: GORM describes each domain class with the JPA and Hibernate annotations that express the same mapping, and Hibernate's own annotation binder binds them. Your domain classes are not changed. Sessions, queries, proxies, dirty checking and the instances you work with are still your real domain classes. The mapping is bound by the same code that binds hand-annotated JPA entities, so it follows Hibernate releases without GO [...]
-Native binding::
-GORM describes each domain class with the JPA and Hibernate annotations that express the same mapping, and Hibernate's own annotation binder binds them. Your domain classes are not changed. Sessions, queries, proxies, dirty checking and the instances you work with are still your real domain classes. This is the default.
+Grails 8 bound the domain classes with the classic binding: GORM read your `static mapping` blocks and constraints and built Hibernate's mapping model itself. The classic binding was removed in Grails 9.0. Native binding is the only binding, and there is no setting that selects another.
-Classic binding::
-GORM reads your `static mapping` blocks and constraints and builds Hibernate's mapping model itself. Classic binding is deprecated and will be removed in a later release.
-
-Native binding is where GORM for Hibernate 7 is heading: the mapping is bound by the same code that binds hand-annotated JPA entities, so it follows Hibernate releases without GORM keeping its own copy of Hibernate's mapping rules.
-
-This page lists everything that differs from classic binding, so you know what changes for an application that was built with it.
+This page lists everything that changed from the classic binding, so you know what to expect for an application, and a database, that were built with Grails 8.
[[nativeDomainBinding-enabling]]
-=== Enabling Native Binding
-
-Native binding is on by default: `hibernate.generatedDomainClasses` is a boolean and defaults to `true`. Nothing needs to be set.
-
-Setting it to `false` selects the deprecated classic binding. Use this only to keep an existing application running while you work through the differences on this page; the application logs a warning at startup that names the setting, and the option goes away when classic binding is removed.
-
-[source,yaml]
-.grails-app/conf/application.yml
-----
-hibernate:
- generatedDomainClasses: false # deprecated: selects the classic binding
-----
+=== The Setting of Grails 8
-The same key works wherever the configuration is read: `application.yml` in Spring Boot, or the `Map` or `PropertyResolver` passed to `HibernateDatastore` when GORM is used standalone. The setting applies to every data source of the application.
+Nothing needs to be set. The setting `hibernate.generatedDomainClasses`, which selected the classic binding in Grails 8 when set to `false`, is no longer read: an application that still sets it, with either value, starts with native binding and logs a warning at startup that names the setting. Remove it from `application.yml`, and from the `Map` or `PropertyResolver` passed to `HibernateDatastore` when GORM is used standalone.
NOTE: Native binding changes how the mapping is built, not the API. `save()`, `get()`, finders, criteria, HQL, `where` queries, events, validation and transactions are used exactly as before.
=== What Stays the Same
-For the domain classes in GORM's own test suites, both bindings produce the same schema apart from the differences listed below. The following are the same on purpose:
+For the domain classes in GORM's own test suites, native binding produces the schema the classic binding of Grails 8 produced, apart from the differences listed below. The following are the same on purpose:
* Entity names are the names of your domain classes, so statistics, entity graphs, cache regions and log messages use the names they used with classic binding.
* Second-level cache regions are named as with classic binding.
@@ -61,29 +44,29 @@ For the domain classes in GORM's own test suites, both bindings produce the same
* All multi-tenancy modes (`DISCRIMINATOR`, `SCHEMA`, `DATABASE`) and multiple data sources work. An association still cannot refer to an entity of another data source.
* Composite identifiers use the same primary key column order.
* Properties mapped with a `UserType` class, and with the registered converter types `yes_no`, `true_false` and `numeric_boolean`, are stored as before.
-* A `hasMany` of basic values whose `type` is `'serializable'` or a `UserType` class is stored in one column of the owner's table, as before, with the `index`, `unique` group and column settings of the property. A `type` on a `hasMany` of domain classes changes nothing in both bindings.
+* A `hasMany` of basic values whose `type` is `'serializable'` or a `UserType` class is stored in one column of the owner's table, as before, with the `index`, `unique` group and column settings of the property. A `type` on a `hasMany` of domain classes changes nothing, as before.
* 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. When more than one embedded property embeds the class, every owner gets a table of its own, see <<nativeDomainBinding-behavior,Differences in Behavior>>.
-* 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.
+* 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. When more than one embedded property embeds the class, every owner gets a table of its own, see <<nativeDomainBinding-behavior,Changes in Behavior from Grails 8>>.
+* 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, as before.
* `type: 'serializable'` on a property that is not a collection (a `String`, a `byte[]` or any `Serializable`) is a binary column holding the Java serialization of the value, as with classic binding.
* `params` on a registered type name such as `type: 'string'` are ignored, as with classic binding. They reach the type when it is a `UserType` that implements `ParameterizedType`.
* A `type` that names an `AttributeConverter` class, for example `type: 'org.hibernate.type.YesNoConverter'`, converts the property with it, on a single property as well as on a `hasMany` stored in one column, as with classic binding.
-* A registered type name for a different Java type than the property's, for example `type: 'string'` on an `Integer`, gives the column of the registered type (`varchar(255)`), as with classic binding. Neither binding converts the value, so saving a value that is not null fails with a `ClassCastException` in both; a null value and the other properties of the class are stored.
+* A registered type name for a different Java type than the property's, for example `type: 'string'` on an `Integer`, gives the column of the registered type (`varchar(255)`), as with classic binding. The value is not converted, as it was not by classic binding, so saving a value that is not null fails with a `ClassCastException`; a null value and the other properties of the class are stored.
* A natural id (`id natural: [...]`) may name an embedded object (the unique key spans its columns, in the order of the embedded class), and a name that is no property of the class is skipped without a message, as with classic binding.
-* A natural id declared on a subclass adds a unique key to the table of the hierarchy (the table of the subclass in a joined hierarchy), over the columns of the named properties in the order the mapping names them, and makes those properties updatable only when the natural id is `mutable`. Classic binding also marks the properties as natural identifiers, and with Hibernate 7 that makes every load of the subclass entity fail with a `NullPointerException`; native binding does not mark them [...]
-* `insertable: false` and `updatable: false` are honored on a property with a column. On an embedded object they apply to every column of the object. On a `hasMany` and on the inverse side of a one-to-one (the side with no column) both bindings ignore them: the collection is written through its own table, and the foreign key lives on the other side.
-* A `discriminator` column may set `precision` and `scale`, and the discriminator may have a `type` other than string, integer or character, for example `type: 'long'`. The precision and the scale change nothing in the DDL of a string, integer or character column, in both bindings.
+* A 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`. The classic binding also marked the properties as natural identifiers, and with Hibernate 7 that made every load of the subclass entity fail with a `NullPointerException`; native binding does not mark [...]
+* `insertable: false` and `updatable: false` are honored on a property with a column. On an embedded object they apply to every column of the object. On a `hasMany` and on the inverse side of a one-to-one (the side with no column) they are ignored, as they were by the classic binding: the collection is written through its own table, and the foreign key lives on the other side.
+* A `discriminator` column may set `precision` and `scale`, and the discriminator may have a `type` other than string, integer or character, for example `type: 'long'`. The precision and the scale change nothing in the DDL of a string, integer or character column, as before.
* 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.
+* 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 as with the classic binding.
* 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 [...]
-* The default `sort` of a bidirectional `hasMany` orders a set and a map by the property, also when it is an association (by its foreign key), and does nothing for a list, which stays in the order of its index. This is the same in both bindings.
+* A `joinTable` that names several `key` columns uses the first one, as with the classic binding (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, no [...]
+* The default `sort` of a bidirectional `hasMany` orders a set and a map by the property, also when it is an association (by its foreign key), and does nothing for a list, which stays in the order of its index. This is the same as with the 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]]
-=== Mappings Native Binding Refuses
+=== Mappings That Are Not Supported
-Native binding does not refuse a mapping that classic binding accepts and can use, with the one exception at the end of the table, which has a supported workaround. It refuses the mappings below, which classic binding cannot use either: classic binding fails to start with them, or it boots them and fails on the first row. The application fails at startup. The exception has an `UnsupportedOperationException` as its root cause, and the message names the domain class and the property, and s [...]
+Native binding supports every mapping that the classic binding of Grails 8 could use, with the one exception at the end of the table, which has a supported workaround. The mappings below are not supported; the classic binding could not use them either: it failed to start with them, or it booted them and failed on the first row. The application fails at startup. The exception has an `UnsupportedOperationException` as its root cause, and the message names the domain class and the property, [...]
[cols="2,3,3", options="header"]
|===
@@ -93,40 +76,40 @@ Native binding does not refuse a mapping that classic binding accepts and can us
| 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 fails with a `ClassCastException` for a collection and with `constraint involves a formula` for a formula.
+| Name only simple properties, enums, many-to-one associations and embedded objects in `natural`. The classic binding failed 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 ...`
-| Remove the `type`, or use `'serializable'` or a `UserType` class to store the collection in one column. Classic binding fails with `Could not load requested class`, and with a custom collection type on a collection of basic values.
+| Remove the `type`, or use `'serializable'` or a `UserType` class to store the collection in one column. The classic binding failed with `Could not load requested class`, and with a custom collection type on a collection of basic values.
-| A composite identifier combined with something classic binding cannot boot: a `hasMany` of domain classes that is not a many-to-many and uses a join table to an entity with a composite identifier, a join table whose key columns are mapped on an entity with a composite identifier, a composite identifier part that is the inverse side of a one-to-one, a part that refers to an entity with a simple identifier or to a composite identifier more than one level deep, a joined subclass of such a [...]
+| A composite identifier combined with something the classic binding could not boot: a `hasMany` of domain classes that is not a many-to-many and uses a join table to an entity with a composite identifier, a join table whose key columns are mapped on an entity with a composite identifier, a composite identifier part that is the inverse side of a one-to-one, a part that refers to an entity with a simple identifier or to a composite identifier more than one level deep, a joined subclass of [...]
| `... 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`.
+| Give the entity a single-column identifier, or map the relationship with a domain class of its own. The classic binding failed with `Foreign key ... must have same number of columns as the referenced primary key` or an `IndexOutOfBoundsException`.
| Several columns mapped on a property that has one: on a simple property, on an association to an entity with a simple identifier, or on the key of a `hasMany` of an entity with a simple identifier. An association mapped with a `formula`. A one-to-one declared `hasOne` on both sides.
| `... the mapping states several columns ...`, `... the association is mapped with a formula ...` or `... the binder binds this one-to-one as a Hibernate OneToOne with a column of its own ...`
-| Map the property or the association with a single `column`. Classic binding fails with `Foreign key ... must have same number of columns as the referenced primary key`, `maps to 2 columns but 1 columns are required`, `value involves formulas` or `PostInitCallback queue could not be processed`.
+| Map the property or the association with a single `column`. The classic binding failed with `Foreign key ... must have same number of columns as the referenced primary key`, `maps to 2 columns but 1 columns are required`, `value involves formulas` or `PostInitCallback queue could not be processed`.
-| A collection that classic binding cannot create: a `SortedSet` of basic values, a `UserType` class as the `type` of a `hasMany` of domain classes, a `Map` of enums, a collection declared with a type that is not `Set`, `SortedSet`, `List`, `Collection` or `Map` (for example `HashSet`), a `hasMany` of a class that is not a domain class, an unknown `indexColumn` type, a default `sort` on a unidirectional `hasMany`, a `Map` or `Set` on a many-to-many that neither side owns (no `belongsTo`) [...]
+| A collection that the classic binding could not create: a `SortedSet` of basic values, a `UserType` class as the `type` of a `hasMany` of domain classes, a `Map` of enums, a collection declared with a type that is not `Set`, `SortedSet`, `List`, `Collection` or `Map` (for example `HashSet`), a `hasMany` of a class that is not a domain class, an unknown `indexColumn` type, a default `sort` on a unidirectional `hasMany`, a `Map` or `Set` on a many-to-many that neither side owns (no `belo [...]
| `Collection property [...]: ...`, `Association property [...]: ...` or `Entity [...] uses ... but the root of its hierarchy uses ...`
-| Change the mapping as the message says. Classic binding fails to start with each of them.
+| Change the mapping as the message says. The classic binding failed to start with each of them.
-| An embedded object as a part of a composite identifier (`id composite: ['code', 'address']` where `address` is listed in `static embedded`). Classic binding boots this mapping; native binding does not support it.
+| An embedded object as a part of a composite identifier (`id composite: ['code', 'address']` where `address` is listed in `static embedded`). The classic binding booted this mapping; native binding does not support it.
| `Composite identifier part [...] of [...] is an embedded object, which the generator does not support because Hibernate cannot state one in an identifier class. Map the properties of the embedded class as plain properties of the identifier instead ...`
| Name the properties of the embedded class in the identifier instead, which keeps the schema. See <<nativeDomainBinding-embeddedId,Embedded Object as Part of a Composite Identifier>>.
| 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.
+| Remove the `type` (an enum is stored as a string unless `enumType` says otherwise). The classic binding booted these mappings but could not use them: saving a row failed with a `ClassCastException` for the enum, with a check constraint violation for the list, and the table of the map was not created.
|===
[[nativeDomainBinding-embeddedId]]
=== Embedded Object as Part of a Composite Identifier
-Hibernate cannot hold an embedded object in an identifier class, so native binding refuses a composite identifier that names one. The workaround is to declare the properties of the embedded class as plain properties of the entity and to name them in the identifier. The tables, the columns, the types, the primary key and its column order stay as they are, with both bindings.
+Hibernate cannot hold an embedded object in an identifier class, so native binding refuses a composite identifier that names one. The workaround is to declare the properties of the embedded class as plain properties of the entity and to name them in the identifier. The tables, the columns, the types, the primary key and its column order stay as Grails 8 created them.
[source,groovy]
-.Before: refused by native binding
+.Before: accepted by Grails 8, refused by native binding
----
class Customer implements Serializable {
String code
@@ -146,7 +129,7 @@ class Address implements Serializable {
----
[source,groovy]
-.After: boots with both bindings
+.After: boots with native binding, with the schema of before
----
class Customer implements Serializable {
String code
@@ -162,7 +145,7 @@ class Customer implements Serializable {
}
----
-Both versions create the same table. The primary key columns are in the order Hibernate gives them (here the sorted column names), which is the same for both:
+Both versions create the same table. The primary key columns are in the order Hibernate gives them (here the sorted column names), which is the order Grails 8 used:
[source,sql]
----
@@ -212,10 +195,10 @@ class Customer implements Serializable {
==== Associations to the Entity
* A `hasMany` of the entity that is bound by a foreign key on the entity (the entity has a many-to-one to its parent, as in `Region.hasMany = [customers: Customer]` and `Region region` in `Customer`) works as for any entity with a composite identifier, and the foreign key `region_id` is unchanged.
-* A many-to-one from another entity to the flattened entity creates the columns `<table of the entity>_<identifier column>`, in the order of the primary key (`customer_address_city`, `customer_address_street` and `customer_code` for the table `customer`), and a foreign key that references the identifier columns one to one: `foreign key (customer_address_city, customer_address_street, customer_code) references customer (address_city, address_street, code)`. Both bindings create the same t [...]
+* A many-to-one from another entity to the flattened entity creates the columns `<table of the entity>_<identifier column>`, in the order of the primary key (`customer_address_city`, `customer_address_street` and `customer_code` for the table `customer`), and a foreign key that references the identifier columns one to one: `foreign key (customer_address_city, customer_address_street, customer_code) references customer (address_city, address_street, code)`.
+
-Classic binding could not do this for the embedded version. It fails to start with `maps to 2 columns but 3 columns are required`, and when the three columns are spelled out it starts but pairs them wrongly (`customer_address_city` references `code`). A database that has such a table keeps the columns, but its foreign key may be wrong: check it before you rely on it.
-* A `hasMany` of the entity through a join table (a unidirectional `hasMany` of the parent) is not supported by either binding for any entity with a composite identifier, flattened or not; it is in the table above. Add the many-to-one to the entity, as in the first item.
+The classic binding of Grails 8 could not do this for the embedded version. It failed to start with `maps to 2 columns but 3 columns are required`, and when the three columns were spelled out it started but paired them wrongly (`customer_address_city` referenced `code`). A database that has such a table keeps the columns, but its foreign key may be wrong: check it before you rely on it.
+* A `hasMany` of the entity through a join table (a unidirectional `hasMany` of the parent) is not supported for any entity with a composite identifier, flattened or not (the classic binding did not boot it either); it is in the table above. Add the many-to-one to the entity, as in the first item.
==== Switching an Existing Database
@@ -223,12 +206,12 @@ The workaround changes no schema, so there is nothing to migrate:
. Replace the embedded object in the class and in the identifier as shown above, and change the code that reads `address.street` in a query to `addressStreet`.
. Start with `dbCreate: validate` against a copy of the database. Hibernate finds every table and column.
-. Rows written with the embedded entity are read, updated and deleted through the flattened one (`Customer.get(new Customer(code: 'c1', addressStreet: 's1', addressCity: 'x1'))`, finders and associations), and rows written by the flattened one are read by the embedded one if you go back.
+. Rows written with the embedded entity are read, updated and deleted through the flattened one (`Customer.get(new Customer(code: 'c1', addressStreet: 's1', addressCity: 'x1'))`, finders and associations), and rows written by the flattened one are read by the embedded entity of a Grails 8 application that still shares the database.
[[nativeDomainBinding-behavior]]
-=== Differences in Behavior
+=== Changes in Behavior from Grails 8
-Some bugs of classic binding are not copied by native binding. Native binding does what the mapping says.
+Some bugs of the classic binding of Grails 8 are not copied by native binding. Native binding does what the mapping says.
[cols="2,3", options="header"]
|===
@@ -236,31 +219,31 @@ Some bugs of classic binding are not copied by native binding. Native binding do
| Difference
| A custom collection type (a `UserCollectionType` class) as the `type` of a `hasMany` of domain classes, for example `books type: MyCollectionType`.
-| Classic binding boots with the same schema but never uses the class: it keeps Hibernate's own collection and does not even create an instance of your type. Native binding applies the type, so Hibernate creates, wraps and loads the collection with your class. If you map a custom collection type that has never been exercised, test it before you switch. On a `hasMany` of basic values neither binding supports it.
+| The classic binding booted with the same schema but never used the class: it kept Hibernate's own collection and did not even create an instance of your type. Native binding applies the type, so Hibernate creates, wraps and loads the collection with your class. If you map a custom collection type that has never been exercised, test it before you upgrade. On a `hasMany` of basic values it is not supported (the classic binding did not boot it either).
| A `unique` group that includes an enum property.
-| Classic binding drops the group. Native binding creates the unique constraint. With `dbCreate: update` the constraint is added to an existing table, and fails if the table holds duplicates.
+| The classic binding dropped the group. Native binding creates the unique constraint. With `dbCreate: update` the constraint is added to an existing table, and fails if the table holds duplicates.
| An owner with two or more unidirectional `hasMany` collections that use a join table.
-| Classic binding can fail to write the join table rows of such a collection. Native binding writes them.
+| The classic binding could fail to write the join table rows of such a collection. Native binding writes them.
| The `nullable: false` constraint on the element column of a map of values.
-| Classic binding leaves the column nullable. Native binding makes it `not null`.
+| The classic binding left the column nullable. Native binding makes it `not null`.
| A `unique` group on the property of a collection (`hasMany`).
-| The group names columns of the owner's table, which the table of the collection does not have. Classic binding tries to create a unique key over them and the statement fails when the schema is created, so the database has no such key. Native binding creates no key. The `index` option on the same property works in both bindings: the index is created over the key column of the collection table (and over the element column of a collection of enums), with the name the mapping gives it.
+| The group names columns of the owner's table, which the table of the collection does not have. The classic binding tried to create a unique key over them and the statement failed when the schema was created, so the database has no such key. Native binding creates no key. The `index` option on the same property works as it did: the index is created over the key column of the collection table (and over the element column of a collection of enums), with the name the mapping gives it.
| A `hasMany` inside a class listed in `static embedded` (basic values, enums or domain classes) when more than one embedded property of the application embeds that class: two domain classes, or one domain class with two properties of that type.
-| Classic binding names the table and the key column after the embedded class, so all the owners share one table. Its foreign key points at the owner that was bound first, so the collection of any other owner cannot be stored (the insert violates the key), the elements of two properties of one owner are mixed up, and the application fails to start when the properties have the same name. Native binding gives every owner a collection table of its own. The first owner, in the order of the e [...]
+| The classic binding named the table and the key column after the embedded class, so all the owners shared one table. Its foreign key pointed at the owner that was bound first, so the collection of any other owner could not be stored (the insert violated the key), the elements of two properties of one owner were mixed up, and the application failed to start when the properties had the same name. Native binding gives every owner a collection table of its own. The first owner, in the orde [...]
| An `index` given as a closure on the property of a collection, for example `index: { column name: 'position' }`.
-| The closure configures the index column of a list or a map in both bindings. Classic binding also creates an index of the collection table that is named after the closure, a name that changes on every start. Native binding creates the index column and no such index.
+| The closure configures the index column of a list or a map, as it did. The classic binding also created an index of the collection table that was named after the closure, a name that changed on every start. Native binding creates the index column and no such index.
|===
[[nativeDomainBinding-schema]]
-=== Differences in the Schema
+=== Changes in the Schema from Grails 8
-The schema of 765 groups of related domain classes was created with both bindings on H2 and compared: tables, columns with type, nullability, default, length, precision and scale, primary keys with their column order, foreign keys, unique keys, indexes, check constraints and sequences. Native binding booted every group that classic binding boots, and these are the differences. Other databases are not covered by this comparison, so verify against your own database as described below.
+The schema of 766 groups of related domain classes was created with the classic binding of Grails 8 and with native binding on H2 and compared: tables, columns with type, nullability, default, length, precision and scale, primary keys with their column order, foreign keys, unique keys, indexes, check constraints and sequences. Native binding boots every group that the classic binding booted, and these are the differences. Other databases are not covered by this comparison, so verify agai [...]
[cols="2,3,3", options="header"]
|===
@@ -270,78 +253,77 @@ The schema of 765 groups of related domain classes was created with both binding
| `check (<index column> >= 0)` on the index column of every `List` mapping.
| Hibernate adds it to every list index column and offers no way to leave it out. GORM never writes a negative index.
-| Tables created by classic binding have no such constraint. It cannot reject a value that GORM writes.
+| Tables created by the classic binding have no such constraint. It cannot reject a value that GORM writes.
| Column types, column order and primary key order of a table that has a foreign key to an entity whose composite identifier contains another composite identifier.
-| Classic binding gives such foreign key columns the type of a different part of the key than their name says, for example a column `parent_grand_parent_name` of type `integer`. Native binding names and types them correctly. The fix for classic binding is in the 8.0.x line; once your version includes it, this difference disappears for the column types.
-| The column types differ from those of a database created by classic binding. Migrate or recreate such tables before you switch. The order of the foreign key columns may remain different.
+| The classic binding gave such foreign key columns the type of a different part of the key than their name says, for example a column `parent_grand_parent_name` of type `integer`. Native binding names and types them correctly. The fix for the classic binding is in the 8.0.x line; a database created by a Grails 8 release that includes it has the right column types.
+| The column types differ from those of a database created by the classic binding. Migrate or recreate such tables before you upgrade. The order of the foreign key columns may remain different.
| The order of the columns of the foreign key from a collection to an entity with a composite identifier.
-| Classic binding creates two foreign keys of the same name in two column orders and keeps one of them depending on the order the classes are bound in.
+| The classic binding created two foreign keys of the same name in two column orders and kept one of them depending on the order the classes were bound in.
| Same constraint name and same columns, in another order.
| No foreign key for an association mapped with `ignoreNotFound: true`.
| Hibernate does not create the foreign key for `@NotFound(IGNORE)`. A dangling reference is the point of the option.
-| A database created by classic binding has the foreign key. A diff reports a foreign key that the model no longer has.
+| A database created by the classic binding has the foreign key. A diff reports a foreign key that the model no longer has.
| One join table instead of two when the two sides of a many-to-many name the join table differently.
-| Classic binding creates a second table for the inverse side that nothing reads or writes. Native binding uses the table that the owning side names.
+| The classic binding created a second table for the inverse side that nothing reads or writes. Native binding uses the table that the owning side names.
| The second table stays in an existing database. Remove it yourself.
| `not null` on the column of a `Map` on a many-to-many that holds the entity the map refers to, when the other side is a `Set`.
-| That column is also the key column of the `Set` that reads the map, and classic binding sets its nullability twice, so it is nullable or not null depending on the order in which the domain classes are bound. Native binding always creates it `not null`, like the element column of any many-to-many.
+| That column is also the key column of the `Set` that reads the map, and the classic binding set its nullability twice, so it is nullable or not null depending on the order in which the domain classes were bound. Native binding always creates it `not null`, like the element column of any many-to-many.
| `update` does not change an existing nullable column. A diff reports the difference.
| `not null` on the element column of a map of values mapped with `nullable: false`.
-| See <<nativeDomainBinding-behavior,Differences in Behavior>>.
+| See <<nativeDomainBinding-behavior,Changes in Behavior from Grails 8>>.
| `update` does not change an existing nullable column. A diff reports the difference.
| No unused extra nullable column on the table of a map of values.
-| Classic binding creates a column such as `attributes_java_lang_string` that nothing uses.
+| The classic binding created a column such as `attributes_java_lang_string` that nothing uses.
| The column stays in an existing database. It does no harm.
| A unique constraint over the columns of a `unique` group that includes an enum.
-| See <<nativeDomainBinding-behavior,Differences in Behavior>>.
+| See <<nativeDomainBinding-behavior,Changes in Behavior from Grails 8>>.
| `update` adds the constraint.
| No unique key on the table of a collection for a `unique` group mapped on the collection property.
-| See <<nativeDomainBinding-behavior,Differences in Behavior>>.
-| The key never existed in a database created by classic binding: the statement that creates it fails.
+| See <<nativeDomainBinding-behavior,Changes in Behavior from Grails 8>>.
+| The key never existed in a database created by the classic binding: the statement that created it failed.
| An extra collection table, with a key column named after the owner and the embedded property, for every owner after the first of an embedded class that has a `hasMany`.
-| See <<nativeDomainBinding-behavior,Differences in Behavior>>. Classic binding shares one table between the owners.
-| The first owner keeps its table and column names. The tables of the other owners are new: `update` creates them, and the elements that classic binding could not store for those owners were never in the database.
+| See <<nativeDomainBinding-behavior,Changes in Behavior from Grails 8>>. The classic binding shared one table between the owners.
+| The first owner keeps its table and column names. The tables of the other owners are new: `update` creates them, and the elements that the classic binding could not store for those owners were never in the database.
| No index named after a closure on the table of a collection whose `index` is a closure.
-| See <<nativeDomainBinding-behavior,Differences in Behavior>>.
-| A database created by classic binding has an index with a name that depends on the start it was created in. Drop it if you want to be rid of it.
+| See <<nativeDomainBinding-behavior,Changes in Behavior from Grails 8>>.
+| A database created by the classic binding has an index with a name that depends on the start it was created in. Drop it if you want to be rid of it.
| The order of the columns in a `createTable` change set that `dbm-generate-gorm-changelog` or `dbm-gorm-diff` writes: the identifier, then the other columns in the order of the property names (the `version` column among them), then the foreign key columns.
-| Hibernate's annotation binder binds the properties of a class sorted by name, and the migration commands read the mapping model as it was bound. Classic binding listed the identifier, the version, then the properties in declaration order. The schema that `dbCreate` creates is not affected: Hibernate orders the columns of a table it creates itself, in the same way for both bindings, which is why the comparison above lists no other difference in column order.
+| Hibernate's annotation binder binds the properties of a class sorted by name, and the migration commands read the mapping model as it was bound. The classic binding listed the identifier, the version, then the properties in declaration order. The schema that `dbCreate` creates is not affected: Hibernate orders the columns of a table it creates itself, as it did for the classic binding, which is why the comparison above lists no other difference in column order.
| None. Liquibase does not compare the order of columns, so a diff against an existing database reports nothing. A table created from a new change set has its columns in the new order.
|===
-The comparison finds no difference in the unique keys, indexes and identifier columns that natural ids, `unique` groups and `index` options create: they have the same columns in the same order as with classic binding.
+The comparison finds no difference in the unique keys, indexes and identifier columns that natural ids, `unique` groups and `index` options create: they have the same columns in the same order as with the classic binding.
-=== Switching an Existing Database
+=== Upgrading an Existing Database
-Do not switch a production database over blindly. Whether `dbCreate: update` or a Liquibase changelog would change anything depends on the differences above.
+Do not upgrade a production database blindly. Whether `dbCreate: update` or a Liquibase changelog would change anything depends on the differences above.
-. Start the upgraded application, with its default native binding, against a copy of your schema. Fix every refused mapping from the table above; classic binding cannot use these either.
-. Run <<ref-diff-scripts-dbm-gorm-diff,dbm-gorm-diff>> against the copy. An empty diff means the switch does not change the schema. Otherwise, compare each reported change with the table above, and apply the changes you want through a migration.
-. Run your test suite once with native binding.
-. If you need more time, set `hibernate.generatedDomainClasses: false` in the environments that are not ready yet, for example in `production` only, and remove it as soon as the migration has run. Classic binding is deprecated and will be removed.
+. Start the upgraded application against a copy of your schema. Fix every refused mapping from the table above; the classic binding of Grails 8 could not use these either.
+. Run <<ref-diff-scripts-dbm-gorm-diff,dbm-gorm-diff>> against the copy. An empty diff means the upgrade does not change the schema. Otherwise, compare each reported change with the table above, and apply the changes you want through a migration.
+. Run your test suite once.
-Prefer migrations over `dbCreate: update` for a production schema.
+Prefer migrations over `dbCreate: update` for a production schema. There is no setting that brings the classic binding back; an application whose mappings or database need work stays on Grails 8 until it is done.
[[nativeDomainBinding-envers]]
=== Envers
-Envers audits the same entities and writes the same revisions with both bindings. There are two differences:
+Envers audits the same entities and writes the same revisions as with the classic binding of Grails 8. There are two differences:
-* A `@NotAudited` annotation on a Groovy property is honored by native binding. Classic binding ignores it: Groovy puts the annotation on the field, and Envers reads the getter, so the property is audited. Classic binding audits a property that you excluded.
-* The `version` column of optimistic locking is audited by both bindings, as it is with classic binding.
+* A `@NotAudited` annotation on a Groovy property is honored by native binding. The classic binding ignored it: Groovy puts the annotation on the field, and Envers read the getter, so the property was audited. The classic binding audited a property that you excluded.
+* The `version` column of optimistic locking is audited, as it was with the classic binding.
=== Reporting an Unsupported Mapping
-If a mapping is refused that you think should work, or if the schema differs in a way that this page does not list, open an issue at https://github.com/apache/grails-core/issues with the domain classes, the `static mapping` blocks and the exception message or the DDL of each binding. Native binding is meant to accept every mapping that classic binding can use, so a mapping that classic binding accepts and uses and that native binding refuses is a bug of native binding.
+If a mapping is refused that you think should work, or if the schema differs from the one of Grails 8 in a way that this page does not list, open an issue at https://github.com/apache/grails-core/issues with the domain classes, the `static mapping` blocks and the exception message or the DDL. Native binding is meant to accept every mapping that the classic binding of Grails 8 could use, so a mapping that Grails 8 accepted and used and that native binding refuses is a bug of native binding.
diff --git a/grails-data-hibernate7/docs/src/docs/asciidoc/configuration/configurationReference.adoc b/grails-data-hibernate7/docs/src/docs/asciidoc/configuration/configurationReference.adoc
index 6fd360d59b..92cc8670f6 100644
--- a/grails-data-hibernate7/docs/src/docs/asciidoc/configuration/configurationReference.adoc
+++ b/grails-data-hibernate7/docs/src/docs/asciidoc/configuration/configurationReference.adoc
@@ -61,7 +61,7 @@ name,description,default value
`hibernate.configLocations`, Location of additional Hibernate XML configuration files
`hibernate.packagesToScan`, Specify packages to search for autodetection of your entity classes in the classpath
`hibernate.grails.proxy.lazy_to_string`, Whether `toString()` on an uninitialized proxy avoids initializing it (see Proxies and toString()), `false`
-`hibernate.generatedDomainClasses`, Whether Hibernate's own annotation binder binds the domain classes (see Native Domain Binding); `false` selects the deprecated classic binding, `true`
+`hibernate.generatedDomainClasses`, No longer used: it selected the classic binding of Grails 8, which was removed; native domain binding is the only binding (see Native Domain Binding). An application that still sets it starts normally and logs a warning, (ignored)
|===
In addition, any additional settings that start with `hibernate.` are passed through to Hibernate, so if there is any specific feature of Hibernate you wish to configure that is possible.
diff --git a/grails-data-hibernate7/docs/src/docs/asciidoc/gettingStarted/hibernateVersions.adoc b/grails-data-hibernate7/docs/src/docs/asciidoc/gettingStarted/hibernateVersions.adoc
index 1a6b4cc25d..4790375b75 100644
--- a/grails-data-hibernate7/docs/src/docs/asciidoc/gettingStarted/hibernateVersions.adoc
+++ b/grails-data-hibernate7/docs/src/docs/asciidoc/gettingStarted/hibernateVersions.adoc
@@ -109,13 +109,13 @@ If you are migrating an application from Hibernate 5 or the Grails Hibernate 5 p
| Grails 9 refuses to start when a bidirectional many-to-many has no `belongsTo` on either side. Earlier versions bound both sides as inverse, so no join table row was ever written and the relationship was silently lost.
| Declare `belongsTo` on the side that should be owned, for example `static belongsTo = Author` in `Book`. For a many-to-many from a class to itself, `belongsTo` names the class itself. The startup error names both sides of each affected relationship. See <<gormAssociation-manyToMany,Many-to-Many Associations>>.
-| Mapping fixes on classic binding
+| Mapping fixes
| `insertable: false` and `updatable: false` are honored, enum columns receive the `comment`, `defaultValue`, `read` and `write` of their column mapping, the elements of basic-value collections of an owner with several unidirectional collections are stored, and the inverse side of a many-to-many reads the join table that its owner writes.
-| Review domain classes that use `insertable: false` or `updatable: false`, because values that used to be written are no longer written. Compare the generated schema of enum properties with your database before using `dbCreate=update`. See <<nativeDomainBinding,Native Domain Binding>> for the related schema differences.
+| Review domain classes that use `insertable: false` or `updatable: false`, because values that used to be written are no longer written. Compare the generated schema of enum properties with your database before using `dbCreate=update`. See <<advancedGORMFeatures-nativeDomainBinding,Native Domain Binding>> for the related schema differences.
-| Native domain binding (the default)
-| Hibernate's own annotation binder binds the domain classes; `hibernate.generatedDomainClasses` defaults to `true`. A few mapping options that classic binding could not use either are refused at startup, and the generated schema differs from classic binding in documented cases. `hibernate.generatedDomainClasses: false` selects the classic binding, which is deprecated, logs a warning at startup and will be removed.
-| Before upgrading an existing database, fix the mappings listed in <<nativeDomainBinding-refused,Mappings Native Binding Refuses>> and run `dbm-gorm-diff` against a copy of the database with the upgraded application. See <<nativeDomainBinding-schema,Differences in the Schema>> and <<nativeDomainBinding-enabling,Enabling Native Binding>> for the temporary fallback.
+| Native domain binding (the only binding)
+| Hibernate's own annotation binder binds the domain classes. The classic binding of Grails 8 was removed, with the `hibernate.generatedDomainClasses` setting that selected it: an application that still sets the setting starts normally and logs a warning. A few mapping options that the classic binding could not use either are refused at startup, and the generated schema differs from the one of Grails 8 in documented cases.
+| Before upgrading an existing database, fix the mappings listed in <<nativeDomainBinding-refused,Mappings That Are Not Supported>> and run `dbm-gorm-diff` against a copy of the database with the upgraded application. See <<nativeDomainBinding-schema,Changes in the Schema from Grails 8>>, and remove the setting (<<nativeDomainBinding-enabling,The Setting of Grails 8>>).
| Query locks and query cache
| Locked queries are not query-cacheable.
diff --git a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc
index 5c913f88e2..be8a1cc28b 100644
--- a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc
+++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc
@@ -57,7 +57,7 @@ class Author {
The same applies to a many-to-many from a class to itself: `belongsTo` names the class itself.
A unidirectional many-to-many, a many-to-many that has `belongsTo` on either side, and one where either side is a `Map` need no change.
-The rule is the same with native domain binding, the default, and with the deprecated classic binding, see below.
+The rule is enforced by native domain binding, see below.
See link:{hibernate7Guide}index.html#gormAssociation-manyToMany[Many-to-Many Associations] in the GORM for Hibernate 7 manual.
@@ -82,20 +82,21 @@ They are also fixed in the 8.0.x line, so an application that is already on a re
===== 1.3 Native Domain Binding
GORM for Hibernate 7 binds your domain classes with Hibernate's own annotation binder instead of building Hibernate's mapping itself.
-This is native domain binding, and in Grails {version} it is the default: an upgraded application starts with it without any setting.
-The classic binding of earlier releases is deprecated and will be removed in a later release.
+This is native domain binding, and in Grails {version} it is the only binding: an upgraded application starts with it without any setting.
+The classic binding of Grails 8 was removed, with the `hibernate.generatedDomainClasses` setting that selected it.
+An application that still sets the setting, with either value, starts normally and logs a warning at startup that names it; remove the setting.
Your domain classes, your queries and the GORM API do not change.
The mapping can, though:
-* Native binding refuses a mapping only when classic binding cannot use it either: classic binding fails to start with it, or boots it and fails on the first row.
- The refusal is an `UnsupportedOperationException` at startup that says what classic binding does.
+* Native binding refuses a mapping only when the classic binding could not use it either: the classic binding failed to start with it, or booted it and failed on the first row.
+ The refusal is an `UnsupportedOperationException` at startup that says what the classic binding did.
The manual chapter lists them.
- The one exception today is an embedded object as a part of a composite identifier, which classic binding boots and native binding refuses with a message that points at a workaround that keeps the schema, see <<native-binding-embedded-id,1.5>>.
-* The generated schema differs from the one of classic binding in a few documented cases, for example a `check (idx >= 0)` constraint on the index column of every list, and the column types of foreign keys to nested composite identifiers.
-* A few defects of classic binding are not copied, such as a `unique` group that includes an enum property being dropped.
+ The one exception is an embedded object as a part of a composite identifier, which the classic binding booted and native binding refuses with a message that points at a workaround that keeps the schema, see <<native-binding-embedded-id,1.5>>.
+* The generated schema differs from the one of the classic binding in a few documented cases, for example a `check (idx >= 0)` constraint on the index column of every list, and the column types of foreign keys to nested composite identifiers.
+* A few defects of the classic binding are not copied, such as a `unique` group that includes an enum property being dropped.
* A `hasMany` inside a class listed in `static embedded` that more than one embedded property embeds gets a collection table of its own for every owner.
- Classic binding shares one table whose foreign key points at only one owner, so the collection of any other owner cannot be stored, and it does not start when the properties have the same name.
+ The classic binding shared one table whose foreign key pointed at only one owner, so the collection of any other owner could not be stored, and it did not start when the properties had the same name.
The first owner (by entity name, then property path) keeps the table and the key column it has today, the others get names that start with their table and the path of the embedded property.
* A custom collection type on a `hasMany` now takes effect, see <<native-binding-custom-collection-type,1.4>>.
* A `createTable` change set written by `dbm-generate-gorm-changelog` or `dbm-gorm-diff` lists the columns in a different order: the identifier, then the columns in the order of the property names, then the foreign keys.
@@ -104,22 +105,13 @@ The mapping can, though:
Before you upgrade an application with an existing database:
. Start the upgraded application against a copy of the database and fix every refused mapping; the startup error says what to change.
-. Run `dbm-gorm-diff` against the copy with the upgraded application, which uses the new default.
- An empty diff means the switch does not change your schema.
+. Run `dbm-gorm-diff` against the copy with the upgraded application.
+ An empty diff means the upgrade does not change your schema.
Otherwise, compare each reported change with the schema differences in the manual and apply the ones you want through a migration.
. Run your test suite once.
-If you need more time, the `hibernate.generatedDomainClasses` setting selects the classic binding for the environments that are not ready yet:
-
-[source,yaml]
-.grails-app/conf/application.yml
-----
-hibernate:
- generatedDomainClasses: false # deprecated: selects the classic binding
-----
-
-The application then logs a warning at startup that names the setting.
-Remove the setting as soon as the migration has run, because classic binding will be removed.
+There is no setting that brings the classic binding back.
+An application whose mappings or database need work stays on Grails 8 until it is done; every refused mapping is one the classic binding could not use either, so the change it needs is the same on both lines.
The link:{hibernate7Guide}index.html#advancedGORMFeatures-nativeDomainBinding[Native Domain Binding] chapter of the GORM for Hibernate 7 manual lists every refused mapping, every schema difference and what each means for an existing database.
@@ -138,8 +130,8 @@ class Author {
}
----
-Classic binding accepts this mapping and creates the usual schema, but it never uses the class.
-It does not even create an instance of `MyCollectionType`, and `author.books` is an ordinary Hibernate collection.
+The classic binding of Grails 8 accepted this mapping and created the usual schema, but it never used the class.
+It did not even create an instance of `MyCollectionType`, and `author.books` was an ordinary Hibernate collection.
Native binding applies the type.
Hibernate creates, wraps and loads the collection with your class, so the code of your collection type runs where it never ran before.
@@ -147,9 +139,8 @@ The schema is the same.
If your application maps a custom collection type, test it with the upgraded application before you deploy.
A type that was never exercised can fail or behave differently once it is used.
-With the deprecated classic binding (`hibernate.generatedDomainClasses: false`) nothing changes.
-A custom collection type on a `hasMany` of basic values is not supported by either binding.
+A custom collection type on a `hasMany` of basic values is not supported (the classic binding did not boot it either).
[[native-binding-embedded-id]]
===== 1.5 An Embedded Object as a Part of a Composite Identifier
@@ -172,6 +163,6 @@ class Customer implements Serializable {
}
----
-The table, its columns and its primary key are the ones the embedded version creates (`address_street` and `address_city` are the names the embedded object gives its columns), so an existing database needs no migration and its rows stay readable.
+The table, its columns and its primary key are the ones the embedded version created with Grails 8 (`address_street` and `address_city` are the names the embedded object gave its columns), so an existing database needs no migration and its rows stay readable.
A transient `Address getAddress()` accessor keeps `customer.address` working.
The link:{hibernate7Guide}index.html#nativeDomainBinding-embeddedId[Native Domain Binding] chapter of the GORM for Hibernate 7 manual describes the accessor, the foreign keys to such an entity and how to switch an existing database.
(grails-core) 03/06: refactor(hibernate7): delete the classic domain binder
Posted by bo...@apache.org.
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 be15a6fad10b1ed6e0176ee28b4e0714facd7c4c
Author: Walter Duque de Estrada <wb...@mac.com>
AuthorDate: Fri Oct 9 18:02:49 2026 -0500
refactor(hibernate7): delete the classic domain binder
Native domain binding is the only binding since the previous commit, so the code that
built Hibernate's boot model by hand goes: GrailsDomainBinder and the 31 binders of
cfg/domainbinding/binder, the 20 second passes, the 7 collection types and the 5 helpers
of util only they used, with their 60 unit specs. What the native path used of them is
kept under names that say what it is: GormMappingContributor (jpa) is the
AdditionalMappingContributor named GORM that GrailsDomainBinder was in native mode (it
caches the mappings, resolves the naming strategy and hands the entities to
GeneratedDomainClassBinder); PropertyAccessorName (jpa) is the accessor decision of
PropertyBinder; the four column helpers the generator and the aligner share move to
cfg/domainbinding/column; ManyToManyOwnerValidator moves next to the aligner; the naming
constants live on DefaultColumnNameFetcher, the default discriminator column name on
GrailsHibernatePersistentEntity, and the enum class parameter is IdentityEnumType's.
The @Entity fixtures the deleted unit specs declared stay in *Fixtures files of the same
packages: the differential specs scan them and the frozen classic oracle records them,
so both differentials keep their 799 groups, 0 mismatches and 85 known differences.
Comments that described what the generator mirrors name the classic binders no more.
HibernateGormDatastoreSpec offers getMappingContributor() in place of the binder and
loses the classic re-bind of hibernateFirstPass(); HibernateToManyPropertySpec reads the
metamodel without it. The hibernate-developer skill describes the native classes.
Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
---
.agents/skills/hibernate-developer/SKILL.md | 67 +--
.../HibernateMappingContextConfiguration.groovy | 17 +-
.../cfg/domainbinding/binder/ClassBinder.groovy | 85 ---
.../binder/ClassPropertiesBinder.groovy | 78 ---
.../domainbinding/binder/CollectionBinder.groovy | 231 --------
.../cfg/domainbinding/binder/ColumnBinder.groovy | 156 -----
.../domainbinding/binder/ComponentBinder.groovy | 128 -----
.../domainbinding/binder/ComponentUpdater.groovy | 54 --
.../domainbinding/binder/CompositeIdBinder.groovy | 82 ---
.../CompositeIdentifierToManyToOneBinder.groovy | 159 ------
.../binder/ConfiguredDiscriminatorBinder.groovy | 106 ----
.../binder/DefaultDiscriminatorBinder.groovy | 52 --
.../binder/DiscriminatorPropertyBinder.groovy | 76 ---
.../cfg/domainbinding/binder/EnumTypeBinder.groovy | 114 ----
.../binder/ForeignKeyOneToOneBinder.groovy | 79 ---
.../domainbinding/binder/GrailsDomainBinder.groovy | 321 -----------
.../binder/GrailsPropertyBinder.groovy | 116 ----
.../cfg/domainbinding/binder/IdentityBinder.groovy | 54 --
.../binder/JoinedSubClassBinder.groovy | 124 ----
.../domainbinding/binder/ManyToOneBinder.groovy | 152 -----
.../binder/NaturalIdentifierBinder.groovy | 61 --
.../cfg/domainbinding/binder/OneToOneBinder.groovy | 62 --
.../cfg/domainbinding/binder/PropertyBinder.groovy | 118 ----
.../cfg/domainbinding/binder/RootBinder.groovy | 108 ----
.../RootPersistentClassCommonValuesBinder.groovy | 111 ----
.../cfg/domainbinding/binder/SimpleIdBinder.groovy | 84 ---
.../domainbinding/binder/SimpleValueBinder.groovy | 118 ----
.../binder/SimpleValueColumnBinder.groovy | 74 ---
.../binder/SingleTableSubclassBinder.groovy | 66 ---
.../cfg/domainbinding/binder/SubClassBinder.groovy | 80 ---
.../binder/SubclassMappingBinder.groovy | 74 ---
.../binder/UnionSubclassBinder.groovy | 94 ----
.../cfg/domainbinding/binder/VersionBinder.groovy | 77 ---
.../collectionType/CollectionHolder.groovy | 59 --
.../collectionType/CollectionType.groovy | 73 ---
.../ColumnConfigToColumnBinder.groovy | 2 +-
.../{binder => column}/IndexBinder.groovy | 2 +-
.../NumericColumnConstraintsBinder.groovy | 2 +-
.../StringColumnConstraintsBinder.groovy | 2 +-
.../GrailsHibernatePersistentEntity.groovy | 7 +-
.../hibernate/HibernateBasicEnumProperty.groovy | 5 +-
.../HibernateEmbeddedCollectionProperty.groovy | 7 +-
.../hibernate/HibernateEnumProperty.groovy | 9 +-
.../hibernate/HibernateMappingBuilder.groovy | 4 +-
.../hibernate/HibernateToManyProperty.groovy | 20 +-
.../hibernate/HibernateVersionProperty.groovy | 3 +-
.../cfg/domainbinding/jpa/ConstraintFacets.groovy | 2 +-
.../jpa/GeneratedDomainClassBinder.groovy | 18 +-
.../jpa/GormMappingContributor.groovy | 114 ++++
.../domainbinding/jpa/GrailsDomainGenerator.groovy | 113 ++--
.../ManyToManyOwnerValidator.groovy | 6 +-
.../domainbinding/jpa/PropertyAccessorName.groovy | 57 ++
.../cfg/domainbinding/jpa/UniqueKeyFacets.groovy | 2 +-
.../secondpass/BasicCollectionElementBinder.groovy | 89 ---
.../BidirectionalMapElementBinder.groovy | 56 --
.../secondpass/BidirectionalOneToManyLinker.groovy | 63 ---
.../secondpass/CollectionKeyBinder.groovy | 102 ----
.../secondpass/CollectionKeyColumnUpdater.groovy | 63 ---
.../secondpass/CollectionSecondPassBinder.groovy | 106 ----
.../CollectionWithJoinTableBinder.groovy | 94 ----
.../secondpass/DependentKeyValueBinder.groovy | 61 --
.../HibernateToManyEntityOrderByBinder.groovy | 83 ---
.../domainbinding/secondpass/ListSecondPass.groovy | 47 --
.../secondpass/ListSecondPassBinder.groovy | 156 -----
.../secondpass/ManyToOneElementBinder.groovy | 53 --
.../domainbinding/secondpass/MapSecondPass.groovy | 47 --
.../secondpass/MapSecondPassBinder.groovy | 106 ----
.../secondpass/PrimaryKeyValueCreator.groovy | 57 --
.../domainbinding/secondpass/SetSecondPass.groovy | 53 --
.../ToManyEntityMultiTenantFilterBinder.groovy | 70 ---
.../UnidirectionalOneToManyBinder.groovy | 90 ---
...idirectionalOneToManyInverseValuesBinder.groovy | 47 --
.../util/DefaultColumnNameFetcher.groovy | 5 +-
.../util/GrailsPropertyResolver.groovy | 52 --
.../util/MultiTenantFilterBinder.groovy | 171 ------
.../util/NamingStrategyWrapper.groovy | 2 +-
.../domainbinding/util/OrderByClauseBuilder.groovy | 134 -----
.../util/PropertyFromValueCreator.groovy | 55 --
.../util/TableForManyCalculator.groovy | 2 +-
.../gorm/tests/HibernateGormDatastoreSpec.groovy | 68 +--
.../GrailsHibernatePersistentPropertySpec.groovy | 6 +-
.../grails/orm/hibernate/cfg/MappingSpec.groovy | 8 +-
.../grails/orm/hibernate/cfg/NaturalIdSpec.groovy | 6 +-
.../cfg/domainbinding/BasicValueCreatorSpec.groovy | 2 +-
.../CascadeBehaviorFetcherSpec.groovy | 4 +-
.../cfg/domainbinding/ClassBinderSpec.groovy | 177 ------
.../domainbinding/CollectionBinderFixtures.groovy | 87 +++
.../cfg/domainbinding/CollectionBinderSpec.groovy | 227 --------
.../CollectionForPropertyConfigBinderSpec.groovy | 77 ---
.../cfg/domainbinding/ColumnBinderFixtures.groovy | 131 +++++
.../cfg/domainbinding/ColumnBinderSpec.groovy | 626 ---------------------
.../ColumnConfigToColumnBinderSpec.groovy | 2 +-
.../cfg/domainbinding/ComponentBinderSpec.groovy | 217 -------
.../cfg/domainbinding/CompositeIdBinderSpec.groovy | 97 ----
...CompositeIdentifierToManyToOneBinderSpec.groovy | 176 ------
.../DefaultColumnNameFetcherSpec.groovy | 40 +-
.../domainbinding/EnumTypeBinderFixtures.groovy | 83 +++
.../cfg/domainbinding/EnumTypeBinderSpec.groovy | 266 ---------
.../ForeignKeyOneToOneBinderSpec.groovy | 138 -----
.../GrailsIdentityGeneratorSpec.groovy | 4 +-
.../GrailsPropertyBinderFixtures.groovy | 128 +++++
.../domainbinding/GrailsPropertyBinderSpec.groovy | 505 -----------------
.../cfg/domainbinding/IdentityBinderSpec.groovy | 83 ---
.../cfg/domainbinding/IndexBinderSpec.groovy | 2 +-
.../cfg/domainbinding/ManyToOneBinderSpec.groovy | 314 -----------
.../domainbinding/ManyToOneValuesBinderSpec.groovy | 76 ---
.../domainbinding/NamingStrategyWrapperSpec.groovy | 4 +-
.../NaturalIdentifierBinderSpec.groovy | 103 ----
.../NumericColumnConstraintsBinderSpec.groovy | 2 +-
.../cfg/domainbinding/OneToOneBinderSpec.groovy | 145 -----
.../domainbinding/OrderByClauseBuilderSpec.groovy | 182 ------
.../domainbinding/PropertyBinderFixtures.groovy | 68 +++
.../cfg/domainbinding/PropertyBinderSpec.groovy | 229 --------
.../PropertyFromValueCreatorSpec.groovy | 85 ---
.../cfg/domainbinding/SimpleIdBinderSpec.groovy | 231 --------
.../cfg/domainbinding/SimpleValueBinderSpec.groovy | 342 -----------
.../SimpleValueColumnBinderSpec.groovy | 70 ---
.../SimpleValueColumnFetcherSpec.groovy | 62 --
.../StringColumnConstraintsBinderSpec.groovy | 2 +-
.../TableForManyCalculatorSpec.groovy | 26 +-
.../cfg/domainbinding/VersionBinderFixtures.groovy | 53 ++
.../cfg/domainbinding/VersionBinderSpec.groovy | 150 -----
.../binder/ClassPropertiesBinderSpec.groovy | 111 ----
.../binder/ComponentUpdaterFixtures.groovy} | 34 +-
.../binder/ComponentUpdaterSpec.groovy | 115 ----
.../ConfiguredDiscriminatorBinderFixtures.groovy} | 20 +-
.../ConfiguredDiscriminatorBinderSpec.groovy | 195 -------
.../binder/DefaultDiscriminatorBinderSpec.groovy | 65 ---
.../DiscriminatorPropertyBinderFixtures.groovy} | 19 +-
.../binder/DiscriminatorPropertyBinderSpec.groovy | 135 -----
.../binder/JoinedSubClassBinderFixtures.groovy} | 29 +-
.../binder/JoinedSubClassBinderSpec.groovy | 105 ----
.../cfg/domainbinding/binder/RootBinderSpec.groovy | 173 ------
...rsistentClassCommonValuesBinderFixtures.groovy} | 55 +-
...ootPersistentClassCommonValuesBinderSpec.groovy | 173 ------
.../SingleTableSubclassBinderFixtures.groovy} | 34 +-
.../binder/SingleTableSubclassBinderSpec.groovy | 104 ----
.../domainbinding/binder/SubClassBinderSpec.groovy | 105 ----
.../binder/SubclassMappingBinderFixtures.groovy} | 58 +-
.../binder/SubclassMappingBinderSpec.groovy | 173 ------
.../binder/UnionSubclassBinderFixtures.groovy} | 30 +-
.../binder/UnionSubclassBinderSpec.groovy | 88 ---
.../collectionType/BagCollectionTypeSpec.groovy | 63 ---
.../collectionType/CollectionHolderSpec.groovy | 53 --
.../collectionType/ListCollectionTypeSpec.groovy | 63 ---
.../collectionType/MapCollectionTypeSpec.groovy | 63 ---
.../collectionType/SetCollectionTypeSpec.groovy | 98 ----
.../SortedSetCollectionTypeSpec.groovy | 63 ---
.../GrailsSequenceStyleGeneratorSpec.groovy | 12 +-
.../generator/GrailsTableGeneratorSpec.groovy | 6 +-
.../hibernate/HibernateBasicPropertySpec.groovy | 4 +-
.../HibernateEmbeddedCollectionPropertySpec.groovy | 2 +-
.../HibernateManyToManyPropertySpec.groovy | 6 +-
.../HibernateOneToManyPropertySpec.groovy | 4 +-
.../hibernate/HibernatePersistentEntitySpec.groovy | 2 +-
.../hibernate/HibernateToManyPropertySpec.groovy | 80 +--
.../GrailsDomainGeneratorDifferentialSpec.groovy | 30 +-
.../jpa/GrailsDomainGeneratorSpec.groovy | 10 +-
.../jpa/GrailsDomainGeneratorSupport.groovy | 8 +-
.../jpa/GrailsDomainGeneratorTenantSpec.groovy | 8 +-
.../jpa/PropertyAccessorNameSpec.groovy | 73 +++
.../BasicCollectionElementBinderFixtures.groovy | 95 ++++
.../BasicCollectionElementBinderSpec.groovy | 271 ---------
.../BasicCollectionKeyPersistenceSpec.groovy | 6 +-
.../BidirectionalMapElementBinderFixtures.groovy} | 34 +-
.../BidirectionalMapElementBinderSpec.groovy | 102 ----
.../BidirectionalOneToManyLinkerSpec.groovy | 79 ---
.../secondpass/CollectionKeyBinderFixtures.groovy | 94 ++++
.../secondpass/CollectionKeyBinderSpec.groovy | 289 ----------
.../CollectionKeyColumnUpdaterFixtures.groovy} | 43 +-
.../CollectionKeyColumnUpdaterSpec.groovy | 141 -----
.../CollectionSecondPassBinderFixtures.groovy | 117 ++++
.../CollectionSecondPassBinderSpec.groovy | 390 -------------
.../CollectionWithJoinTableBinderFixtures.groovy} | 27 +-
.../CollectionWithJoinTableBinderSpec.groovy | 177 ------
.../DependentKeyValueBinderFixtures.groovy | 59 ++
.../secondpass/DependentKeyValueBinderSpec.groovy | 131 -----
...bernateToManyEntityOrderByBinderFixtures.groovy | 67 +++
.../HibernateToManyEntityOrderByBinderSpec.groovy | 218 -------
.../secondpass/ListSecondPassBinderFixtures.groovy | 91 +++
.../secondpass/ListSecondPassBinderSpec.groovy | 323 -----------
.../ManyToOneElementBinderFixtures.groovy} | 34 +-
.../secondpass/ManyToOneElementBinderSpec.groovy | 106 ----
.../secondpass/MapSecondPassBinderFixtures.groovy} | 33 +-
.../secondpass/MapSecondPassBinderSpec.groovy | 465 ---------------
.../secondpass/PrimaryKeyValueCreatorSpec.groovy | 102 ----
...anyEntityMultiTenantFilterBinderFixtures.groovy | 78 +++
.../ToManyEntityMultiTenantFilterBinderSpec.groovy | 191 -------
.../UnidirectionalOneToManyBinderFixtures.groovy} | 30 +-
.../UnidirectionalOneToManyBinderSpec.groovy | 162 ------
...nalOneToManyInverseValuesBinderFixtures.groovy} | 34 +-
...ectionalOneToManyInverseValuesBinderSpec.groovy | 105 ----
.../util/GrailsPropertyResolverSpec.groovy | 101 ----
.../util/MultiTenantFilterBinderSpec.groovy | 196 -------
.../MultiTenantFilterDefinitionBinderSpec.groovy | 2 +-
.../src/test/resources/simplelogger.properties | 1 -
196 files changed, 1999 insertions(+), 15917 deletions(-)
diff --git a/.agents/skills/hibernate-developer/SKILL.md b/.agents/skills/hibernate-developer/SKILL.md
index ae3197ba97..a1e8a46160 100644
--- a/.agents/skills/hibernate-developer/SKILL.md
+++ b/.agents/skills/hibernate-developer/SKILL.md
@@ -12,9 +12,9 @@ Licensed to the Apache Software Foundation (ASF) under one or more contributor l
## What I Do
- Provide repository-specific guidance for the `grails-data-hibernate7` project.
-- Guide changes around `GrailsDomainBinder`, `GrailsPropertyBinder`, `IdentityBinder`, `VersionBinder`, collection binders, and related utilities.
+- Guide changes around native domain binding: `GrailsDomainGenerator`, `GeneratedDomainClassBinder`, `GormMappingContributor`, the metamodel under `domainbinding.hibernate`, the column helpers and the identifier generators.
- Keep changes aligned with the testing constraints used by the Hibernate 7 modules in this repository.
-- Help with migration work inside this framework module (e.g., porting domain-binding behaviour from H5 to H7, updating binder internals, fixing H7 regressions). Does not cover user-facing application migration guides; those belong in `grails-doc`.
+- Help with migration work inside this framework module (e.g., closing a gap of native binding against what the classic binding of Grails 8 did, updating the metamodel, fixing H7 regressions). Does not cover user-facing application migration guides; those belong in `grails-doc`.
## When to Use Me
@@ -30,57 +30,44 @@ Activate this skill when working on the Hibernate 7 module, especially for:
This skill is for the Grails framework's Hibernate 7 integration module, not for a Grails application. Prefer guidance from this skill over generic Grails app patterns when working in `grails-data-hibernate7`.
-`GrailsDomainBinder` is the main entry point for binding Grails domain classes to Hibernate metadata. Changes often ripple through:
+Native domain binding is the only binding: `GrailsDomainGenerator` generates a JPA-annotated class for every GORM entity from the mapping model, Hibernate's own annotation binder binds those classes, and `GeneratedDomainClassBinder` aligns the bound model with what the mapping asks for and points the bound entities at the real domain classes. The classic binder of Grails 8, which built Hibernate's boot model by hand, was removed in 9.0.x; its behaviour is recorded in `core/src/test/resou [...]
-- `org.grails.orm.hibernate.cfg`
-- `org.grails.orm.hibernate.cfg.domainbinding`
-- `org.grails.orm.hibernate.cfg.domainbinding.collectionType`
-- `org.grails.orm.hibernate.cfg.domainbinding.secondpass`
-- `org.grails.orm.hibernate.cfg.domainbinding.generator`
+- `org.grails.orm.hibernate.cfg` (the mapping DSL and its model)
+- `org.grails.orm.hibernate.cfg.domainbinding.hibernate` (the metamodel the generator reads)
+- `org.grails.orm.hibernate.cfg.domainbinding.jpa` (the generator, the facets it decides, the aligner)
+- `org.grails.orm.hibernate.cfg.domainbinding.column` and `.util` (column and naming helpers)
+- `org.grails.orm.hibernate.cfg.domainbinding.generator` (identifier generators)
## Key Classes and Responsibilities
-### Main Binding Flow
+### Binding Flow
-- `GrailsDomainBinder`: central coordinator for Hibernate 7 mapping contribution.
-- `GrailsPropertyBinder`: main coordinator for converting persistent properties into Hibernate `Value` instances.
-- `PropertyFromValueCreator`: shared utility for creating Hibernate `Property` instances from a bound `Value`.
+- `HibernateMappingContextConfiguration`: builds the session factory; registers `GormMappingContributor` as the first `AdditionalMappingContributor` and `GeneratedDomainClassBinder` as a `SessionFactoryBuilderFactory`.
+- `GormMappingContributor`: hands the entities of a data source to Hibernate; resolves the naming strategy (`NamingStrategyWrapper`) against the JDBC environment.
+- `GeneratedDomainClassBinder`: generates the classes, binds them with Hibernate's annotation binder, installs the GORM identifier generators and the tenant filter, aligns discriminators, unique keys, join columns and collection tables, then switches the class loader service to the real classes.
+- `GrailsDomainGenerator`: decides the facets (`*Facets` records) of every entity and property and emits the annotated class with Byte Buddy. A mapping it cannot describe is refused by name with an `UnsupportedOperationException` that says what to change.
-### Identifier and Version Binding
+### Metamodel
-- `IdentityBinder`: coordinates identifier binding.
-- `SimpleIdBinder`: handles simple identifiers.
-- `CompositeIdBinder`: handles composite identifiers.
-- `VersionBinder`: binds optimistic locking version properties.
-- `NaturalIdentifierBinder`: binds `naturalId` properties.
+- `GrailsHibernatePersistentEntity`, `HibernatePersistentProperty` and the `Hibernate*Property` types: the GORM mapping model with the Hibernate-specific reads the generator needs (column names, join tables, cascade, lazy, the tenant id).
+- `HibernateMappingBuilder`, `Mapping`, `PropertyConfig`, `ColumnConfig`: the mapping DSL and its model.
-### Associations and Collections
+### Column and Naming Helpers
-- `OneToOneBinder`, `ManyToOneBinder`, `ManyToOneValuesBinder`: association binding.
-- `CollectionBinder`: collection mapping.
-- `CollectionSecondPassBinder`, `ListSecondPassBinder`, `MapSecondPassBinder`: second-pass association and collection binding.
-- `CollectionHolder` plus the collection type classes: carry collection metadata through binding.
-
-### Value and Column Binding
-
-- `SimpleValueBinder`: binds simple properties.
-- `SimpleValueColumnBinder`: binds columns to simple values.
-- `ComponentBinder`, `ComponentPropertyBinder`: embedded/component binding.
-- `EnumTypeBinder`: enum mapping.
+- `ColumnConfigToColumnBinder`, `StringColumnConstraintsBinder`, `NumericColumnConstraintsBinder`, `IndexBinder` (`domainbinding.column`): apply a column config to a Hibernate `Column`; the generator and the aligner share them.
+- `DefaultColumnNameFetcher`, `ColumnNameForPropertyAndPathFetcher`, `TableForManyCalculator`, `NamingStrategyWrapper`, `BackticksRemover`, `CascadeBehaviorFetcher`, `CreateKeyForProps`, `UniqueNameGenerator` (`domainbinding.util`).
### Generators
-- `BasicValueCreator`: creates identifier values and generators.
-- `GrailsSequenceWrapper`, `GrailsSequenceGeneratorEnum`: generator integration helpers.
-- `GrailsIdentityGenerator`, `GrailsIncrementGenerator`, `GrailsNativeGenerator`, `GrailsSequenceStyleGenerator`, `GrailsTableGenerator`: Grails-specific Hibernate 7 generator implementations.
+- `GrailsIdentityGenerator`, `GrailsIncrementGenerator`, `GrailsNativeGenerator`, `GrailsSequenceStyleGenerator`, `GrailsTableGenerator`: Grails-specific Hibernate 7 generator implementations the generated classes name through `@GrailsIdGenerator`; `GrailsSequenceWrapper`, `BasicValueCreator` and `GeneratorCreationContextWrapper` install them.
## Current Module Guidance
Keep these module-specific expectations in mind:
-- `GrailsPropertyBinder` has already been simplified to a unified binder-dispatch structure. Preserve that consolidation instead of reintroducing scattered property creation or ad hoc branching.
-- Property creation and addition should stay centralized through callers using `PropertyFromValueCreator` where applicable.
-- Utility classes in `domainbinding.util` should prefer Hibernate-aware GORM types internally, but public signatures may still need base interfaces when Spock mocks require them.
+- A mapping option the generator does not state is a gap, not a refusal: native binding must not refuse a mapping the classic binding of Grails 8 accepted (the manual's "Mappings Native Binding Refuses" lists the only exceptions). Add the facet, state it on the generated class, and prove it with a spec that boots a datastore.
+- Utility classes in `domainbinding.util` and `domainbinding.column` should prefer Hibernate-aware GORM types internally, but public signatures may still need base interfaces when Spock mocks require them.
+- A new `@Entity` fixture in the core test tree is scanned by the differential specs and needs its records in the classic oracle (see the README for how to record them).
- `GrailsIncrementGenerator` still contains reflection-based Hibernate 7 compatibility workarounds; avoid broad refactors unless the change explicitly addresses that area.
## Testing Rules
@@ -95,9 +82,9 @@ When touching `grails-data-hibernate7`, test through real Hibernate wiring rathe
## Change Workflow
-1. Identify which binder, creator, generator, fetcher, or second-pass class owns the behavior.
-2. Trace whether the change affects only `Value` creation, `Property` creation, or both.
-3. Preserve the existing separation between logical mapping decisions and Hibernate object construction.
+1. Identify which facet of `GrailsDomainGenerator`, which alignment of `GeneratedDomainClassBinder`, or which helper owns the behavior.
+2. Trace whether the change affects what the generated class states, what the aligner changes on the bound model, or both.
+3. Preserve the existing separation between the mapping decisions (facets) and the emission of the annotated class.
4. Update or add specs in `grails-data-hibernate7` that exercise the affected behavior through the public Hibernate-backed path.
5. Run the relevant Hibernate 7 module tests, and expand test coverage when binder flow or entity registration behavior changes.
@@ -110,7 +97,7 @@ When touching `grails-data-hibernate7`, test through real Hibernate wiring rathe
## Known Status and Constraints
-- The Hibernate 7 binder migration is complete: all main binders, collection types, second-pass binders, generators, and utilities have been migrated.
+- Native domain binding is the only binding since 9.0.x; the generator describes every mapping the classic binding of Grails 8 could boot.
- `GrailsIncrementGenerator` retains reflection-based workarounds for accessing Hibernate 7 internals; avoid broad refactors in that class unless explicitly targeting that area.
## Source of Truth
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/HibernateMappingContextConfiguration.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/HibernateMappingContextConfiguration.groovy
index bf46fb0685..35d938819d 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/HibernateMappingContextConfiguration.groovy
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/HibernateMappingContextConfiguration.groovy
@@ -66,10 +66,10 @@ import org.grails.orm.hibernate.EventListenerIntegrator
import org.grails.orm.hibernate.GrailsSessionContext
import org.grails.orm.hibernate.HibernateEventListeners
import org.grails.orm.hibernate.MetadataIntegrator
-import org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsDomainBinder
import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentEntity
import org.grails.orm.hibernate.cfg.domainbinding.jpa.GeneratedDomainClassBinder
import org.grails.orm.hibernate.cfg.domainbinding.jpa.GeneratedDomainClassLoaderService
+import org.grails.orm.hibernate.cfg.domainbinding.jpa.GormMappingContributor
import org.grails.orm.hibernate.cfg.domainbinding.util.NamingStrategyProvider
import org.grails.orm.hibernate.proxy.GrailsBytecodeProvider
@@ -320,8 +320,7 @@ class HibernateMappingContextConfiguration extends Configuration
}
final GeneratedDomainClassBinder generatedBinder = new GeneratedDomainClassBinder(dataSourceName, appClassLoader)
- final GrailsDomainBinder domainBinder = new GrailsDomainBinder(
- dataSourceName,
+ final GormMappingContributor contributor = new GormMappingContributor(
sessionFactoryBeanName,
persistentEntities,
namingStrategyProvider,
@@ -332,7 +331,7 @@ class HibernateMappingContextConfiguration extends Configuration
// the mappings are bound against the generated classes; once they are bound, the same names resolve to the real ones
GeneratedDomainClassLoaderService classLoaderService = new GeneratedDomainClassLoaderService(
- newClassLoaderService(generatedBinder.classLoader, domainBinder, generatedBinder),
+ newClassLoaderService(generatedBinder.classLoader, contributor, generatedBinder),
new ClassLoaderServiceImpl(appClassLoader))
generatedBinder.classLoaderService = classLoaderService
EventListenerIntegrator eventListenerIntegrator =
@@ -378,18 +377,18 @@ class HibernateMappingContextConfiguration extends Configuration
}
private static ClassLoaderService newClassLoaderService(
- ClassLoader classLoader, GrailsDomainBinder domainBinder, GeneratedDomainClassBinder generatedBinder) {
+ ClassLoader classLoader, GormMappingContributor contributor, GeneratedDomainClassBinder generatedBinder) {
return new ClassLoaderServiceImpl(classLoader) {
@Override
<S> Collection<S> loadJavaServices(Class<S> serviceContract) {
// Ensure Grails contributes mappings for GORM entities even if they lack JPA @Entity
if (AdditionalMappingContributor.isAssignableFrom(serviceContract)) {
- // Include the GrailsDomainBinder first, then any other contributors
+ // Include GORM's contributor first, then any other contributors
// discovered by the parent classloader (e.g., Envers AdditionalMappingContributorImpl).
// Without this, Envers' AdditionalMappingContributor would be excluded,
// preventing EnversService from being initialized before EnversIntegrator runs.
Collection<S> parentContributors = super.loadJavaServices(serviceContract)
- S grailsBinder = (S) domainBinder
+ S grailsBinder = (S) contributor
List<S> allContributors = new ArrayList<>(parentContributors.size() + 1)
allContributors.add(grailsBinder)
allContributors.addAll(parentContributors)
@@ -412,8 +411,8 @@ class HibernateMappingContextConfiguration extends Configuration
ClassLoader storedClassLoader = classLoaderObject instanceof ClassLoader ?
(ClassLoader) classLoaderObject : getClass().classLoader
// addProperties() or a custom configClass may have replaced CLASSLOADERS after the
- // setters ran. GrailsDomainBinder binds entities by class name and Hibernate resolves
- // them through this loader, so it has to see the restarted application classes.
+ // setters ran. The entities are bound by class name and Hibernate resolves them
+ // through this loader, so it has to see the restarted application classes.
return DevToolsClassLoaders.preferRestartClassLoader(storedClassLoader)
}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ClassBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ClassBinder.groovy
deleted file mode 100644
index b00094d5f1..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ClassBinder.groovy
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import jakarta.annotation.Nonnull
-import org.hibernate.boot.spi.InFlightMetadataCollector
-import org.hibernate.mapping.PersistentClass
-
-import org.grails.orm.hibernate.cfg.Mapping
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity
-
-import static org.grails.orm.hibernate.cfg.GrailsHibernateUtil.unqualify
-
-/**
- * Binds a Grails domain class to the Hibernate persistent class model.
- *
- * @since 8.0
- */
-@CompileStatic
-class ClassBinder {
-
- private final InFlightMetadataCollector collector
-
- ClassBinder(@Nonnull InFlightMetadataCollector collector) {
- this.collector = collector
- }
-
- /**
- * Binds the specified persistent class to the runtime model based on the properties defined in
- * the domain class
- *
- * @param persistentEntity The Grails domain class
- * @param persistentClass The persistent class
- */
- void bindClass(@Nonnull GrailsHibernatePersistentEntity persistentEntity, PersistentClass persistentClass) {
- persistentClass.lazy = true
- String entityName = persistentEntity.name
- persistentClass.entityName = entityName
- persistentClass.jpaEntityName = entityName
- persistentClass.proxyInterfaceName = entityName
- persistentClass.className = entityName
- persistentClass.setAbstract(persistentEntity.isAbstract())
-
- Mapping mappedForm = persistentEntity.hibernateMappedForm
- boolean autoImport
- if (mappedForm != null) {
- autoImport = mappedForm.autoImport
- persistentClass.dynamicInsert = mappedForm.dynamicInsert
- persistentClass.dynamicUpdate = mappedForm.dynamicUpdate
- persistentClass.batchSize = mappedForm.batchSize != null ? mappedForm.batchSize : 0
- } else {
- autoImport =
- collector.metadataBuildingOptions.mappingDefaults.isAutoImportEnabled()
- persistentClass.dynamicInsert = false
- persistentClass.dynamicUpdate = false
- persistentClass.batchSize = 0
- }
- persistentClass.selectBeforeUpdate = false
- persistentEntity.persistentClass = persistentClass
-
- if (autoImport) {
- String unqualified = unqualify(entityName)
- persistentClass.jpaEntityName = unqualified
- collector.addImport(unqualified, entityName)
- }
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ClassPropertiesBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ClassPropertiesBinder.groovy
deleted file mode 100644
index 6f89f86596..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ClassPropertiesBinder.groovy
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import org.hibernate.MappingException
-import org.hibernate.mapping.PersistentClass
-import org.hibernate.mapping.Table
-import org.hibernate.mapping.Value
-
-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.util.PropertyFromValueCreator
-
-/**
- * Binds the properties of a Grails domain class to the Hibernate meta-model.
- *
- * @since 8.0
- */
-@CompileStatic
-@SuppressWarnings('PMD.DataflowAnomalyAnalysis')
-class ClassPropertiesBinder {
-
- private final GrailsPropertyBinder grailsPropertyBinder
- private final PropertyFromValueCreator propertyFromValueCreator
- private final NaturalIdentifierBinder naturalIdentifierBinder
-
- ClassPropertiesBinder(
- GrailsPropertyBinder grailsPropertyBinder,
- PropertyFromValueCreator propertyFromValueCreator,
- NaturalIdentifierBinder naturalIdentifierBinder) {
- this.grailsPropertyBinder = grailsPropertyBinder
- this.propertyFromValueCreator = propertyFromValueCreator
- this.naturalIdentifierBinder = naturalIdentifierBinder
- }
-
- ClassPropertiesBinder(
- GrailsPropertyBinder grailsPropertyBinder, PropertyFromValueCreator propertyFromValueCreator) {
- this(grailsPropertyBinder, propertyFromValueCreator, new NaturalIdentifierBinder())
- }
-
- void bindClassProperties(HibernatePersistentEntity hibernatePersistentEntity) {
- PersistentClass persistentClass = hibernatePersistentEntity.persistentClass
- getTable(persistentClass).comment = hibernatePersistentEntity.comment
- for (HibernatePersistentProperty currentGrailsProp :
- hibernatePersistentEntity.persistentPropertiesToBind) {
- Value value = grailsPropertyBinder.bindProperty(currentGrailsProp, null, GrailsDomainBinder.EMPTY_PATH)
- persistentClass.addProperty(propertyFromValueCreator.createProperty(value, currentGrailsProp))
- }
-
- naturalIdentifierBinder.bindNaturalIdentifier(hibernatePersistentEntity, persistentClass)
- }
-
- private Table getTable(PersistentClass persistentClass) {
- if (persistentClass.table == null) {
- throw new MappingException(
- "Persistent class [${persistentClass.entityName}] does not have a table associated with it".toString())
- }
- return persistentClass.table
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CollectionBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CollectionBinder.groovy
deleted file mode 100644
index 7734e4a21b..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CollectionBinder.groovy
+++ /dev/null
@@ -1,231 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import org.hibernate.boot.spi.InFlightMetadataCollector
-import org.hibernate.boot.spi.MetadataBuildingContext
-import org.hibernate.mapping.Collection
-import org.hibernate.mapping.OneToMany
-
-import org.grails.orm.hibernate.cfg.ColumnConfig
-import org.grails.orm.hibernate.cfg.JoinTable
-import org.grails.orm.hibernate.cfg.PersistentEntityNamingStrategy
-import org.grails.orm.hibernate.cfg.PropertyConfig
-import org.grails.orm.hibernate.cfg.domainbinding.collectionType.CollectionHolder
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateAssociation
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateManyToManyProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyEntityProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyProperty
-import org.grails.orm.hibernate.cfg.domainbinding.secondpass.BasicCollectionElementBinder
-import org.grails.orm.hibernate.cfg.domainbinding.secondpass.BidirectionalMapElementBinder
-import org.grails.orm.hibernate.cfg.domainbinding.secondpass.BidirectionalOneToManyLinker
-import org.grails.orm.hibernate.cfg.domainbinding.secondpass.CollectionKeyBinder
-import org.grails.orm.hibernate.cfg.domainbinding.secondpass.CollectionKeyColumnUpdater
-import org.grails.orm.hibernate.cfg.domainbinding.secondpass.CollectionSecondPassBinder
-import org.grails.orm.hibernate.cfg.domainbinding.secondpass.CollectionWithJoinTableBinder
-import org.grails.orm.hibernate.cfg.domainbinding.secondpass.DependentKeyValueBinder
-import org.grails.orm.hibernate.cfg.domainbinding.secondpass.HibernateToManyEntityOrderByBinder
-import org.grails.orm.hibernate.cfg.domainbinding.secondpass.ListSecondPass
-import org.grails.orm.hibernate.cfg.domainbinding.secondpass.ListSecondPassBinder
-import org.grails.orm.hibernate.cfg.domainbinding.secondpass.ManyToOneElementBinder
-import org.grails.orm.hibernate.cfg.domainbinding.secondpass.MapSecondPass
-import org.grails.orm.hibernate.cfg.domainbinding.secondpass.MapSecondPassBinder
-import org.grails.orm.hibernate.cfg.domainbinding.secondpass.PrimaryKeyValueCreator
-import org.grails.orm.hibernate.cfg.domainbinding.secondpass.SetSecondPass
-import org.grails.orm.hibernate.cfg.domainbinding.secondpass.ToManyEntityMultiTenantFilterBinder
-import org.grails.orm.hibernate.cfg.domainbinding.secondpass.UnidirectionalOneToManyBinder
-import org.grails.orm.hibernate.cfg.domainbinding.secondpass.UnidirectionalOneToManyInverseValuesBinder
-import org.grails.orm.hibernate.cfg.domainbinding.util.DefaultColumnNameFetcher
-import org.grails.orm.hibernate.cfg.domainbinding.util.GrailsPropertyResolver
-import org.grails.orm.hibernate.cfg.domainbinding.util.SimpleValueColumnFetcher
-import org.grails.orm.hibernate.cfg.domainbinding.util.TableForManyCalculator
-
-/**
- * Handles the binding of collections to the Hibernate runtime meta model.
- *
- * @since 8.0
- */
-@CompileStatic
-@SuppressWarnings('PMD.DataflowAnomalyAnalysis')
-class CollectionBinder {
-
- private final MetadataBuildingContext metadataBuildingContext
- private final CollectionHolder collectionHolder
- private final ListSecondPassBinder listSecondPassBinder
- private final CollectionSecondPassBinder collectionSecondPassBinder
- final MapSecondPassBinder mapSecondPassBinder
- private final InFlightMetadataCollector mappings
- private final TableForManyCalculator tableForManyCalculator
- private final ManyToManyOwnerValidator manyToManyOwnerValidator = new ManyToManyOwnerValidator()
-
- void setComponentBinder(ComponentBinder componentBinder) {
- this.collectionSecondPassBinder.setComponentBinder(componentBinder)
- }
-
- CollectionBinder(
- MetadataBuildingContext metadataBuildingContext,
- PersistentEntityNamingStrategy namingStrategy,
- SimpleValueBinder simpleValueBinder,
- EnumTypeBinder enumTypeBinder,
- ManyToOneBinder manyToOneBinder,
- CompositeIdentifierToManyToOneBinder compositeIdentifierToManyToOneBinder,
- SimpleValueColumnFetcher simpleValueColumnFetcher,
- CollectionHolder collectionHolder,
- InFlightMetadataCollector mappings,
- TableForManyCalculator tableForManyCalculator) {
- this.metadataBuildingContext = metadataBuildingContext
- this.collectionHolder = collectionHolder
- this.mappings = mappings
- this.tableForManyCalculator = tableForManyCalculator
- GrailsPropertyResolver grailsPropertyResolver = new GrailsPropertyResolver()
- CollectionForPropertyConfigBinder collectionForPropertyConfigBinder = new CollectionForPropertyConfigBinder()
- UnidirectionalOneToManyInverseValuesBinder unidirectionalOneToManyInverseValuesBinder =
- new UnidirectionalOneToManyInverseValuesBinder(metadataBuildingContext)
- SimpleValueColumnBinder simpleValueColumnBinder = new SimpleValueColumnBinder()
- CollectionWithJoinTableBinder collectionWithJoinTableBinder = new CollectionWithJoinTableBinder(
- namingStrategy,
- unidirectionalOneToManyInverseValuesBinder,
- compositeIdentifierToManyToOneBinder,
- collectionForPropertyConfigBinder,
- simpleValueColumnBinder,
- new BasicCollectionElementBinder(
- metadataBuildingContext,
- namingStrategy,
- enumTypeBinder,
- simpleValueColumnBinder,
- simpleValueColumnFetcher,
- new ColumnConfigToColumnBinder()))
- this.collectionSecondPassBinder = new CollectionSecondPassBinder(
- new CollectionKeyColumnUpdater(new CollectionKeyBinder(
- new BidirectionalOneToManyLinker(grailsPropertyResolver),
- new DependentKeyValueBinder(simpleValueBinder, compositeIdentifierToManyToOneBinder),
- simpleValueColumnBinder,
- new PrimaryKeyValueCreator(metadataBuildingContext))),
- new UnidirectionalOneToManyBinder(collectionWithJoinTableBinder, mappings),
- collectionWithJoinTableBinder,
- new BidirectionalMapElementBinder(manyToOneBinder, collectionForPropertyConfigBinder),
- new ManyToOneElementBinder(manyToOneBinder, collectionForPropertyConfigBinder),
- new HibernateToManyEntityOrderByBinder(),
- new ToManyEntityMultiTenantFilterBinder(new DefaultColumnNameFetcher(namingStrategy))
- )
- this.listSecondPassBinder = new ListSecondPassBinder(
- metadataBuildingContext, namingStrategy, collectionSecondPassBinder, simpleValueColumnBinder, mappings)
- this.mapSecondPassBinder = new MapSecondPassBinder(
- metadataBuildingContext,
- namingStrategy,
- collectionSecondPassBinder,
- simpleValueColumnBinder,
- new ColumnConfigToColumnBinder(),
- simpleValueColumnFetcher)
- }
-
- /**
- * First pass to bind collection to Hibernate metamodel, sets up second pass
- *
- * @param property The GrailsDomainClassProperty instance
- * @param path The property path
- * @return the result
- */
- Collection bindCollection(HibernateToManyProperty property, String path) {
- Collection collection = collectionHolder.create(property)
- property.setCollection(collection, path)
-
- if (property.shouldBindWithForeignKey()) {
- bindOneToManyElement((HibernateToManyEntityProperty) property, collection)
- } else {
- bindCollectionTable(property, collection)
- }
-
- registerSecondPass(property, collection)
-
- mappings.addCollectionBinding(collection)
-
- return collection
- }
-
- private void bindOneToManyElement(HibernateToManyEntityProperty property, Collection collection) {
- OneToMany oneToMany = new OneToMany(metadataBuildingContext, collection.owner)
- oneToMany.referencedEntityName = property.hibernateAssociatedEntity.name
- oneToMany.ignoreNotFound = true
- collection.element = oneToMany
- }
-
- /**
- * A bidirectional many-to-many has one join table, and the owning side is the one that writes it. When
- * the owning side names that table, the inverse side adopts the name, schema, catalog and column names
- * (its key is the owner's column and its column is the owner's key) unless it configures its own.
- */
- private void inheritOwningJoinTable(HibernateToManyProperty property) {
- if (!(property instanceof HibernateManyToManyProperty) || !property.isBidirectional() || property.isOwningSide()) {
- return
- }
- PropertyConfig config = property.hibernateMappedForm
- JoinTable own = config.joinTable
- if (own != null && own.name != null) {
- return
- }
- HibernateAssociation owningSide = property.hibernateInverseSide
- PropertyConfig owningConfig = owningSide instanceof HibernateManyToManyProperty ?
- ((HibernateManyToManyProperty) owningSide).hibernateMappedForm : null
- JoinTable owner = owningConfig == null ? null : owningConfig.joinTable
- if (owner == null || owner.name == null) {
- return
- }
- JoinTable inherited = own == null ? new JoinTable() : own
- inherited.name = owner.name
- if (inherited.schema == null) {
- inherited.schema = owner.schema
- }
- if (inherited.catalog == null) {
- inherited.catalog = owner.catalog
- }
- if ((inherited.keys == null || inherited.keys.isEmpty()) && owner.column != null) {
- inherited.keys = [owner.column]
- }
- List<ColumnConfig> ownerKeys = owner.keys
- if (inherited.column == null && ownerKeys != null && ownerKeys.size() == 1) {
- inherited.column = ownerKeys.get(0)
- }
- config.joinTable = inherited
- }
-
- private void bindCollectionTable(HibernateToManyProperty property, Collection collection) {
- inheritOwningJoinTable(property)
- manyToManyOwnerValidator.validate(property)
- String tableName = tableForManyCalculator.getTableName(property)
- String schemaName = tableForManyCalculator.getJoinTableSchema(property)
- String catalogName = tableForManyCalculator.getJoinTableCatalog(property)
-
- collection.collectionTable =
- mappings.addTable(schemaName, catalogName, tableName, null, false, metadataBuildingContext, false)
- collection.inverse = property.isBidirectional() && !property.isOwningSide()
- }
-
- private void registerSecondPass(HibernateToManyProperty property, Collection collection) {
- if (collection instanceof org.hibernate.mapping.List) {
- mappings.addSecondPass(new ListSecondPass(listSecondPassBinder, property))
- } else if (collection instanceof org.hibernate.mapping.Map) {
- mappings.addSecondPass(new MapSecondPass(mapSecondPassBinder, property))
- } else {
- mappings.addSecondPass(new SetSecondPass(collectionSecondPassBinder, property))
- }
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ColumnBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ColumnBinder.groovy
deleted file mode 100644
index 8c7bf6630b..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ColumnBinder.groovy
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import org.hibernate.dialect.Dialect
-import org.hibernate.mapping.Column
-import org.hibernate.mapping.Table
-import org.slf4j.Logger
-import org.slf4j.LoggerFactory
-
-import org.grails.orm.hibernate.cfg.ColumnConfig
-import org.grails.orm.hibernate.cfg.Mapping
-import org.grails.orm.hibernate.cfg.PersistentEntityNamingStrategy
-import org.grails.orm.hibernate.cfg.PropertyConfig
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateAssociation
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty
-import org.grails.orm.hibernate.cfg.domainbinding.util.BackticksRemover
-import org.grails.orm.hibernate.cfg.domainbinding.util.ColumnNameForPropertyAndPathFetcher
-import org.grails.orm.hibernate.cfg.domainbinding.util.CreateKeyForProps
-import org.grails.orm.hibernate.cfg.domainbinding.util.DefaultColumnNameFetcher
-
-/**
- * Binds a {@link org.hibernate.mapping.Column} to the Hibernate meta-model from Grails property and column config.
- *
- * @since 8.0
- */
-@CompileStatic
-@SuppressWarnings(['PMD.NullAssignment', 'PMD.DataflowAnomalyAnalysis'])
-class ColumnBinder {
-
- private static final Logger LOG = LoggerFactory.getLogger(ColumnBinder)
-
- private final ColumnNameForPropertyAndPathFetcher columnNameForPropertyAndPathFetcher
- private final StringColumnConstraintsBinder stringColumnConstraintsBinder
- private final NumericColumnConstraintsBinder numericColumnConstraintsBinder
- private final CreateKeyForProps createKeyForProps
- private final IndexBinder indexBinder
-
- /** Public constructor that accepts all collaborators. */
- ColumnBinder(
- ColumnNameForPropertyAndPathFetcher columnNameForPropertyAndPathFetcher,
- StringColumnConstraintsBinder stringColumnConstraintsBinder,
- NumericColumnConstraintsBinder numericColumnConstraintsBinder,
- CreateKeyForProps createKeyForProps,
- IndexBinder indexBinder) {
- this.columnNameForPropertyAndPathFetcher = columnNameForPropertyAndPathFetcher
- this.stringColumnConstraintsBinder = stringColumnConstraintsBinder
- this.numericColumnConstraintsBinder = numericColumnConstraintsBinder
- this.createKeyForProps = createKeyForProps
- this.indexBinder = indexBinder
- }
-
- ColumnBinder(PersistentEntityNamingStrategy namingStrategy, Dialect dialect) {
- this(
- new ColumnNameForPropertyAndPathFetcher(
- namingStrategy, new DefaultColumnNameFetcher(namingStrategy), new BackticksRemover()),
- new StringColumnConstraintsBinder(),
- new NumericColumnConstraintsBinder(dialect),
- new CreateKeyForProps(new ColumnNameForPropertyAndPathFetcher(
- namingStrategy, new DefaultColumnNameFetcher(namingStrategy), new BackticksRemover())),
- new IndexBinder())
- }
-
- /**
- * Binds a Column instance to the Hibernate meta model
- *
- * @param property The Grails domain class property
- * @param parentProperty parent property
- * @param column The column to bind
- * @param path the path
- * @param table The table name
- * @param typeName the property's resolved Hibernate type name
- */
- void bindColumn(
- HibernatePersistentProperty property,
- HibernatePersistentProperty parentProperty,
- Column column,
- ColumnConfig cc,
- String path,
- Table table,
- String typeName) {
-
- if (cc != null) {
- column.comment = cc.comment
- column.defaultValue = cc.defaultValue
- column.customRead = cc.read
- column.customWrite = cc.write
- }
-
- Class<?> userType = property.userType
- String columnName = columnNameForPropertyAndPathFetcher.getColumnNameForPropertyAndPath(property, path, cc)
- if ((property instanceof HibernateAssociation) && userType == null) {
- HibernateAssociation assoc = (HibernateAssociation) property
- // Only use conventional naming when the column has not been explicitly mapped.
- if (column.name == null) {
- column.name = columnName
- }
- column.nullable = assoc.isAssociationColumnNullable()
- } else {
- column.name = columnName
- column.nullable = property.isNullable() || (parentProperty != null && parentProperty.isNullable())
- // Use the constraints for this property to more accurately define
- // the column's length, precision, and scale
- Class<?> type = property.type
- if (type != null && (String.isAssignableFrom(type) || byte[].class.isAssignableFrom(type))) {
- PropertyConfig mappedForm = property.hibernateMappedForm
- stringColumnConstraintsBinder.bindStringColumnConstraints(column, mappedForm, typeName)
- } else if (type != null && Number.isAssignableFrom(type)) {
- PropertyConfig mappedForm = property.hibernateMappedForm
- numericColumnConstraintsBinder.bindNumericColumnConstraints(column, cc, mappedForm, type)
- }
- }
-
- createKeyForProps.createKeyForProps(property, path, table, columnName)
- indexBinder.bindIndex(columnName, column, cc, table)
-
- def owner = property.hibernateOwner
- if (!owner.isRoot()) {
- Mapping mapping = owner.hibernateMappedForm
- if (mapping != null && mapping.getTablePerHierarchy()) {
- if (LOG.isDebugEnabled()) {
- LOG.debug('Sub class property [{}] for column name [{}] set to nullable', property.name, column.name)
- }
- column.nullable = true
- } else {
- column.nullable = property.isNullable()
- }
- }
-
- // Apply uniqueness last to ensure it isn't overridden by downstream binders
- PropertyConfig mappedFormFinal = property.hibernateMappedForm
- column.unique = mappedFormFinal.isUnique() && !mappedFormFinal.isUniqueWithinGroup()
-
- if (LOG.isDebugEnabled()) {
- LOG.debug('Bound property [{}] to column name [{}] in table [{}]', property.name, column.name, table.name)
- }
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ComponentBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ComponentBinder.groovy
deleted file mode 100644
index f243f562ed..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ComponentBinder.groovy
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import jakarta.annotation.Nonnull
-import org.hibernate.boot.spi.MetadataBuildingContext
-import org.hibernate.mapping.Collection
-import org.hibernate.mapping.Component
-import org.hibernate.mapping.PersistentClass
-
-import org.grails.orm.hibernate.cfg.GrailsHibernateUtil
-import org.grails.orm.hibernate.cfg.MappingCacheHolder
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateEmbeddedCollectionProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateEmbeddedProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty
-
-// ComponentBinder holds a GrailsPropertyBinder reference set post-construction via
-// setGrailsPropertyBinder() to break a circular dependency (ComponentBinder ↔ GrailsPropertyBinder ↔
-// CollectionBinder ↔ ComponentBinder). A future major release can introduce a shared binding context or
-// factory object that all binders receive at construction time.
-/**
- * Binds embedded components and embedded collection elements to the Hibernate meta-model.
- *
- * @since 8.0
- */
-@CompileStatic
-@SuppressWarnings('PMD.DataflowAnomalyAnalysis')
-class ComponentBinder {
-
- private final MetadataBuildingContext metadataBuildingContext
- private final MappingCacheHolder mappingCacheHolder
- private final ComponentUpdater componentUpdater
- private GrailsPropertyBinder grailsPropertyBinder
-
- ComponentBinder(
- MetadataBuildingContext metadataBuildingContext,
- MappingCacheHolder mappingCacheHolder,
- ComponentUpdater componentUpdater) {
- this.metadataBuildingContext = metadataBuildingContext
- this.mappingCacheHolder = mappingCacheHolder
- this.componentUpdater = componentUpdater
- }
-
- void setGrailsPropertyBinder(GrailsPropertyBinder grailsPropertyBinder) {
- this.grailsPropertyBinder = grailsPropertyBinder
- }
-
- Component bindComponent(@Nonnull HibernateEmbeddedProperty embeddedProperty, String path) {
- PersistentClass owner = embeddedProperty.persistentClass
- Component component = new Component(metadataBuildingContext, owner)
- Class<?> type = embeddedProperty.type
- String role = GrailsHibernateUtil.qualify(type.name, embeddedProperty.name)
- component.roleName = role
- component.componentClassName = type.name
-
- GrailsHibernatePersistentEntity associatedEntity =
- (GrailsHibernatePersistentEntity) embeddedProperty.associatedEntity
- mappingCacheHolder.cacheMapping(associatedEntity)
-
- PersistentClass persistentClass = component.owner
- associatedEntity.persistentClass = persistentClass
- String currentPath = path.isEmpty() ? embeddedProperty.name : "${path}.${embeddedProperty.name}"
- Class<?> propertyType = embeddedProperty.owner.javaClass
-
- associatedEntity
- .getHibernateParentProperty(propertyType)
- .ifPresent { p -> component.setParentProperty(p.name) }
-
- for (HibernatePersistentProperty peerProperty :
- associatedEntity.getHibernatePersistentProperties(propertyType)) {
- def value = grailsPropertyBinder.bindProperty(peerProperty, embeddedProperty, currentPath)
- componentUpdater.updateComponent(component, embeddedProperty, peerProperty, value)
- }
- return component
- }
-
- /**
- * Binds an embedded collection property as a Hibernate {@link Component} element.
- * Used for {@code hasMany} associations whose element type is a non-entity value object
- * (a GORM embedded type) rather than a scalar or persistent entity.
- */
- Component bindEmbeddedCollectionComponent(@Nonnull HibernateEmbeddedCollectionProperty property) {
- Collection collection = property.collection
- Component component = new Component(metadataBuildingContext, collection)
-
- GrailsHibernatePersistentEntity associatedEntity =
- (GrailsHibernatePersistentEntity) property.associatedEntity
- mappingCacheHolder.cacheMapping(associatedEntity)
-
- Class<?> elementType = property.componentType
- if (elementType == null) {
- elementType = property.type
- }
- component.componentClassName = elementType.name
-
- String role = GrailsHibernateUtil.qualify(property.owner.javaClass.name, property.name)
- component.roleName = role
-
- associatedEntity.persistentClass = collection.owner
-
- Class<?> ownerType = property.owner.javaClass
- for (HibernatePersistentProperty peer : associatedEntity.getHibernatePersistentProperties(ownerType)) {
- def value = grailsPropertyBinder.bindProperty(peer, null, property.name)
- componentUpdater.updateComponent(component, property, peer, value)
- }
-
- return component
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ComponentUpdater.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ComponentUpdater.groovy
deleted file mode 100644
index 3cbc879a6a..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ComponentUpdater.groovy
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import org.hibernate.mapping.Column
-import org.hibernate.mapping.Component
-import org.hibernate.mapping.Property
-import org.hibernate.mapping.Value
-
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty
-import org.grails.orm.hibernate.cfg.domainbinding.util.PropertyFromValueCreator
-
-@CompileStatic
-class ComponentUpdater {
-
- private final PropertyFromValueCreator propertyFromValueCreator
-
- ComponentUpdater(PropertyFromValueCreator propertyFromValueCreator) {
- this.propertyFromValueCreator = propertyFromValueCreator
- }
-
- void updateComponent(
- Component component,
- HibernatePersistentProperty componentProperty,
- HibernatePersistentProperty currentGrailsProp,
- Value value) {
- Property persistentProperty = propertyFromValueCreator.createProperty(value, currentGrailsProp)
- component.addProperty(persistentProperty)
- if (componentProperty != null &&
- componentProperty.hibernateOwner.isComponentPropertyNullable(componentProperty)) {
- for (Column c : value.columns) {
- c.nullable = true
- }
- }
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeIdBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeIdBinder.groovy
deleted file mode 100644
index c74d56e28b..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeIdBinder.groovy
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import jakarta.annotation.Nonnull
-import org.hibernate.MappingException
-import org.hibernate.boot.spi.MetadataBuildingContext
-import org.hibernate.mapping.Component
-import org.hibernate.mapping.RootClass
-import org.hibernate.mapping.Value
-
-import org.grails.orm.hibernate.cfg.GrailsHibernateUtil
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateCompositeIdentityProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentEntity
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty
-
-@CompileStatic
-@SuppressWarnings('PMD.DataflowAnomalyAnalysis')
-class CompositeIdBinder {
-
- private final MetadataBuildingContext metadataBuildingContext
- private final ComponentUpdater componentUpdater
- private final GrailsPropertyBinder grailsPropertyBinder
-
- CompositeIdBinder(
- MetadataBuildingContext metadataBuildingContext,
- ComponentUpdater componentUpdater,
- GrailsPropertyBinder grailsPropertyBinder) {
- this.metadataBuildingContext = metadataBuildingContext
- this.componentUpdater = componentUpdater
- this.grailsPropertyBinder = grailsPropertyBinder
- }
-
- void bindCompositeId(@Nonnull HibernatePersistentEntity domainClass) {
- if (domainClass.identityProperty instanceof HibernateCompositeIdentityProperty) {
- HibernateCompositeIdentityProperty compositeIdentityProperty =
- (HibernateCompositeIdentityProperty) domainClass.identityProperty
- Component id = getComponent(domainClass)
-
- for (HibernatePersistentProperty property : compositeIdentityProperty.parts) {
- Value value = grailsPropertyBinder.bindProperty(property, null, '')
- componentUpdater.updateComponent(id, null, property, value)
- }
- return
- }
- throw new MappingException("Invalid composite id binding for entity [${domainClass.name}]".toString())
- }
-
- private Component getComponent(HibernatePersistentEntity domainClass) {
- RootClass rootClass = domainClass.rootClass
- Component id = new Component(metadataBuildingContext, rootClass)
- id.nullValue = 'undefined'
- rootClass.identifier = id
- rootClass.embeddedIdentifier = true
- id.componentClassName = domainClass.name
- id.key = true
- id.embedded = true
-
- String path = GrailsHibernateUtil.qualify(rootClass.entityName, 'id')
-
- id.roleName = path
- return id
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeIdentifierToManyToOneBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeIdentifierToManyToOneBinder.groovy
deleted file mode 100644
index be10f4de12..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeIdentifierToManyToOneBinder.groovy
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import org.hibernate.boot.spi.MetadataBuildingContext
-import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment
-import org.hibernate.mapping.Column
-import org.hibernate.mapping.SimpleValue
-
-import org.grails.orm.hibernate.cfg.ColumnConfig
-import org.grails.orm.hibernate.cfg.HibernateCompositeIdentity
-import org.grails.orm.hibernate.cfg.PersistentEntityNamingStrategy
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToOneProperty
-import org.grails.orm.hibernate.cfg.domainbinding.util.BackticksRemover
-import org.grails.orm.hibernate.cfg.domainbinding.util.DefaultColumnNameFetcher
-import org.grails.orm.hibernate.cfg.domainbinding.util.ForeignKeyColumnCountCalculator
-
-import static org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsDomainBinder.UNDERSCORE
-
-@CompileStatic
-@SuppressWarnings('PMD.DataflowAnomalyAnalysis')
-class CompositeIdentifierToManyToOneBinder {
-
- private final ForeignKeyColumnCountCalculator foreignKeyColumnCountCalculator
- private final PersistentEntityNamingStrategy namingStrategy
- private final DefaultColumnNameFetcher defaultColumnNameFetcher
- private final BackticksRemover backticksRemover
- private final SimpleValueBinder simpleValueBinder
-
- CompositeIdentifierToManyToOneBinder(
- ForeignKeyColumnCountCalculator foreignKeyColumnCountCalculator,
- PersistentEntityNamingStrategy namingStrategy,
- DefaultColumnNameFetcher defaultColumnNameFetcher,
- BackticksRemover backticksRemover,
- SimpleValueBinder simpleValueBinder) {
- this.foreignKeyColumnCountCalculator = foreignKeyColumnCountCalculator
- this.namingStrategy = namingStrategy
- this.defaultColumnNameFetcher = defaultColumnNameFetcher
- this.backticksRemover = backticksRemover
- this.simpleValueBinder = simpleValueBinder
- }
-
- CompositeIdentifierToManyToOneBinder(
- MetadataBuildingContext metadataBuildingContext,
- PersistentEntityNamingStrategy namingStrategy,
- JdbcEnvironment jdbcEnvironment) {
- this(
- new ForeignKeyColumnCountCalculator(),
- namingStrategy,
- new DefaultColumnNameFetcher(namingStrategy),
- new BackticksRemover(),
- new SimpleValueBinder(metadataBuildingContext, namingStrategy, jdbcEnvironment))
- }
-
- void bindCompositeIdentifierToManyToOne(
- HibernatePersistentProperty property,
- SimpleValue value,
- HibernateCompositeIdentity compositeId,
- GrailsHibernatePersistentEntity refDomainClass,
- String path) {
- String[] propertyNames = compositeId.propertyNames
- List<ColumnConfig> columns = property.hibernateMappedForm.columns
- int existingCount = columns.size()
- if (existingCount !=
- foreignKeyColumnCountCalculator.calculateForeignKeyColumnCount(refDomainClass, propertyNames)) {
- String prefix = refDomainClass.getTableName(namingStrategy)
- List<ColumnConfig> generated = []
- for (int idx = 0; idx < propertyNames.length; idx++) {
- ColumnConfig cc = idx < existingCount ? columns.get(idx) : new ColumnConfig()
- if (cc.name != null) {
- continue
- }
- String propertyName = propertyNames[idx]
- HibernatePersistentProperty ref = refDomainClass.getHibernatePropertyByName(propertyName)
- List<ColumnConfig> nested = tryExpandNestedComposite(prefix, propertyName, ref)
- if (nested != null) {
- generated.addAll(nested)
- } else {
- generated.add(singleColumn(prefix, propertyName, ref, cc))
- }
- }
- columns.addAll(generated)
- }
- simpleValueBinder.bindSimpleValue(property, null, value, path)
- refDomainClass.sortOrIndexForeignKeyColumns(value)
- List<Column> referencedColumns = refDomainClass.getReferencedIdentifierColumns(propertyNames)
- if (!referencedColumns.isEmpty() &&
- value.createForeignKeyOfEntity(refDomainClass.name, referencedColumns) != null) {
- value.disableForeignKey()
- }
- property.markValueSorted(value)
- }
-
- /**
- * If {@code ref} is a to-one whose associated entity has a composite identity, returns a list
- * of one named {@link ColumnConfig} per composite-identity property. Returns {@code null} otherwise.
- */
- private List<ColumnConfig> tryExpandNestedComposite(
- String prefix, String propertyName, HibernatePersistentProperty ref) {
- if (!(ref instanceof HibernateToOneProperty)) {
- return null
- }
- HibernateToOneProperty toOne = (HibernateToOneProperty) ref
- HibernatePersistentProperty[] nestedComposite =
- toOne.hibernateAssociatedEntity.compositeIdentity
- if (nestedComposite == null) {
- return null
- }
- List<ColumnConfig> result = []
- for (HibernatePersistentProperty cip : nestedComposite) {
- result.add(namedColumn(join(
- prefix,
- namingStrategy.resolveColumnName(propertyName),
- defaultColumnNameFetcher.getDefaultColumnName(cip))))
- }
- return result
- }
-
- private ColumnConfig singleColumn(
- String prefix, String propertyName, HibernatePersistentProperty ref, ColumnConfig cc) {
- String suffix = ref != null ? defaultColumnNameFetcher.getDefaultColumnName(ref) : propertyName
- cc.name = join(prefix, suffix)
- return cc
- }
-
- private ColumnConfig namedColumn(String name) {
- ColumnConfig cc = new ColumnConfig()
- cc.name = name
- return cc
- }
-
- private String join(String... parts) {
- List<String> cleaned = []
- for (String part : parts) {
- cleaned.add(backticksRemover.apply(part))
- }
- return cleaned.join(UNDERSCORE.toString())
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ConfiguredDiscriminatorBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ConfiguredDiscriminatorBinder.groovy
deleted file mode 100644
index 5035d0a7b1..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ConfiguredDiscriminatorBinder.groovy
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import org.hibernate.mapping.Column
-import org.hibernate.mapping.Formula
-import org.hibernate.mapping.RootClass
-import org.hibernate.mapping.SimpleValue
-
-import org.grails.orm.hibernate.cfg.ColumnConfig
-import org.grails.orm.hibernate.cfg.DiscriminatorConfig
-
-import static org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsDomainBinder.DEFAULT_DISCRIMINATOR_COLUMN_NAME
-
-@CompileStatic
-class ConfiguredDiscriminatorBinder {
-
- private static final String STRING_TYPE = 'string'
-
- private final SimpleValueColumnBinder simpleValueColumnBinder
- private final ColumnConfigToColumnBinder columnConfigToColumnBinder
-
- ConfiguredDiscriminatorBinder(
- SimpleValueColumnBinder simpleValueColumnBinder, ColumnConfigToColumnBinder columnConfigToColumnBinder) {
- this.simpleValueColumnBinder = simpleValueColumnBinder
- this.columnConfigToColumnBinder = columnConfigToColumnBinder
- }
-
- /**
- * Binds a discriminator with explicit configuration
- *
- * @param entity The root class entity
- * @param discriminator The discriminator value to configure
- * @param config The discriminator configuration
- */
- void bindConfiguredDiscriminator(RootClass entity, SimpleValue discriminator, DiscriminatorConfig config) {
- // A configuration that maps only the column or formula keeps the class name as the value
- entity.discriminatorValue = config.value != null ? config.value : entity.className
-
- // Configure insertable if specified
- if (config.insertable != null) {
- entity.setDiscriminatorInsertable(config.insertable)
- }
-
- // Resolve type name
- String typeName = resolveTypeName(config.type)
-
- // Bind based on configuration type
- if (config.formula != null) {
- bindDiscriminatorWithFormula(discriminator, typeName, config.formula)
- } else {
- bindDiscriminatorWithColumn(discriminator, typeName, config.column)
- }
- }
-
- private String resolveTypeName(Object type) {
- if (type == null) {
- return STRING_TYPE
- }
-
- return (type instanceof Class) ? ((Class<?>) type).name : type.toString()
- }
-
- private void bindDiscriminatorWithFormula(SimpleValue discriminator, String typeName, String formula) {
- discriminator.typeName = typeName
- Formula f = new Formula()
- f.formula = formula
- discriminator.addFormula(f)
- }
-
- private void bindDiscriminatorWithColumn(SimpleValue discriminator, String typeName, ColumnConfig columnConfig) {
- simpleValueColumnBinder.bindSimpleValue(discriminator, typeName, DEFAULT_DISCRIMINATOR_COLUMN_NAME, false)
-
- if (columnConfig != null) {
- configureDiscriminatorColumn(discriminator, columnConfig)
- }
- }
-
- private void configureDiscriminatorColumn(SimpleValue discriminator, ColumnConfig columnConfig) {
- Column column = discriminator.columns.iterator().next()
-
- if (columnConfig.name != null) {
- column.name = columnConfig.name
- }
-
- columnConfigToColumnBinder.bindColumnConfigToColumn(column, columnConfig, null)
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/DefaultDiscriminatorBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/DefaultDiscriminatorBinder.groovy
deleted file mode 100644
index 38f70cee18..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/DefaultDiscriminatorBinder.groovy
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import org.hibernate.mapping.RootClass
-import org.hibernate.mapping.SimpleValue
-
-import static org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsDomainBinder.DEFAULT_DISCRIMINATOR_COLUMN_NAME
-
-@CompileStatic
-class DefaultDiscriminatorBinder {
-
- private static final String STRING_TYPE = 'string'
-
- private final SimpleValueColumnBinder simpleValueColumnBinder
-
- DefaultDiscriminatorBinder(SimpleValueColumnBinder simpleValueColumnBinder) {
- this.simpleValueColumnBinder = simpleValueColumnBinder
- }
-
- /**
- * Binds a discriminator with default configuration (no explicit config)
- *
- * @param entity The root class entity
- * @param discriminator The discriminator value to configure
- */
- void bindDefaultDiscriminator(RootClass entity, SimpleValue discriminator) {
- // Use class name as discriminator value
- entity.discriminatorValue = entity.className
-
- // Bind with default column configuration
- simpleValueColumnBinder.bindSimpleValue(discriminator, STRING_TYPE, DEFAULT_DISCRIMINATOR_COLUMN_NAME, false)
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/DiscriminatorPropertyBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/DiscriminatorPropertyBinder.groovy
deleted file mode 100644
index c2340f9204..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/DiscriminatorPropertyBinder.groovy
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import org.hibernate.boot.spi.MetadataBuildingContext
-import org.hibernate.mapping.BasicValue
-import org.hibernate.mapping.RootClass
-import org.hibernate.mapping.SimpleValue
-
-import org.grails.orm.hibernate.cfg.DiscriminatorConfig
-import org.grails.orm.hibernate.cfg.Mapping
-import org.grails.orm.hibernate.cfg.MappingCacheHolder
-
-@CompileStatic
-@SuppressWarnings('PMD.DataflowAnomalyAnalysis')
-class DiscriminatorPropertyBinder {
-
- private final MetadataBuildingContext metadataBuildingContext
- private final MappingCacheHolder mappingCacheHolder
- private final ConfiguredDiscriminatorBinder configuredDiscriminatorBinder
- private final DefaultDiscriminatorBinder defaultDiscriminatorBinder
-
- DiscriminatorPropertyBinder(
- MetadataBuildingContext metadataBuildingContext,
- MappingCacheHolder mappingCacheHolder,
- ConfiguredDiscriminatorBinder configuredDiscriminatorBinder,
- DefaultDiscriminatorBinder defaultDiscriminatorBinder) {
- this.metadataBuildingContext = metadataBuildingContext
- this.mappingCacheHolder = mappingCacheHolder
- this.configuredDiscriminatorBinder = configuredDiscriminatorBinder
- this.defaultDiscriminatorBinder = defaultDiscriminatorBinder
- }
-
- /**
- * Creates and binds the discriminator property used in table-per-hierarchy inheritance to
- * discriminate between sub class instances
- *
- * @param entity The root class entity
- */
- void bindDiscriminatorProperty(RootClass entity) {
- SimpleValue discriminator = createDiscriminator(entity)
- entity.discriminator = discriminator
-
- Mapping mapping = mappingCacheHolder.getMapping(entity.mappedClass)
- DiscriminatorConfig config = mapping.discriminator
-
- if (config != null) {
- configuredDiscriminatorBinder.bindConfiguredDiscriminator(entity, discriminator, config)
- }
- else {
- defaultDiscriminatorBinder.bindDefaultDiscriminator(entity, discriminator)
- }
- }
-
- private SimpleValue createDiscriminator(RootClass entity) {
- return new BasicValue(metadataBuildingContext, entity.table)
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/EnumTypeBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/EnumTypeBinder.groovy
deleted file mode 100644
index 79b96de747..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/EnumTypeBinder.groovy
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import jakarta.annotation.Nonnull
-import org.hibernate.boot.spi.MetadataBuildingContext
-import org.hibernate.mapping.BasicValue
-import org.hibernate.mapping.Column
-import org.hibernate.mapping.Table
-import org.slf4j.Logger
-import org.slf4j.LoggerFactory
-
-import org.grails.orm.hibernate.cfg.ColumnConfig
-import org.grails.orm.hibernate.cfg.PersistentEntityNamingStrategy
-import org.grails.orm.hibernate.cfg.PropertyConfig
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateEnumProperty
-import org.grails.orm.hibernate.cfg.domainbinding.util.ColumnNameForPropertyAndPathFetcher
-import org.grails.orm.hibernate.cfg.domainbinding.util.GrailsEnumType
-
-import static org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsDomainBinder.ENUM_CLASS_PROP
-
-@CompileStatic
-class EnumTypeBinder {
-
- private static final Logger LOG = LoggerFactory.getLogger(EnumTypeBinder)
-
- private final MetadataBuildingContext metadataBuildingContext
- private final ColumnNameForPropertyAndPathFetcher columnNameForPropertyAndPathFetcher
- private final IndexBinder indexBinder
- private final ColumnConfigToColumnBinder columnConfigToColumnBinder
- private final PersistentEntityNamingStrategy namingStrategy
-
- EnumTypeBinder(
- MetadataBuildingContext metadataBuildingContext,
- ColumnNameForPropertyAndPathFetcher columnNameForPropertyAndPathFetcher,
- PersistentEntityNamingStrategy namingStrategy) {
- this(
- metadataBuildingContext,
- columnNameForPropertyAndPathFetcher,
- new IndexBinder(),
- new ColumnConfigToColumnBinder(),
- namingStrategy)
- }
-
- protected EnumTypeBinder(
- MetadataBuildingContext metadataBuildingContext,
- ColumnNameForPropertyAndPathFetcher columnNameForPropertyAndPathFetcher,
- IndexBinder indexBinder,
- ColumnConfigToColumnBinder columnConfigToColumnBinder,
- PersistentEntityNamingStrategy namingStrategy) {
- this.metadataBuildingContext = metadataBuildingContext
- this.columnNameForPropertyAndPathFetcher = columnNameForPropertyAndPathFetcher
- this.indexBinder = indexBinder
- this.columnConfigToColumnBinder = columnConfigToColumnBinder
- this.namingStrategy = namingStrategy
- }
-
- BasicValue bindEnumType(@Nonnull HibernateEnumProperty property, String path) {
- String columnName = property.resolveEnumColumnName(namingStrategy, columnNameForPropertyAndPathFetcher, path)
- BasicValue simpleValue = new BasicValue(metadataBuildingContext, property.table)
- Class<?> propertyType = property.enumType
- PropertyConfig pc = property.hibernateMappedForm
- String typeName = property.getTypeName(propertyType)
- if (typeName != null) {
- simpleValue.typeName = typeName
- } else {
- GrailsEnumType.fromString(pc.enumType).configure(simpleValue, propertyType)
- }
- Properties enumProperties = new Properties()
- enumProperties.put(ENUM_CLASS_PROP, propertyType.name)
- simpleValue.setTypeParameters(enumProperties)
-
- Column column = new Column()
- if (property.hibernateOwner.isTablePerHierarchySubclass() && LOG.isDebugEnabled()) {
- LOG.debug('[GrailsDomainBinder] Sub class property [{}] for column name [{}] forced to nullable',
- property.name, columnName)
- }
- column.nullable = property.isEnumColumnNullable()
- column.value = simpleValue
- column.name = columnName
- Table t = simpleValue.table
- t.addColumn(column)
- simpleValue.addColumn(column)
-
- if (!pc.columns.isEmpty()) {
- ColumnConfig columnConfig = pc.columns.get(0)
- column.comment = columnConfig.comment
- column.defaultValue = columnConfig.defaultValue
- column.customRead = columnConfig.read
- column.customWrite = columnConfig.write
- indexBinder.bindIndex(columnName, column, columnConfig, t)
- columnConfigToColumnBinder.bindColumnConfigToColumn(column, columnConfig, pc)
- }
- return simpleValue
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ForeignKeyOneToOneBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ForeignKeyOneToOneBinder.groovy
deleted file mode 100644
index d3cda3a82a..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ForeignKeyOneToOneBinder.groovy
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import org.hibernate.MappingException
-import org.hibernate.mapping.Column
-import org.hibernate.mapping.ManyToOne
-
-import org.grails.orm.hibernate.cfg.PropertyConfig
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateOneToOneProperty
-import org.grails.orm.hibernate.cfg.domainbinding.util.SimpleValueColumnFetcher
-
-/**
- * Binds a {@link HibernateOneToOneProperty} whose foreign key resides on this side as a Hibernate
- * {@link ManyToOne} value, and applies unique-key constraints as needed.
- *
- * <p>This handles the case where {@code isValidHibernateOneToOne()} is {@code false} — i.e. the
- * association cannot be mapped as a Hibernate {@code OneToOne}, so it falls back to a ManyToOne
- * column with an alternate unique key.
- */
-@CompileStatic
-class ForeignKeyOneToOneBinder {
-
- private final ManyToOneBinder manyToOneBinder
- private final SimpleValueColumnFetcher simpleValueColumnFetcher
-
- ForeignKeyOneToOneBinder(
- ManyToOneBinder manyToOneBinder, SimpleValueColumnFetcher simpleValueColumnFetcher) {
- this.manyToOneBinder = manyToOneBinder
- this.simpleValueColumnFetcher = simpleValueColumnFetcher
- }
-
- /**
- * Binds the one-to-one property as a {@link ManyToOne} value and applies unique-key constraints.
- */
- ManyToOne bind(HibernateOneToOneProperty property, String path) {
- GrailsHibernatePersistentEntity refDomainClass = property.hibernateAssociatedEntity
- ManyToOne manyToOne = manyToOneBinder.bindManyToOne(property, path)
- if (refDomainClass.hibernateCompositeIdentity.isEmpty()) {
- bindUniqueKey(property, manyToOne)
- }
- return manyToOne
- }
-
- private void bindUniqueKey(HibernateOneToOneProperty property, ManyToOne manyToOne) {
- PropertyConfig config = property.hibernateMappedForm
- manyToOne.alternateUniqueKey = true
- Column c = simpleValueColumnFetcher.getColumnForSimpleValue(manyToOne)
- if (c == null) {
- throw new MappingException("There is no column for property [${property.name}]".toString())
- }
- if (!config.isUniqueWithinGroup()) {
- c.unique = config.isUnique()
- }
- else if (property.isBidirectional() &&
- property.hibernateInverseSide.isValidHibernateOneToOne()) {
- c.unique = true
- }
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/GrailsDomainBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/GrailsDomainBinder.groovy
deleted file mode 100644
index 4aa4dc60b7..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/GrailsDomainBinder.groovy
+++ /dev/null
@@ -1,321 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import java.util.function.BiFunction
-
-import groovy.transform.CompileStatic
-import org.hibernate.boot.ResourceStreamLocator
-import org.hibernate.boot.model.TypeContributions
-import org.hibernate.boot.model.TypeContributor
-import org.hibernate.boot.spi.AdditionalMappingContributions
-import org.hibernate.boot.spi.AdditionalMappingContributor
-import org.hibernate.boot.spi.InFlightMetadataCollector
-import org.hibernate.boot.spi.MetadataBuildingContext
-import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment
-import org.hibernate.mapping.BasicValue
-import org.hibernate.mapping.Table
-import org.hibernate.service.ServiceRegistry
-import org.slf4j.Logger
-import org.slf4j.LoggerFactory
-
-import org.grails.orm.hibernate.cfg.MappingCacheHolder
-import org.grails.orm.hibernate.cfg.PersistentEntityNamingStrategy
-import org.grails.orm.hibernate.cfg.domainbinding.collectionType.CollectionHolder
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentEntity
-import org.grails.orm.hibernate.cfg.domainbinding.jpa.GeneratedDomainClassBinder
-import org.grails.orm.hibernate.cfg.domainbinding.util.BackticksRemover
-import org.grails.orm.hibernate.cfg.domainbinding.util.BasicValueCreator
-import org.grails.orm.hibernate.cfg.domainbinding.util.ColumnNameForPropertyAndPathFetcher
-import org.grails.orm.hibernate.cfg.domainbinding.util.DefaultColumnNameFetcher
-import org.grails.orm.hibernate.cfg.domainbinding.util.ForeignKeyColumnCountCalculator
-import org.grails.orm.hibernate.cfg.domainbinding.util.GrailsPropertyResolver
-import org.grails.orm.hibernate.cfg.domainbinding.util.MultiTenantFilterBinder
-import org.grails.orm.hibernate.cfg.domainbinding.util.MultiTenantFilterDefinitionBinder
-import org.grails.orm.hibernate.cfg.domainbinding.util.NamingStrategyProvider
-import org.grails.orm.hibernate.cfg.domainbinding.util.NamingStrategyWrapper
-import org.grails.orm.hibernate.cfg.domainbinding.util.PropertyFromValueCreator
-import org.grails.orm.hibernate.cfg.domainbinding.util.SimpleValueColumnFetcher
-import org.grails.orm.hibernate.cfg.domainbinding.util.TableForManyCalculator
-
-/**
- * Handles the binding Grails domain classes and properties to the Hibernate runtime meta model.
- * Based on the HbmBinder code in Hibernate core and influenced by AnnotationsBinder.
- *
- * @since 8.0
- */
-@CompileStatic
-class GrailsDomainBinder implements AdditionalMappingContributor, TypeContributor {
-
- public static final String FOREIGN_KEY_SUFFIX = '_id'
- public static final String EMPTY_PATH = ''
- public static final char UNDERSCORE = '_'
-
- public static final String ENUM_CLASS_PROP = 'enumClass'
- public static final Logger LOG = LoggerFactory.getLogger(GrailsDomainBinder)
-
- /**
- * The name of the discriminator column of a table-per-hierarchy tree that does not map one.
- */
- public static final String DEFAULT_DISCRIMINATOR_COLUMN_NAME = 'class'
-
- private final String sessionFactoryName
- private final String dataSourceName
- private final List<HibernatePersistentEntity> persistentEntities
- private final NamingStrategyProvider namingStrategyProvider
- private final MappingCacheHolder mappingCacheHolder
- private final GeneratedDomainClassBinder generatedDomainClassBinder
- private PersistentEntityNamingStrategy namingStrategy
- private MetadataBuildingContext metadataBuildingContext
-
- /**
- * @param persistentEntities the entities to bind; each must already carry the name of {@code dataSourceName}
- */
- GrailsDomainBinder(
- String dataSourceName,
- String sessionFactoryName,
- List<HibernatePersistentEntity> persistentEntities,
- NamingStrategyProvider namingStrategyProvider,
- MappingCacheHolder mappingCacheHolder) {
- this(dataSourceName, sessionFactoryName, persistentEntities, namingStrategyProvider, mappingCacheHolder, null)
- }
-
- /**
- * @param persistentEntities the entities to bind; each must already carry the name of {@code dataSourceName}
- * @param generatedDomainClassBinder when not {@code null}, the entities are not built into Hibernate's boot model by
- * this binder: classes are generated from them and Hibernate's annotation binder binds those
- */
- GrailsDomainBinder(
- String dataSourceName,
- String sessionFactoryName,
- List<HibernatePersistentEntity> persistentEntities,
- NamingStrategyProvider namingStrategyProvider,
- MappingCacheHolder mappingCacheHolder,
- GeneratedDomainClassBinder generatedDomainClassBinder) {
- this.generatedDomainClassBinder = generatedDomainClassBinder
- this.sessionFactoryName = sessionFactoryName
- this.dataSourceName = dataSourceName
- this.persistentEntities = persistentEntities
- this.namingStrategyProvider = namingStrategyProvider
- this.mappingCacheHolder = mappingCacheHolder
-
- // pre-build mappings
- for (HibernatePersistentEntity persistentEntity : persistentEntities) {
- mappingCacheHolder.cacheMapping(persistentEntity)
- }
- }
-
- JdbcEnvironment getJdbcEnvironment() {
- return metadataBuildingContext.metadataCollector.database.jdbcEnvironment
- }
-
- @Override
- void contribute(
- AdditionalMappingContributions contributions,
- InFlightMetadataCollector metadataCollector,
- ResourceStreamLocator resourceStreamLocator,
- MetadataBuildingContext buildingContext) {
- if (generatedDomainClassBinder == null) {
- bind(metadataCollector, buildingContext, persistentEntities)
- }
- else {
- this.metadataBuildingContext = buildingContext
- generatedDomainClassBinder.contribute(
- contributions, buildingContext, persistentEntities, getNamingStrategy(), getJdbcEnvironment())
- }
- }
-
- @SuppressWarnings('PMD.DataflowAnomalyAnalysis')
- private void bind(
- InFlightMetadataCollector metadataCollector,
- MetadataBuildingContext buildingContext,
- List<HibernatePersistentEntity> entities) {
- this.metadataBuildingContext = buildingContext
- CollectionHolder collectionHolder = new CollectionHolder(metadataBuildingContext)
- BackticksRemover backticksRemover = new BackticksRemover()
- PersistentEntityNamingStrategy namingStrategy = getNamingStrategy()
- JdbcEnvironment jdbcEnvironment = getJdbcEnvironment()
- DefaultColumnNameFetcher defaultColumnNameFetcher =
- new DefaultColumnNameFetcher(namingStrategy, backticksRemover)
- ColumnNameForPropertyAndPathFetcher columnNameForPropertyAndPathFetcher =
- new ColumnNameForPropertyAndPathFetcher(namingStrategy, defaultColumnNameFetcher, backticksRemover)
- SimpleValueBinder simpleValueBinder =
- new SimpleValueBinder(metadataBuildingContext, namingStrategy, jdbcEnvironment)
- EnumTypeBinder enumTypeBinder =
- new EnumTypeBinder(metadataBuildingContext, columnNameForPropertyAndPathFetcher, namingStrategy)
- PropertyFromValueCreator propertyFromValueCreator = new PropertyFromValueCreator()
- ClassBinder classBinder = new ClassBinder(metadataCollector)
- SimpleValueColumnFetcher simpleValueColumnFetcher = new SimpleValueColumnFetcher()
- CompositeIdentifierToManyToOneBinder compositeIdentifierToManyToOneBinder =
- new CompositeIdentifierToManyToOneBinder(
- new ForeignKeyColumnCountCalculator(),
- namingStrategy,
- defaultColumnNameFetcher,
- backticksRemover,
- simpleValueBinder)
- OneToOneBinder oneToOneBinder = new OneToOneBinder(metadataBuildingContext, simpleValueBinder)
- ManyToOneBinder manyToOneBinder = new ManyToOneBinder(
- metadataBuildingContext,
- namingStrategy,
- simpleValueBinder,
- new ManyToOneValuesBinder(),
- compositeIdentifierToManyToOneBinder)
- ForeignKeyOneToOneBinder foreignKeyOneToOneBinder =
- new ForeignKeyOneToOneBinder(manyToOneBinder, simpleValueColumnFetcher)
-
- TableForManyCalculator tableForManyCalculator = new TableForManyCalculator(namingStrategy, metadataCollector)
- CollectionBinder collectionBinder = new CollectionBinder(
- metadataBuildingContext,
- namingStrategy,
- simpleValueBinder,
- enumTypeBinder,
- manyToOneBinder,
- compositeIdentifierToManyToOneBinder,
- simpleValueColumnFetcher,
- collectionHolder,
- metadataCollector,
- tableForManyCalculator)
- ComponentUpdater componentUpdater = new ComponentUpdater(propertyFromValueCreator)
- ComponentBinder componentBinder =
- new ComponentBinder(metadataBuildingContext, mappingCacheHolder, componentUpdater)
-
- GrailsPropertyBinder grailsPropertyBinder = new GrailsPropertyBinder(
- enumTypeBinder,
- componentBinder,
- collectionBinder,
- simpleValueBinder,
- oneToOneBinder,
- manyToOneBinder,
- foreignKeyOneToOneBinder)
- componentBinder.setGrailsPropertyBinder(grailsPropertyBinder)
- collectionBinder.setComponentBinder(componentBinder)
- CompositeIdBinder compositeIdBinder =
- new CompositeIdBinder(metadataBuildingContext, componentUpdater, grailsPropertyBinder)
- PropertyBinder propertyBinder = new PropertyBinder()
- SimpleIdBinder simpleIdBinder = new SimpleIdBinder(
- metadataBuildingContext,
- new BasicValueCreator(metadataBuildingContext, jdbcEnvironment, namingStrategy),
- simpleValueBinder,
- propertyBinder)
- IdentityBinder identityBinder = new IdentityBinder(simpleIdBinder, compositeIdBinder)
- VersionBinder versionBinder =
- new VersionBinder(metadataBuildingContext, simpleValueBinder, propertyBinder,
- { MetadataBuildingContext ctx, Table table -> new BasicValue(ctx, table) } as BiFunction<MetadataBuildingContext, Table, BasicValue>)
- NaturalIdentifierBinder naturalIdentifierBinder = new NaturalIdentifierBinder()
- ClassPropertiesBinder classPropertiesBinder =
- new ClassPropertiesBinder(grailsPropertyBinder, propertyFromValueCreator, naturalIdentifierBinder)
- MultiTenantFilterBinder multiTenantFilterBinder = new MultiTenantFilterBinder(
- new GrailsPropertyResolver(),
- new MultiTenantFilterDefinitionBinder(),
- metadataCollector,
- defaultColumnNameFetcher)
- JoinedSubClassBinder joinedSubClassBinder = new JoinedSubClassBinder(
- metadataBuildingContext,
- namingStrategy,
- new SimpleValueColumnBinder(),
- columnNameForPropertyAndPathFetcher,
- classBinder,
- metadataCollector)
- UnionSubclassBinder unionSubclassBinder =
- new UnionSubclassBinder(metadataBuildingContext, namingStrategy, classBinder, metadataCollector)
- SingleTableSubclassBinder singleTableSubclassBinder =
- new SingleTableSubclassBinder(classBinder, metadataBuildingContext)
-
- SubclassMappingBinder subclassMappingBinder = new SubclassMappingBinder(
- joinedSubClassBinder, unionSubclassBinder, singleTableSubclassBinder, classPropertiesBinder)
- SubClassBinder subClassBinder =
- new SubClassBinder(subclassMappingBinder, multiTenantFilterBinder, dataSourceName)
- RootPersistentClassCommonValuesBinder rootPersistentClassCommonValuesBinder =
- new RootPersistentClassCommonValuesBinder(
- metadataBuildingContext,
- getNamingStrategy(),
- identityBinder,
- versionBinder,
- classBinder,
- classPropertiesBinder,
- metadataCollector)
- DiscriminatorPropertyBinder discriminatorPropertyBinder = new DiscriminatorPropertyBinder(
- metadataBuildingContext,
- mappingCacheHolder,
- new ConfiguredDiscriminatorBinder(new SimpleValueColumnBinder(), new ColumnConfigToColumnBinder()),
- new DefaultDiscriminatorBinder(new SimpleValueColumnBinder()))
- RootBinder rootBinder = new RootBinder(
- dataSourceName,
- multiTenantFilterBinder,
- subClassBinder,
- rootPersistentClassCommonValuesBinder,
- discriminatorPropertyBinder,
- metadataCollector,
- mappingCacheHolder)
-
- for (HibernatePersistentEntity persistentEntity : entities) {
- if (persistentEntity.forGrailsDomainMapping(dataSourceName)) {
- rootBinder.bindRoot(persistentEntity)
- }
- }
- }
-
- /**
- * Override the default naming strategy given a Class or a full class name, or an instance of a
- * PhysicalNamingStrategy.
- *
- * @param datasourceName the datasource name
- * @param strategy the class, name, or instance
- * @throws ClassNotFoundException When the class was not found for specified strategy
- * @throws ReflectiveOperationException When an error occurred instantiating the strategy
- */
- void configureNamingStrategy(String datasourceName, Object strategy)
- throws ClassNotFoundException, ReflectiveOperationException {
- namingStrategyProvider.configureNamingStrategy(datasourceName, strategy)
- }
-
- PersistentEntityNamingStrategy getNamingStrategy() {
- if (namingStrategy == null) {
- namingStrategy = new NamingStrategyWrapper(
- namingStrategyProvider.getPhysicalNamingStrategy(sessionFactoryName), getJdbcEnvironment())
- }
- return namingStrategy
- }
-
- MetadataBuildingContext getMetadataBuildingContext() {
- return metadataBuildingContext
- }
-
- MappingCacheHolder getMappingCacheHolder() {
- return mappingCacheHolder
- }
-
- @Override
- String getContributorName() {
- return 'GORM'
- }
-
- @Override
- void contribute(TypeContributions typeContributions, ServiceRegistry serviceRegistry) {
- }
-
- /**
- * Manually re-runs the contribution process for the given entities with the building context of the last
- * bootstrap. Useful for unit testing where entities are registered after the session factory was built.
- */
- void contribute(InFlightMetadataCollector metadataCollector, List<HibernatePersistentEntity> entities) {
- bind(metadataCollector, metadataBuildingContext, entities)
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/GrailsPropertyBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/GrailsPropertyBinder.groovy
deleted file mode 100644
index 43e6cad663..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/GrailsPropertyBinder.groovy
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import jakarta.annotation.Nonnull
-import org.hibernate.mapping.Table
-import org.hibernate.mapping.Value
-import org.slf4j.Logger
-import org.slf4j.LoggerFactory
-
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateCustomProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateEmbeddedProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateEnumProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateManyToOneProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateOneToOneProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateSimpleProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateTenantIdProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyProperty
-
-@CompileStatic
-class GrailsPropertyBinder {
-
- private static final Logger LOG = LoggerFactory.getLogger(GrailsPropertyBinder)
-
- private final EnumTypeBinder enumTypeBinder
- private final ComponentBinder componentBinder
- private final CollectionBinder collectionBinder
- private final SimpleValueBinder simpleValueBinder
- private final OneToOneBinder oneToOneBinder
- private final ManyToOneBinder manyToOneBinder
- private final ForeignKeyOneToOneBinder foreignKeyOneToOneBinder
-
- GrailsPropertyBinder(
- EnumTypeBinder enumTypeBinder,
- ComponentBinder componentBinder,
- CollectionBinder collectionBinder,
- SimpleValueBinder simpleValueBinder,
- OneToOneBinder oneToOneBinder,
- ManyToOneBinder manyToOneBinder,
- ForeignKeyOneToOneBinder foreignKeyOneToOneBinder) {
- this.enumTypeBinder = enumTypeBinder
- this.componentBinder = componentBinder
- this.collectionBinder = collectionBinder
- this.simpleValueBinder = simpleValueBinder
- this.oneToOneBinder = oneToOneBinder
- this.manyToOneBinder = manyToOneBinder
- this.foreignKeyOneToOneBinder = foreignKeyOneToOneBinder
- }
-
- Value bindProperty(
- @Nonnull HibernatePersistentProperty currentGrailsProp,
- HibernatePersistentProperty parentProperty,
- String path) {
- Table table = currentGrailsProp.table
- if (LOG.isDebugEnabled()) {
- LOG.debug('[GrailsPropertyBinder] Binding persistent property [{}]', currentGrailsProp.name)
- }
-
- Value value
-
- if (currentGrailsProp instanceof HibernateEnumProperty &&
- !((HibernateEnumProperty) currentGrailsProp).isCollectionElement()) {
- // A hasMany-of-enum property is also a HibernateEnumProperty, but it must still go
- // through collectionBinder.bindCollection() below so its join table gets created;
- // EnumTypeBinder only binds its element column, from BasicCollectionElementBinder.
- value = enumTypeBinder.bindEnumType((HibernateEnumProperty) currentGrailsProp, path)
- } else if (currentGrailsProp.isUserButNotCollectionType()) {
- value = simpleValueBinder.bindBasicValue(currentGrailsProp, parentProperty, path)
- } else if (currentGrailsProp instanceof HibernateOneToOneProperty &&
- ((HibernateOneToOneProperty) currentGrailsProp).isValidHibernateOneToOne()) {
- value = oneToOneBinder.bindOneToOne((HibernateOneToOneProperty) currentGrailsProp, path)
- } else if (currentGrailsProp instanceof HibernateOneToOneProperty) {
- value = foreignKeyOneToOneBinder.bind((HibernateOneToOneProperty) currentGrailsProp, path)
- } else if (currentGrailsProp instanceof HibernateManyToOneProperty) {
- value = manyToOneBinder.bindManyToOne((HibernateManyToOneProperty) currentGrailsProp, table, path)
- } else if (currentGrailsProp instanceof HibernateToManyProperty &&
- !currentGrailsProp.isSerializableType()) {
- value = collectionBinder.bindCollection((HibernateToManyProperty) currentGrailsProp, path)
- } else if (currentGrailsProp instanceof HibernateEmbeddedProperty) {
- value = componentBinder.bindComponent((HibernateEmbeddedProperty) currentGrailsProp, path)
- } else if (currentGrailsProp instanceof HibernateSimpleProperty) {
- value = simpleValueBinder.bindBasicValue((HibernateSimpleProperty) currentGrailsProp, parentProperty, path)
- } else if (currentGrailsProp instanceof HibernateCustomProperty) {
- value = simpleValueBinder.bindBasicValue((HibernateCustomProperty) currentGrailsProp, parentProperty, path)
- } else if (currentGrailsProp instanceof HibernateTenantIdProperty) {
- value = simpleValueBinder.bindBasicValue((HibernateTenantIdProperty) currentGrailsProp, parentProperty, path)
- } else if (currentGrailsProp instanceof HibernateToManyProperty &&
- currentGrailsProp.isSerializableType()) {
- value = simpleValueBinder.bindBasicValue((HibernateToManyProperty) currentGrailsProp, parentProperty, path)
- } else {
- throw new RuntimeException(
- "Unsupported property type: ${currentGrailsProp.class.name}".toString())
- }
-
- return value
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/IdentityBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/IdentityBinder.groovy
deleted file mode 100644
index 5a5dd0fcc5..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/IdentityBinder.groovy
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import jakarta.annotation.Nonnull
-import org.hibernate.MappingException
-
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateCompositeIdentityProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateIdentityProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentEntity
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateSimpleIdentityProperty
-
-@CompileStatic
-class IdentityBinder {
-
- private final SimpleIdBinder simpleIdBinder
- private final CompositeIdBinder compositeIdBinder
-
- IdentityBinder(SimpleIdBinder simpleIdBinder, CompositeIdBinder compositeIdBinder) {
- this.simpleIdBinder = simpleIdBinder
- this.compositeIdBinder = compositeIdBinder
- }
-
- void bindIdentity(@Nonnull HibernatePersistentEntity domainClass) {
- HibernateIdentityProperty identityProperty = domainClass.identityProperty
- if (identityProperty instanceof HibernateCompositeIdentityProperty) {
- compositeIdBinder.bindCompositeId(domainClass)
- }
- else if (identityProperty instanceof HibernateSimpleIdentityProperty) {
- simpleIdBinder.bindSimpleId(domainClass)
- }
- else {
- throw new MappingException("No identity found for ${domainClass.name}".toString())
- }
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/JoinedSubClassBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/JoinedSubClassBinder.groovy
deleted file mode 100644
index d3639d7b08..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/JoinedSubClassBinder.groovy
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import org.hibernate.boot.spi.InFlightMetadataCollector
-import org.hibernate.boot.spi.MetadataBuildingContext
-import org.hibernate.mapping.DependantValue
-import org.hibernate.mapping.JoinedSubclass
-import org.hibernate.mapping.PersistentClass
-import org.hibernate.mapping.SimpleValue
-import org.hibernate.mapping.Table
-import org.slf4j.Logger
-import org.slf4j.LoggerFactory
-
-import org.grails.orm.hibernate.cfg.GrailsHibernateUtil
-import org.grails.orm.hibernate.cfg.PersistentEntityNamingStrategy
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty
-import org.grails.orm.hibernate.cfg.domainbinding.util.ColumnNameForPropertyAndPathFetcher
-
-/**
- * Binds a joined sub-class mapping using table-per-subclass
- *
- * @since 8.0
- */
-@CompileStatic
-class JoinedSubClassBinder {
-
- private static final Logger LOG = LoggerFactory.getLogger(JoinedSubClassBinder)
- private static final String EMPTY_PATH = ''
-
- private final MetadataBuildingContext metadataBuildingContext
- private final PersistentEntityNamingStrategy namingStrategy
- private final SimpleValueColumnBinder simpleValueColumnBinder
- private final ColumnNameForPropertyAndPathFetcher columnNameForPropertyAndPathFetcher
- private final ClassBinder classBinder
- private final InFlightMetadataCollector mappings
-
- JoinedSubClassBinder(
- MetadataBuildingContext metadataBuildingContext,
- PersistentEntityNamingStrategy namingStrategy,
- SimpleValueColumnBinder simpleValueColumnBinder,
- ColumnNameForPropertyAndPathFetcher columnNameForPropertyAndPathFetcher,
- ClassBinder classBinder,
- InFlightMetadataCollector mappings) {
- this.metadataBuildingContext = metadataBuildingContext
- this.namingStrategy = namingStrategy
- this.simpleValueColumnBinder = simpleValueColumnBinder
- this.columnNameForPropertyAndPathFetcher = columnNameForPropertyAndPathFetcher
- this.classBinder = classBinder
- this.mappings = mappings
- }
-
- /**
- * Binds a joined sub-class mapping using table-per-subclass
- *
- * @param sub The Grails sub class
- * @param parent The Hibernate Parent PersistentClass object
- * @return The created JoinedSubclass
- */
- JoinedSubclass bindJoinedSubClass(GrailsHibernatePersistentEntity sub, PersistentClass parent) {
- JoinedSubclass joinedSubclass = new JoinedSubclass(parent, metadataBuildingContext)
- classBinder.bindClass(sub, joinedSubclass)
-
- String schemaName = sub.getSchema(mappings)
- String catalogName = sub.getCatalog(mappings)
-
- Table mytable = mappings.addTable(
- schemaName,
- catalogName,
- getJoinedSubClassTableName(sub, joinedSubclass),
- null,
- false,
- metadataBuildingContext,
- false)
-
- joinedSubclass.table = mytable
- if (LOG.isInfoEnabled()) {
- LOG.info('Mapping joined-subclass: {} -> {}', joinedSubclass.entityName, joinedSubclass.table.name)
- }
-
- SimpleValue key = new DependantValue(metadataBuildingContext, mytable, joinedSubclass.identifier)
- joinedSubclass.key = key
- HibernatePersistentProperty identifier = sub.identity
- String columnName =
- columnNameForPropertyAndPathFetcher.getColumnNameForPropertyAndPath(identifier, EMPTY_PATH, null)
- simpleValueColumnBinder.bindSimpleValue(key, identifier.type.name, columnName, false)
-
- joinedSubclass.createPrimaryKey()
- joinedSubclass.createForeignKey()
-
- return joinedSubclass
- }
-
- private String getJoinedSubClassTableName(GrailsHibernatePersistentEntity sub, PersistentClass model) {
-
- String logicalTableName = GrailsHibernateUtil.unqualify(model.entityName)
- String physicalTableName = sub.getTableName(namingStrategy)
-
- String schemaName = sub.getSchema(mappings)
- String catalogName = sub.getCatalog(mappings)
-
- mappings.addTableNameBinding(schemaName, catalogName, logicalTableName, physicalTableName, null)
- return physicalTableName
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ManyToOneBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ManyToOneBinder.groovy
deleted file mode 100644
index 1ed09cfc79..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ManyToOneBinder.groovy
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import org.hibernate.boot.spi.MetadataBuildingContext
-import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment
-import org.hibernate.mapping.Collection
-import org.hibernate.mapping.ManyToOne
-import org.hibernate.mapping.Table
-
-import org.grails.orm.hibernate.cfg.ColumnConfig
-import org.grails.orm.hibernate.cfg.HibernateCompositeIdentity
-import org.grails.orm.hibernate.cfg.JoinTable
-import org.grails.orm.hibernate.cfg.Mapping
-import org.grails.orm.hibernate.cfg.PersistentEntityNamingStrategy
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateAssociation
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateManyToManyProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateManyToOneProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateOneToOneProperty
-
-import static org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsDomainBinder.FOREIGN_KEY_SUFFIX
-
-@CompileStatic
-@SuppressWarnings('PMD.DataflowAnomalyAnalysis')
-class ManyToOneBinder {
-
- private final MetadataBuildingContext metadataBuildingContext
- private final PersistentEntityNamingStrategy namingStrategy
- private final SimpleValueBinder simpleValueBinder
- private final ManyToOneValuesBinder manyToOneValuesBinder
- private final CompositeIdentifierToManyToOneBinder compositeIdentifierToManyToOneBinder
-
- ManyToOneBinder(
- MetadataBuildingContext metadataBuildingContext,
- PersistentEntityNamingStrategy namingStrategy,
- SimpleValueBinder simpleValueBinder,
- ManyToOneValuesBinder manyToOneValuesBinder,
- CompositeIdentifierToManyToOneBinder compositeIdentifierToManyToOneBinder) {
- this.metadataBuildingContext = metadataBuildingContext
- this.namingStrategy = namingStrategy
- this.simpleValueBinder = simpleValueBinder
- this.manyToOneValuesBinder = manyToOneValuesBinder
- this.compositeIdentifierToManyToOneBinder = compositeIdentifierToManyToOneBinder
- }
-
- ManyToOneBinder(
- MetadataBuildingContext metadataBuildingContext,
- PersistentEntityNamingStrategy namingStrategy,
- JdbcEnvironment jdbcEnvironment) {
- this(
- metadataBuildingContext,
- namingStrategy,
- new SimpleValueBinder(metadataBuildingContext, namingStrategy, jdbcEnvironment),
- new ManyToOneValuesBinder(),
- new CompositeIdentifierToManyToOneBinder(metadataBuildingContext, namingStrategy, jdbcEnvironment))
- }
-
- /** Binds a many-to-one association. */
- ManyToOne bindManyToOne(HibernateManyToOneProperty property, Table table, String path) {
- return doBind(property, property.hibernateAssociatedEntity, table, path)
- }
-
- /** Binds the inverse side of a many-to-many association as a collection element. */
- ManyToOne bindManyToOne(HibernateManyToManyProperty property, String path) {
- Collection collection = property.collection
- HibernateManyToManyProperty otherSide = (HibernateManyToManyProperty) property.hibernateInverseSide
- Table collectionTable = collection.collectionTable
- GrailsHibernatePersistentEntity refDomainClass = otherSide.hibernateOwner
- if (otherSide.isCircular()) {
- prepareCircularManyToMany(otherSide)
- }
- ManyToOne manyToOne = doBind(otherSide, refDomainClass, collectionTable, path)
- manyToOne.referencedEntityName = otherSide.owner.name
- return manyToOne
- }
-
- ManyToOne bindManyToOne(HibernateOneToOneProperty property, String path) {
- return doBind(property, property.hibernateAssociatedEntity, property.table, path)
- }
-
- private ManyToOne doBind(
- HibernateAssociation property,
- GrailsHibernatePersistentEntity refDomainClass,
- Table table,
- String path) {
- ManyToOne manyToOne = new ManyToOne(metadataBuildingContext, table)
- manyToOneValuesBinder.bindManyToOneValues(property, manyToOne)
- Optional<HibernateCompositeIdentity> compositeId = refDomainClass.hibernateCompositeIdentity
- if (compositeId.isPresent()) {
- compositeIdentifierToManyToOneBinder.bindCompositeIdentifierToManyToOne(
- property, manyToOne, compositeId.get(), refDomainClass, path)
- } else {
- simpleValueBinder.bindSimpleValue(property, null, manyToOne, path)
- }
- return manyToOne
- }
-
- private void prepareCircularManyToMany(HibernateManyToManyProperty property) {
- Mapping ownerMapping = property.hibernateOwner.hibernateMappedForm
- if (ownerMapping != null && !ownerMapping.columns.containsKey(property.name)) {
- ownerMapping.columns.put(property.name, property.hibernateMappedForm)
- }
- if (!property.hibernateMappedForm.hasJoinKeyMapping()) {
- JoinTable jt = new JoinTable()
- Optional<HibernateCompositeIdentity> compositeId = property.hibernateOwner.hibernateCompositeIdentity
- List<ColumnConfig> keyColumns = []
- if (compositeId.isPresent() && compositeId.get().propertyNames != null && compositeId.get().propertyNames.length > 0) {
- List<ColumnConfig> joinKeys = property.hibernateMappedForm.joinTable != null ?
- property.hibernateMappedForm.joinTable.keys : null
- String[] propNames = compositeId.get().propertyNames
- if (joinKeys != null && joinKeys.size() == propNames.length) {
- for (int i = 0; i < propNames.length; i++) {
- ColumnConfig cc = new ColumnConfig()
- cc.name = joinKeys.get(i).name
- keyColumns.add(cc)
- }
- } else {
- for (String propName : propNames) {
- ColumnConfig cc = new ColumnConfig()
- cc.name = namingStrategy.resolveColumnName(propName) + FOREIGN_KEY_SUFFIX
- keyColumns.add(cc)
- }
- }
- } else {
- ColumnConfig cc = new ColumnConfig()
- cc.name = namingStrategy.resolveColumnName(property.name) + FOREIGN_KEY_SUFFIX
- keyColumns.add(cc)
- }
- jt.keys = keyColumns
- property.hibernateMappedForm.joinTable = jt
- }
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/NaturalIdentifierBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/NaturalIdentifierBinder.groovy
deleted file mode 100644
index e371374419..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/NaturalIdentifierBinder.groovy
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import org.hibernate.mapping.PersistentClass
-import org.hibernate.mapping.UniqueKey
-
-import org.grails.orm.hibernate.cfg.NaturalId
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePropertyIdentity
-import org.grails.orm.hibernate.cfg.domainbinding.util.UniqueNameGenerator
-
-@CompileStatic
-class NaturalIdentifierBinder {
-
- private final UniqueNameGenerator uniqueNameGenerator
-
- NaturalIdentifierBinder(UniqueNameGenerator uniqueNameGenerator) {
- this.uniqueNameGenerator = uniqueNameGenerator
- }
-
- NaturalIdentifierBinder() {
- this(new UniqueNameGenerator())
- }
-
- void bindNaturalIdentifier(
- GrailsHibernatePersistentEntity persistentEntity, PersistentClass persistentClass) {
- HibernatePropertyIdentity identity = persistentEntity.hibernateMappedForm.identity
- if (identity == null) {
- return
- }
- NaturalId natural = identity.natural
- if (natural == null) {
- return
- }
- Optional<UniqueKey> uniqueKey = natural.createUniqueKey(persistentClass)
- if (uniqueKey.isPresent()) {
- UniqueKey uk = uniqueKey.get()
- uniqueNameGenerator.setGeneratedUniqueName(uk)
- persistentClass.table.addUniqueKey(uk)
- }
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/OneToOneBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/OneToOneBinder.groovy
deleted file mode 100644
index df13b6427a..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/OneToOneBinder.groovy
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import org.hibernate.boot.spi.MetadataBuildingContext
-import org.hibernate.mapping.OneToOne
-import org.hibernate.mapping.PersistentClass
-import org.hibernate.mapping.Table
-
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateOneToOneProperty
-
-@CompileStatic
-class OneToOneBinder {
-
- private final MetadataBuildingContext metadataBuildingContext
- private final SimpleValueBinder simpleValueBinder
-
- OneToOneBinder(MetadataBuildingContext metadataBuildingContext, SimpleValueBinder simpleValueBinder) {
- this.metadataBuildingContext = metadataBuildingContext
- this.simpleValueBinder = simpleValueBinder
- }
-
- OneToOne bindOneToOne(final HibernateOneToOneProperty property, String path) {
- Table table = property.table
- PersistentClass owner = property.hibernateOwner.persistentClass
- OneToOne oneToOne = new OneToOne(metadataBuildingContext, table, owner)
-
- oneToOne.constrained = property.isHibernateConstrained()
- oneToOne.foreignKeyType = property.hibernateForeignKeyDirection
- oneToOne.alternateUniqueKey = true
- oneToOne.fetchMode = property.hibernateFetchMode
- oneToOne.referencedEntityName = property.hibernateReferencedEntityName
- oneToOne.propertyName = property.name
- oneToOne.referenceToPrimaryKey = false
-
- if (property.needsSimpleValueBinding()) {
- simpleValueBinder.bindSimpleValue(property, null, oneToOne, path)
- }
- else {
- oneToOne.referencedPropertyName = property.hibernateReferencedPropertyName
- }
- return oneToOne
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/PropertyBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/PropertyBinder.groovy
deleted file mode 100644
index 5f3469ebf4..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/PropertyBinder.groovy
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import org.codehaus.groovy.transform.trait.Traits
-import org.hibernate.boot.spi.AccessType
-import org.hibernate.mapping.Property
-import org.hibernate.mapping.Value
-
-import org.grails.datastore.mapping.model.types.Association
-import org.grails.datastore.mapping.reflect.EntityReflector
-import org.grails.orm.hibernate.access.TraitPropertyAccessStrategy
-import org.grails.orm.hibernate.cfg.PropertyConfig
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateAssociation
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty
-import org.grails.orm.hibernate.cfg.domainbinding.util.CascadeBehaviorFetcher
-
-@CompileStatic
-class PropertyBinder {
-
- private final CascadeBehaviorFetcher cascadeBehaviorFetcher
-
- PropertyBinder(CascadeBehaviorFetcher cascadeBehaviorFetcher) {
- this.cascadeBehaviorFetcher = cascadeBehaviorFetcher
- }
-
- PropertyBinder() {
- this(new CascadeBehaviorFetcher())
- }
-
- /**
- * Decides how Hibernate reads and writes the property of a real instance: the mapping's {@code accessType}
- * ({@code property} unless the mapping says {@code field}), and the trait accessor for a trait-implemented getter
- * read by field.
- *
- * @param persistentProperty The grails property instance
- * @return The Hibernate property accessor name
- */
- String accessorName(HibernatePersistentProperty persistentProperty) {
- PropertyConfig config = persistentProperty.hibernateMappedForm
- AccessType accessType = AccessType.getAccessStrategy(config != null ? config.accessType : new PropertyConfig().accessType)
- return accessType == AccessType.FIELD ?
- Optional.ofNullable(persistentProperty.reader)
- .map { EntityReflector.PropertyReader reader -> reader.getter() }
- .map { getter -> getter.getAnnotation(Traits.Implemented) }
- .map { annotation -> TraitPropertyAccessStrategy.name }
- .orElse(accessType.type) :
- accessType.type
- }
-
- /**
- * Binds a property to Hibernate runtime meta model. Deals with cascade strategy based on the
- * Grails domain model
- *
- * @param persistentProperty The grails property instance
- * @param value The Hibernate value
- * @return The Hibernate property
- */
- Property bindProperty(HibernatePersistentProperty persistentProperty, Value value) {
- Property prop = new Property()
- prop.value = value
- // set the property name
- prop.name = persistentProperty.name
- PropertyConfig config = persistentProperty.hibernateMappedForm
- if (config == null) {
- config = new PropertyConfig()
- }
-
- // The mapping's insertable/updatable flags; the value's columns can only narrow them further, below. The
- // many-to-one side of a bidirectional list mapping is left to its columns, as it always was.
- boolean insertable = true
- boolean updatable = true
- if (!(persistentProperty instanceof HibernateAssociation &&
- ((HibernateAssociation) persistentProperty).isBidirectionalManyToOneWithListMapping(prop))) {
- insertable = config.insertable
- updatable = config.updatable
- }
-
- prop.propertyAccessorName = accessorName(persistentProperty)
-
- prop.optional = persistentProperty.isNullable()
- // No enum type is excluded here on its own account: a plain scalar enum property is never an
- // Association, so instanceof Association<?> already excludes it. A hasMany-of-enum collection IS
- // an Association (Basic), and CascadeBehaviorFetcher already dispatches Basic -> ALL correctly,
- // so it must go through the same path as every other collection type.
- if (persistentProperty instanceof Association) {
- prop.cascade = cascadeBehaviorFetcher.getCascadeBehaviour((Association) persistentProperty)
- }
-
- // Use centralized laziness determination
- prop.lazy = persistentProperty.isLazy()
-
- // An explicit false in the mapping is honoured, and a value without insertable/updatable columns
- // (a formula, a collection, an inverse side) is never written.
- prop.insertable = insertable && value.hasAnyInsertableColumns()
- prop.updatable = updatable && value.hasAnyUpdatableColumns()
-
- return prop
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/RootBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/RootBinder.groovy
deleted file mode 100644
index 6e12cf4595..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/RootBinder.groovy
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import java.util.stream.Stream
-
-import groovy.transform.CompileStatic
-import jakarta.annotation.Nonnull
-import org.hibernate.boot.spi.InFlightMetadataCollector
-import org.hibernate.mapping.RootClass
-import org.hibernate.mapping.Subclass
-import org.slf4j.Logger
-import org.slf4j.LoggerFactory
-
-import org.grails.orm.hibernate.cfg.MappingCacheHolder
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentEntity
-import org.grails.orm.hibernate.cfg.domainbinding.util.MultiTenantFilterBinder
-
-/** Binder for root classes. */
-@CompileStatic
-@SuppressWarnings('PMD.DataflowAnomalyAnalysis')
-class RootBinder {
-
- private static final Logger LOG = LoggerFactory.getLogger(RootBinder)
-
- private final String dataSourceName
- private final MultiTenantFilterBinder multiTenantFilterBinder
- private final SubClassBinder subClassBinder
- private final RootPersistentClassCommonValuesBinder rootPersistentClassCommonValuesBinder
- private final DiscriminatorPropertyBinder discriminatorPropertyBinder
- private final InFlightMetadataCollector mappings
- private final MappingCacheHolder mappingCacheHolder
-
- RootBinder(
- String dataSourceName,
- MultiTenantFilterBinder multiTenantFilterBinder,
- SubClassBinder subClassBinder,
- RootPersistentClassCommonValuesBinder rootPersistentClassCommonValuesBinder,
- DiscriminatorPropertyBinder discriminatorPropertyBinder,
- InFlightMetadataCollector mappings,
- MappingCacheHolder mappingCacheHolder) {
- this.dataSourceName = dataSourceName
- this.multiTenantFilterBinder = multiTenantFilterBinder
- this.subClassBinder = subClassBinder
- this.rootPersistentClassCommonValuesBinder = rootPersistentClassCommonValuesBinder
- this.discriminatorPropertyBinder = discriminatorPropertyBinder
- this.mappings = mappings
- this.mappingCacheHolder = mappingCacheHolder
- }
-
- /**
- * Binds a root class (one with no super classes) to the runtime meta model based on the supplied
- * Grails domain class
- *
- * @param entity The Grails domain class
- */
- void bindRoot(@Nonnull HibernatePersistentEntity entity) {
- if (mappings.getEntityBinding(entity.name) != null) {
- if (LOG.isWarnEnabled()) {
- LOG.warn('[RootBinder] Class [{}] is already mapped, skipping.. ', entity.name)
- }
- return
- }
-
- Collection<HibernatePersistentEntity> children = entity.getChildEntities(dataSourceName)
- RootClass root = rootPersistentClassCommonValuesBinder.bindRoot(entity)
-
- if (!children.isEmpty() && entity.isTablePerHierarchy()) {
- discriminatorPropertyBinder.bindDiscriminatorProperty(root)
- }
-
- // bind the sub classes
- children.stream().flatMap(sub -> getSubclassStream(sub, root)).forEach(subClass -> addSubclass(subClass))
-
- multiTenantFilterBinder.bind(entity, root)
-
- mappings.addEntityBinding(root)
- }
-
- private void addSubclass(Subclass subClass) {
- // Hibernate resolves a class's subclasses through its direct superclass, so a nested subclass
- // must be added to its own parent rather than to the root of the hierarchy
- subClass.superclass.addSubclass(subClass)
- mappings.addEntityBinding(subClass)
- }
-
- private Stream<Subclass> getSubclassStream(HibernatePersistentEntity entity, RootClass root) {
- mappingCacheHolder.cacheMapping(entity)
- return subClassBinder.bindSubClass(entity, root).stream()
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/RootPersistentClassCommonValuesBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/RootPersistentClassCommonValuesBinder.groovy
deleted file mode 100644
index c6826617d3..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/RootPersistentClassCommonValuesBinder.groovy
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import jakarta.annotation.Nonnull
-import org.hibernate.boot.spi.InFlightMetadataCollector
-import org.hibernate.boot.spi.MetadataBuildingContext
-import org.hibernate.mapping.RootClass
-import org.hibernate.mapping.Table
-import org.slf4j.Logger
-import org.slf4j.LoggerFactory
-
-import org.grails.orm.hibernate.cfg.CacheConfig
-import org.grails.orm.hibernate.cfg.Mapping
-import org.grails.orm.hibernate.cfg.PersistentEntityNamingStrategy
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentEntity
-
-@CompileStatic
-class RootPersistentClassCommonValuesBinder {
-
- static final Logger LOG = LoggerFactory.getLogger(RootPersistentClassCommonValuesBinder)
-
- private final MetadataBuildingContext metadataBuildingContext
- private final PersistentEntityNamingStrategy namingStrategy
- private final IdentityBinder identityBinder
- private final VersionBinder versionBinder
- private final ClassBinder classBinder
- private final ClassPropertiesBinder classPropertiesBinder
- private final InFlightMetadataCollector mappings
-
- RootPersistentClassCommonValuesBinder(
- MetadataBuildingContext metadataBuildingContext,
- PersistentEntityNamingStrategy namingStrategy,
- IdentityBinder identityBinder,
- VersionBinder versionBinder,
- ClassBinder classBinder,
- ClassPropertiesBinder classPropertiesBinder,
- InFlightMetadataCollector mappings) {
- this.metadataBuildingContext = metadataBuildingContext
- this.namingStrategy = namingStrategy
- this.identityBinder = identityBinder
- this.versionBinder = versionBinder
- this.classBinder = classBinder
- this.classPropertiesBinder = classPropertiesBinder
- this.mappings = mappings
- }
-
- RootClass bindRoot(@Nonnull HibernatePersistentEntity hibernatePersistentEntity) {
-
- RootClass root = new RootClass(this.metadataBuildingContext)
- classBinder.bindClass(hibernatePersistentEntity, root)
-
- // get the schema and catalog names from the configuration
- Mapping gormMapping = hibernatePersistentEntity.hibernateMappedForm
-
- hibernatePersistentEntity.configureDerivedProperties()
- CacheConfig cc = gormMapping.cache
- if (cc != null && cc.enabled) {
- root.cacheConcurrencyStrategy = cc.usage.toString()
- root.cached = true
- if ('read-only'.equalsIgnoreCase(cc.usage.toString())) {
- root.mutable = false
- }
- root.setLazyPropertiesCacheable(
- !'non-lazy'.equalsIgnoreCase(cc.include.toString()))
- }
-
- String schema = hibernatePersistentEntity.getSchema(mappings)
-
- String catalog = hibernatePersistentEntity.getCatalog(mappings)
-
- // create the table
- Table table = mappings.addTable(
- schema,
- catalog,
- hibernatePersistentEntity.getTableName(namingStrategy),
- null,
- hibernatePersistentEntity.isTableAbstract(),
- metadataBuildingContext,
- false)
- root.table = table
- if (LOG.isDebugEnabled()) {
- LOG.debug('[GrailsDomainBinder] Mapping Grails domain class: {} -> {}', hibernatePersistentEntity.name, root.table.name)
- }
-
- identityBinder.bindIdentity(hibernatePersistentEntity)
- versionBinder.bindVersion(hibernatePersistentEntity.version, root)
- root.createPrimaryKey()
- classPropertiesBinder.bindClassProperties(hibernatePersistentEntity)
-
- return root
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SimpleIdBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SimpleIdBinder.groovy
deleted file mode 100644
index 01f81dd26d..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SimpleIdBinder.groovy
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import jakarta.annotation.Nonnull
-import org.hibernate.MappingException
-import org.hibernate.boot.spi.MetadataBuildingContext
-import org.hibernate.mapping.BasicValue
-import org.hibernate.mapping.Property
-import org.hibernate.mapping.RootClass
-
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentEntity
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateSimpleIdentityProperty
-import org.grails.orm.hibernate.cfg.domainbinding.util.BasicValueCreator
-
-import static org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsDomainBinder.EMPTY_PATH
-
-/** The simple id binder class. */
-@CompileStatic
-@SuppressWarnings('PMD.DataflowAnomalyAnalysis')
-class SimpleIdBinder {
-
- private final MetadataBuildingContext metadataBuildingContext
- private final BasicValueCreator basicValueCreator
- private final SimpleValueBinder simpleValueBinder
- private final PropertyBinder propertyBinder
-
- SimpleIdBinder(
- MetadataBuildingContext metadataBuildingContext,
- BasicValueCreator basicValueCreator,
- SimpleValueBinder simpleValueBinder,
- PropertyBinder propertyBinder) {
- this.metadataBuildingContext = metadataBuildingContext
- this.basicValueCreator = basicValueCreator
- this.simpleValueBinder = simpleValueBinder
- this.propertyBinder = propertyBinder
- }
-
- MetadataBuildingContext getMetadataBuildingContext() {
- return metadataBuildingContext
- }
-
- void bindSimpleId(@Nonnull HibernatePersistentEntity persistentEntity) {
- if (persistentEntity.identityProperty instanceof HibernateSimpleIdentityProperty) {
- HibernateSimpleIdentityProperty simpleIdentityProperty =
- (HibernateSimpleIdentityProperty) persistentEntity.identityProperty
- RootClass rootClass = persistentEntity.rootClass
- BasicValue id = basicValueCreator.bindBasicValue(simpleIdentityProperty)
- Property idProperty = new Property()
- idProperty.name = simpleIdentityProperty.name
- idProperty.value = id
- rootClass.declaredIdentifierProperty = idProperty
- rootClass.identifier = id
- // set type
- simpleValueBinder.bindSimpleValue(simpleIdentityProperty, null, id, EMPTY_PATH)
-
- // bind property
- Property prop = propertyBinder.bindProperty(simpleIdentityProperty, id)
- // set identifier property
- rootClass.identifierProperty = prop
-
- return
- }
- throw new MappingException("Invalid simple id binding for entity [${persistentEntity.name}]".toString())
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SimpleValueBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SimpleValueBinder.groovy
deleted file mode 100644
index 8718a755ab..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SimpleValueBinder.groovy
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import jakarta.annotation.Nonnull
-import org.hibernate.boot.spi.MetadataBuildingContext
-import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment
-import org.hibernate.mapping.BasicValue
-import org.hibernate.mapping.Column
-import org.hibernate.mapping.DependantValue
-import org.hibernate.mapping.Formula
-import org.hibernate.mapping.SimpleValue
-import org.hibernate.mapping.Table
-
-import org.grails.datastore.mapping.model.types.TenantId
-import org.grails.orm.hibernate.cfg.ColumnConfig
-import org.grails.orm.hibernate.cfg.PersistentEntityNamingStrategy
-import org.grails.orm.hibernate.cfg.PropertyConfig
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty
-import org.grails.orm.hibernate.cfg.domainbinding.util.BasicValueCreator
-
-@CompileStatic
-@SuppressWarnings('PMD.NullAssignment')
-class SimpleValueBinder {
-
- private final MetadataBuildingContext metadataBuildingContext
- private final ColumnConfigToColumnBinder columnConfigToColumnBinder
- private final ColumnBinder columnBinder
- private final BasicValueCreator basicValueCreator
-
- /** Private constructor that accepts all collaborators. */
- private SimpleValueBinder(
- MetadataBuildingContext metadataBuildingContext,
- ColumnConfigToColumnBinder columnConfigToColumnBinder,
- ColumnBinder columnBinder,
- BasicValueCreator basicValueCreator) {
- this.metadataBuildingContext = metadataBuildingContext
- this.columnConfigToColumnBinder = columnConfigToColumnBinder
- this.columnBinder = columnBinder
- this.basicValueCreator = basicValueCreator
- }
-
- SimpleValueBinder(
- MetadataBuildingContext metadataBuildingContext,
- PersistentEntityNamingStrategy namingStrategy,
- JdbcEnvironment jdbcEnvironment) {
- this(
- metadataBuildingContext,
- new ColumnConfigToColumnBinder(),
- new ColumnBinder(namingStrategy, jdbcEnvironment.dialect),
- new BasicValueCreator(metadataBuildingContext, jdbcEnvironment, namingStrategy))
- }
-
- BasicValue bindBasicValue(
- @Nonnull HibernatePersistentProperty property,
- HibernatePersistentProperty parentProperty,
- String path) {
- BasicValue basicValue = basicValueCreator.bindBasicValue(property)
- bindSimpleValue(property, parentProperty, basicValue, path)
- return basicValue
- }
-
- SimpleValue bindSimpleValue(
- @Nonnull HibernatePersistentProperty property,
- HibernatePersistentProperty parentProperty,
- SimpleValue simpleValue,
- String path) {
-
- PropertyConfig propertyConfig = property.hibernateMappedForm
- String typeName = property.getTypeName(simpleValue)
- simpleValue.typeName = typeName
- simpleValue.setTypeParameters(property.getTypeParameters(simpleValue))
-
- if (propertyConfig.isDerived() && !(property instanceof TenantId)) {
- Formula formula = new Formula()
- formula.formula = propertyConfig.formula
- simpleValue.addFormula(formula)
- } else {
- Table table = simpleValue.table
-
- List<ColumnConfig> columnConfigs = propertyConfig.columns
- if (columnConfigs == null || columnConfigs.isEmpty()) {
- columnConfigs = [null]
- }
- for (ColumnConfig cc : columnConfigs) {
- Column column = new Column()
- columnConfigToColumnBinder.bindColumnConfigToColumn(column, cc, propertyConfig)
- columnBinder.bindColumn(property, parentProperty, column, cc, path, table, typeName)
- if (simpleValue instanceof DependantValue) {
- column.nullable = true
- }
- if (table != null) {
- table.addColumn(column)
- }
- simpleValue.addColumn(column)
- }
- }
- return simpleValue
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SimpleValueColumnBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SimpleValueColumnBinder.groovy
deleted file mode 100644
index f393900b7e..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SimpleValueColumnBinder.groovy
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import org.hibernate.MappingException
-import org.hibernate.boot.spi.MetadataBuildingContext
-import org.hibernate.mapping.BasicValue
-import org.hibernate.mapping.Column
-import org.hibernate.mapping.SimpleValue
-import org.hibernate.mapping.Table
-
-@CompileStatic
-class SimpleValueColumnBinder {
-
- /**
- * Creates a {@link BasicValue}, binds it, and returns it.
- *
- * @param metadataBuildingContext The metadata building context
- * @param table The table the value belongs to
- * @param type The type of the property
- * @param columnName The column name
- * @param nullable Whether it is nullable
- */
- BasicValue bindSimpleValue(
- MetadataBuildingContext metadataBuildingContext,
- Table table,
- String type,
- String columnName,
- boolean nullable) {
- BasicValue basicValue = new BasicValue(metadataBuildingContext, table)
- bindSimpleValue(basicValue, type, columnName, nullable)
- return basicValue
- }
-
- /**
- * Binds a value for the specified parameters to the meta model.
- *
- * @param simpleValue The simple value instance
- * @param type The type of the property
- * @param columnName The property name
- * @param nullable Whether it is nullable
- */
- void bindSimpleValue(SimpleValue simpleValue, String type, String columnName, boolean nullable) {
- Table table = simpleValue.table
- if (table == null) {
- throw new MappingException('SimpleValue must have a table')
- }
- Column column = new Column()
- column.nullable = nullable
- column.value = simpleValue
- column.name = columnName
- table.addColumn(column)
- simpleValue.addColumn(column)
- simpleValue.typeName = type
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SingleTableSubclassBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SingleTableSubclassBinder.groovy
deleted file mode 100644
index 963a594bb2..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SingleTableSubclassBinder.groovy
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import jakarta.annotation.Nonnull
-import org.hibernate.boot.spi.MetadataBuildingContext
-import org.hibernate.mapping.PersistentClass
-import org.hibernate.mapping.SingleTableSubclass
-import org.slf4j.Logger
-import org.slf4j.LoggerFactory
-
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity
-
-/**
- * Binds a sub-class using table-per-hierarchy inheritance mapping
- *
- * @since 8.0
- */
-@CompileStatic
-class SingleTableSubclassBinder {
-
- private static final Logger LOG = LoggerFactory.getLogger(SingleTableSubclassBinder)
-
- private final ClassBinder classBinder
- private final MetadataBuildingContext metadataBuildingContext
-
- SingleTableSubclassBinder(ClassBinder classBinder, MetadataBuildingContext metadataBuildingContext) {
- this.classBinder = classBinder
- this.metadataBuildingContext = metadataBuildingContext
- }
-
- /**
- * Binds a sub-class using table-per-hierarchy inheritance mapping
- *
- * @param sub The Grails domain class instance representing the sub-class
- * @param parent The Hibernate Parent PersistentClass object
- * @return The created SingleTableSubclass
- */
- SingleTableSubclass bindSubClass(@Nonnull GrailsHibernatePersistentEntity sub, PersistentClass parent) {
- SingleTableSubclass subClass = new SingleTableSubclass(parent, metadataBuildingContext)
- classBinder.bindClass(sub, subClass)
- subClass.discriminatorValue = sub.discriminatorValue
- if (LOG.debugEnabled) {
- LOG.debug('Mapping subclass: {} -> {}', subClass.entityName, subClass.table.name)
- }
- return subClass
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SubClassBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SubClassBinder.groovy
deleted file mode 100644
index 4a0b8fb012..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SubClassBinder.groovy
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import jakarta.annotation.Nonnull
-import org.hibernate.mapping.JoinedSubclass
-import org.hibernate.mapping.PersistentClass
-import org.hibernate.mapping.SingleTableSubclass
-import org.hibernate.mapping.Subclass
-import org.hibernate.mapping.UnionSubclass
-
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentEntity
-import org.grails.orm.hibernate.cfg.domainbinding.util.MultiTenantFilterBinder
-
-/** Binder for subclasses. */
-@CompileStatic
-class SubClassBinder {
-
- private final SubclassMappingBinder subclassMappingBinder
- private final MultiTenantFilterBinder multiTenantFilterBinder
- private final String dataSourceName
-
- SubClassBinder(
- SubclassMappingBinder subclassMappingBinder,
- MultiTenantFilterBinder multiTenantFilterBinder,
- String dataSourceName) {
- this.subclassMappingBinder = subclassMappingBinder
- this.multiTenantFilterBinder = multiTenantFilterBinder
- this.dataSourceName = dataSourceName
- }
-
- /**
- * Binds a sub class.
- *
- * @param sub The sub domain class instance
- * @param parent The parent persistent class instance
- * @return The list of subclasses created
- */
- List<Subclass> bindSubClass(@Nonnull HibernatePersistentEntity sub, PersistentClass parent) {
- Subclass subClass = subclassMappingBinder.createSubclassMapping(sub, parent)
- sub.setPersistentClass(subClass)
- bindMultiTenantFilter(sub, subClass)
- List<Subclass> subclasses = new ArrayList<>()
- subclasses.add(subClass)
- for (HibernatePersistentEntity sub1 : sub.getChildEntities(dataSourceName)) {
- subclasses.addAll(bindSubClass(sub1, subClass))
- }
- return subclasses
- }
-
- private void bindMultiTenantFilter(HibernatePersistentEntity sub, Subclass subClass) {
- if (subClass instanceof SingleTableSubclass) {
- multiTenantFilterBinder.bind(sub, (SingleTableSubclass) subClass)
- }
- else if (subClass instanceof JoinedSubclass) {
- multiTenantFilterBinder.bind(sub, (JoinedSubclass) subClass)
- }
- else if (subClass instanceof UnionSubclass) {
- multiTenantFilterBinder.bind(sub, (UnionSubclass) subClass)
- }
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SubclassMappingBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SubclassMappingBinder.groovy
deleted file mode 100644
index 9e5fbd2e87..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SubclassMappingBinder.groovy
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import org.hibernate.mapping.PersistentClass
-import org.hibernate.mapping.Subclass
-
-import org.grails.orm.hibernate.cfg.GrailsHibernateUtil
-import org.grails.orm.hibernate.cfg.Mapping
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentEntity
-
-@CompileStatic
-class SubclassMappingBinder {
-
- private final JoinedSubClassBinder joinedSubClassBinder
- private final UnionSubclassBinder unionSubclassBinder
- private final SingleTableSubclassBinder singleTableSubclassBinder
- private final ClassPropertiesBinder classPropertiesBinder
-
- SubclassMappingBinder(
- JoinedSubClassBinder joinedSubClassBinder,
- UnionSubclassBinder unionSubclassBinder,
- SingleTableSubclassBinder singleTableSubclassBinder,
- ClassPropertiesBinder classPropertiesBinder) {
- this.joinedSubClassBinder = joinedSubClassBinder
- this.unionSubclassBinder = unionSubclassBinder
- this.singleTableSubclassBinder = singleTableSubclassBinder
- this.classPropertiesBinder = classPropertiesBinder
- }
-
- Subclass createSubclassMapping(HibernatePersistentEntity subEntity, PersistentClass parent) {
- Subclass subClass
- subEntity.configureDerivedProperties()
- Mapping m = subEntity.hibernateMappedForm
- if (subEntity.isJoinedSubclass()) {
- subClass = joinedSubClassBinder.bindJoinedSubClass(subEntity, parent)
- }
- else if (subEntity.isUnionSubclass()) {
- subClass = unionSubclassBinder.bindUnionSubclass(subEntity, parent)
- }
- else {
- subClass = singleTableSubclassBinder.bindSubClass(subEntity, parent)
- }
-
- Integer batchSize = m.batchSize
- subClass.batchSize = batchSize != null ? batchSize : -1
- subClass.dynamicUpdate = m.dynamicUpdate
- subClass.dynamicInsert = m.dynamicInsert
- subClass.cached = parent.isCached()
- subClass.setAbstract(subEntity.isAbstract())
- subClass.entityName = subEntity.name
- subClass.jpaEntityName = GrailsHibernateUtil.unqualify(subEntity.name)
- classPropertiesBinder.bindClassProperties(subEntity)
- return subClass
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/UnionSubclassBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/UnionSubclassBinder.groovy
deleted file mode 100644
index 962702e108..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/UnionSubclassBinder.groovy
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import jakarta.annotation.Nonnull
-import org.hibernate.MappingException
-import org.hibernate.boot.spi.InFlightMetadataCollector
-import org.hibernate.boot.spi.MetadataBuildingContext
-import org.hibernate.mapping.PersistentClass
-import org.hibernate.mapping.Table
-import org.hibernate.mapping.UnionSubclass
-import org.slf4j.Logger
-import org.slf4j.LoggerFactory
-
-import org.grails.orm.hibernate.cfg.PersistentEntityNamingStrategy
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity
-
-/**
- * Binds a union sub-class mapping using table-per-concrete-class
- *
- * @since 8.0
- */
-@CompileStatic
-class UnionSubclassBinder {
-
- private static final Logger LOG = LoggerFactory.getLogger(UnionSubclassBinder)
-
- private final MetadataBuildingContext metadataBuildingContext
- private final PersistentEntityNamingStrategy namingStrategy
- private final ClassBinder classBinder
- private final InFlightMetadataCollector mappings
-
- UnionSubclassBinder(
- MetadataBuildingContext metadataBuildingContext,
- PersistentEntityNamingStrategy namingStrategy,
- ClassBinder classBinder,
- InFlightMetadataCollector mappings) {
- this.metadataBuildingContext = metadataBuildingContext
- this.namingStrategy = namingStrategy
- this.classBinder = classBinder
- this.mappings = mappings
- }
-
- /**
- * Binds a union sub-class mapping using table-per-concrete-class
- *
- * @param subClass The Grails sub class
- * @param parent The Hibernate Parent PersistentClass object
- * @return The created UnionSubclass
- */
- UnionSubclass bindUnionSubclass(@Nonnull GrailsHibernatePersistentEntity subClass, PersistentClass parent)
- throws MappingException {
- UnionSubclass unionSubclass = new UnionSubclass(parent, metadataBuildingContext)
- classBinder.bindClass(subClass, unionSubclass)
-
- String schema = subClass.getSchema(mappings)
- String catalog = subClass.getCatalog(mappings)
-
- Table denormalizedSuperTable = unionSubclass.superclass.table
- Table mytable = mappings.addDenormalizedTable(
- schema,
- catalog,
- subClass.getTableName(namingStrategy),
- Boolean.TRUE.equals(unionSubclass.isAbstract()),
- null,
- denormalizedSuperTable,
- metadataBuildingContext)
- unionSubclass.table = mytable
- unionSubclass.className = subClass.name
-
- if (LOG.isInfoEnabled()) {
- LOG.info('Mapping union-subclass: {} -> {}', unionSubclass.entityName, unionSubclass.table.name)
- }
- return unionSubclass
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/VersionBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/VersionBinder.groovy
deleted file mode 100644
index 1af7acb6e3..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/VersionBinder.groovy
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.binder
-
-import groovy.transform.CompileStatic
-import org.hibernate.boot.spi.MetadataBuildingContext
-import org.hibernate.engine.OptimisticLockStyle
-import org.hibernate.mapping.BasicValue
-import org.hibernate.mapping.Property
-import org.hibernate.mapping.RootClass
-import org.hibernate.mapping.Table
-
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty
-
-import java.util.function.BiFunction
-
-import static org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsDomainBinder.EMPTY_PATH
-
-@CompileStatic
-class VersionBinder {
-
- private final MetadataBuildingContext metadataBuildingContext
- private final SimpleValueBinder simpleValueBinder
- private final PropertyBinder propertyBinder
- private final BiFunction<MetadataBuildingContext, Table, BasicValue> basicValueFactory
-
- VersionBinder(
- MetadataBuildingContext metadataBuildingContext,
- SimpleValueBinder simpleValueBinder,
- PropertyBinder propertyBinder,
- BiFunction<MetadataBuildingContext, Table, BasicValue> basicValueFactory) {
- this.metadataBuildingContext = metadataBuildingContext
- this.simpleValueBinder = simpleValueBinder
- this.propertyBinder = propertyBinder
- this.basicValueFactory = basicValueFactory
- }
-
- void bindVersion(HibernatePersistentProperty version, RootClass entity) {
-
- if (version != null) {
-
- BasicValue val = basicValueFactory.apply(metadataBuildingContext, entity.table)
-
- // set type — bindSimpleValue resolves the Java property type (e.g. "java.lang.Long")
- // or the explicit DSL type if one was configured; no override needed here
- simpleValueBinder.bindSimpleValue(version, null, val, EMPTY_PATH)
-
- Property prop = propertyBinder.bindProperty(version, val)
- prop.lazy = false
- val.nullValue = 'undefined'
- entity.version = prop
- entity.declaredVersion = prop
- entity.optimisticLockStyle = OptimisticLockStyle.VERSION
- entity.addProperty(prop)
- }
- else {
- entity.optimisticLockStyle = OptimisticLockStyle.NONE
- }
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/collectionType/CollectionHolder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/collectionType/CollectionHolder.groovy
deleted file mode 100644
index d1e18c0c44..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/collectionType/CollectionHolder.groovy
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.collectionType
-
-import groovy.transform.CompileStatic
-import org.hibernate.boot.spi.MetadataBuildingContext
-
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyProperty
-
-/** Collection holder. */
-@CompileStatic
-final class CollectionHolder {
-
- private final Map<Class<?>, CollectionType> map
-
- CollectionHolder(Map<Class<?>, CollectionType> map) {
- this.map = map
- }
-
- /** Creates a new {@link CollectionHolder} instance. */
- CollectionHolder(MetadataBuildingContext buildingContext) {
- this(Map.ofEntries(
- Map.entry(Set, new SetCollectionType(buildingContext)),
- Map.entry(SortedSet, new SetCollectionType(buildingContext)),
- Map.entry(List, new ListCollectionType(buildingContext)),
- Map.entry(Collection, new BagCollectionType(buildingContext)),
- Map.entry(Map, new MapCollectionType(buildingContext))))
- }
-
- Map<Class<?>, CollectionType> map() {
- return map
- }
-
- /** Get. */
- CollectionType get(Class<?> collectionClass) {
- return map.get(collectionClass)
- }
-
- org.hibernate.mapping.Collection create(HibernateToManyProperty property) {
- return map.get(property.type).create(property, property.persistentClass)
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/collectionType/CollectionType.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/collectionType/CollectionType.groovy
deleted file mode 100644
index 3de2a721fe..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/collectionType/CollectionType.groovy
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.collectionType
-
-import groovy.transform.CompileStatic
-import org.hibernate.MappingException
-import org.hibernate.boot.spi.MetadataBuildingContext
-import org.hibernate.mapping.Collection
-import org.hibernate.mapping.PersistentClass
-
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyProperty
-
-/**
- * A Collection type, for the moment only Set is supported
- *
- * @author Graeme
- */
-@CompileStatic
-abstract class CollectionType {
-
- /** The clazz. */
- protected final Class<?> clazz
-
- /** The building context. */
- protected final MetadataBuildingContext buildingContext
-
- /** Creates a new {@link CollectionType} instance. */
- protected CollectionType(Class<?> clazz, MetadataBuildingContext buildingContext) {
- this.clazz = clazz
- this.buildingContext = buildingContext
- }
-
- /** Create collection. */
- abstract Collection createCollection(PersistentClass owner)
-
- /** Create. */
- Collection create(HibernateToManyProperty property, PersistentClass owner) throws MappingException {
- Collection coll = createCollection(owner)
- coll.setCollectionTable(owner.table)
- String typeName = getTypeName(property)
- if (typeName != null && clazz.name != typeName) {
- coll.setTypeName(typeName)
- }
- return coll
- }
-
- @Override
- String toString() {
- return clazz.name
- }
-
- /** Gets the type name. */
- String getTypeName(HibernateToManyProperty property) {
- return property.typeName
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ColumnConfigToColumnBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/column/ColumnConfigToColumnBinder.groovy
similarity index 97%
rename from grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ColumnConfigToColumnBinder.groovy
rename to grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/column/ColumnConfigToColumnBinder.groovy
index 8d1a84c99f..8b7d8fdae3 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ColumnConfigToColumnBinder.groovy
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/column/ColumnConfigToColumnBinder.groovy
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.grails.orm.hibernate.cfg.domainbinding.binder
+package org.grails.orm.hibernate.cfg.domainbinding.column
import groovy.transform.CompileStatic
import org.hibernate.mapping.Column
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/IndexBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/column/IndexBinder.groovy
similarity index 97%
rename from grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/IndexBinder.groovy
rename to grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/column/IndexBinder.groovy
index 56eb2c0f4b..db57e6988c 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/IndexBinder.groovy
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/column/IndexBinder.groovy
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.grails.orm.hibernate.cfg.domainbinding.binder
+package org.grails.orm.hibernate.cfg.domainbinding.column
import groovy.transform.CompileStatic
import jakarta.annotation.Nonnull
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/NumericColumnConstraintsBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/column/NumericColumnConstraintsBinder.groovy
similarity index 98%
rename from grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/NumericColumnConstraintsBinder.groovy
rename to grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/column/NumericColumnConstraintsBinder.groovy
index b008e961ed..d59f237b71 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/NumericColumnConstraintsBinder.groovy
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/column/NumericColumnConstraintsBinder.groovy
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.grails.orm.hibernate.cfg.domainbinding.binder
+package org.grails.orm.hibernate.cfg.domainbinding.column
import groovy.transform.CompileStatic
import org.codehaus.groovy.runtime.DefaultGroovyMethods
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/StringColumnConstraintsBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/column/StringColumnConstraintsBinder.groovy
similarity index 98%
rename from grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/StringColumnConstraintsBinder.groovy
rename to grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/column/StringColumnConstraintsBinder.groovy
index 4bc4610751..c30ea64c63 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/StringColumnConstraintsBinder.groovy
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/column/StringColumnConstraintsBinder.groovy
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.grails.orm.hibernate.cfg.domainbinding.binder
+package org.grails.orm.hibernate.cfg.domainbinding.column
import groovy.transform.CompileStatic
import org.hibernate.Length
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/GrailsHibernatePersistentEntity.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/GrailsHibernatePersistentEntity.groovy
index 64f1dc968c..47aa1359d1 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/GrailsHibernatePersistentEntity.groovy
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/GrailsHibernatePersistentEntity.groovy
@@ -41,12 +41,15 @@ import org.grails.orm.hibernate.cfg.domainbinding.util.ConfigureDerivedPropertie
import org.grails.orm.hibernate.cfg.domainbinding.util.DefaultColumnNameFetcher
import org.grails.orm.hibernate.cfg.domainbinding.util.NamespaceNameExtractor
-import static org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsDomainBinder.DEFAULT_DISCRIMINATOR_COLUMN_NAME
-
/** Common interface for Hibernate persistent entities */
@CompileStatic
interface GrailsHibernatePersistentEntity extends PersistentEntity {
+ /**
+ * The name of the discriminator column of a table-per-hierarchy tree that does not map one.
+ */
+ String DEFAULT_DISCRIMINATOR_COLUMN_NAME = 'class'
+
private static String resolveDiscriminatorValue(DiscriminatorConfig discriminatorConfig) {
return discriminatorConfig.column != null ? discriminatorConfig.column.name : discriminatorConfig.formula
}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateBasicEnumProperty.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateBasicEnumProperty.groovy
index 95aff0173d..820665faea 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateBasicEnumProperty.groovy
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateBasicEnumProperty.groovy
@@ -69,9 +69,8 @@ class HibernateBasicEnumProperty extends HibernateBasicProperty implements Hiber
* collection's join table rather than the owning entity's table. Before the collection
* table has been assigned (e.g. while it is itself being computed), falls back to the
* owning entity's table, matching the pre-collection-binding default. Scoped to the enum
- * subclass because only {@link org.grails.orm.hibernate.cfg.domainbinding.binder.EnumTypeBinder}
- * binds through {@code getTable()}; the non-enum element binding reads the collection
- * table directly.
+ * subclass because only an enum element is bound through {@code getTable()}; the non-enum
+ * element binding reads the collection table directly.
*/
@Override
Table getTable() {
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateEmbeddedCollectionProperty.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateEmbeddedCollectionProperty.groovy
index 0a1c9f0616..67614ddca3 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateEmbeddedCollectionProperty.groovy
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateEmbeddedCollectionProperty.groovy
@@ -43,10 +43,9 @@ class HibernateEmbeddedCollectionProperty extends EmbeddedCollectionWithMapping<
}
/**
- * Returns {@code null} so that {@link org.grails.orm.hibernate.cfg.domainbinding.collectionType.CollectionType}
- * does not set a Hibernate type name on the collection mapping. For embedded value-object collections
- * the element is bound as a Hibernate {@link org.hibernate.mapping.Component}, not as a basic type,
- * so propagating the Java class name here would cause Hibernate to reject it at boot.
+ * Returns {@code null} so that no Hibernate type name is set on the collection mapping. For embedded
+ * value-object collections the element is bound as a Hibernate {@link org.hibernate.mapping.Component},
+ * not as a basic type, so propagating the Java class name here would cause Hibernate to reject it at boot.
*/
@Override
String getTypeName() {
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateEnumProperty.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateEnumProperty.groovy
index e2af950778..1f27c72cd0 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateEnumProperty.groovy
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateEnumProperty.groovy
@@ -37,8 +37,7 @@ import org.grails.orm.hibernate.cfg.domainbinding.util.ColumnNameForPropertyAndP
*
* <p>Use {@code instanceof HibernateEnumProperty} instead of {@code isEnumType()} to branch on
* enum properties at binding time. Each implementation resolves its own enum class and column
- * name so {@link org.grails.orm.hibernate.cfg.domainbinding.binder.EnumTypeBinder} can bind any
- * of them through a single code path.
+ * name so the binding can describe any of them through a single code path.
*/
@CompileStatic
interface HibernateEnumProperty extends HibernatePersistentProperty {
@@ -66,9 +65,9 @@ interface HibernateEnumProperty extends HibernatePersistentProperty {
/**
* Whether this property is a {@code hasMany} basic-collection element rather than a scalar
- * enum-typed property. {@link org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsPropertyBinder}
- * uses this to decide whether to bind it directly here, or let it fall through to the normal
- * to-many collection path (whose element is bound later, from within the collection binder).
+ * enum-typed property. The binding uses this to decide whether to describe it directly here, or let
+ * it fall through to the normal to-many collection path (whose element is described as a collection
+ * element).
*/
default boolean isCollectionElement() {
return false
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateMappingBuilder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateMappingBuilder.groovy
index d5b72e0721..c33ffd4918 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateMappingBuilder.groovy
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateMappingBuilder.groovy
@@ -54,8 +54,8 @@ import org.grails.orm.hibernate.cfg.PropertyDefinitionDelegate
import org.grails.orm.hibernate.cfg.SortConfig
/**
- * Implements the ORM mapping DSL constructing a model that can be evaluated by the
- * GrailsDomainBinder class which maps GORM classes onto the database.
+ * Implements the ORM mapping DSL constructing a model that the domain binding reads to map
+ * GORM classes onto the database.
*
* @author Graeme Rocher
* @since 1.0
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateToManyProperty.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateToManyProperty.groovy
index 2e054112ea..504107e77a 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateToManyProperty.groovy
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateToManyProperty.groovy
@@ -35,12 +35,12 @@ import org.grails.orm.hibernate.cfg.ColumnConfig
import org.grails.orm.hibernate.cfg.JoinTable
import org.grails.orm.hibernate.cfg.PersistentEntityNamingStrategy
import org.grails.orm.hibernate.cfg.PropertyConfig
-import org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsDomainBinder
import org.grails.orm.hibernate.cfg.domainbinding.util.BackticksRemover
import org.grails.orm.hibernate.cfg.domainbinding.util.CascadeBehavior
import static org.grails.orm.hibernate.cfg.GrailsHibernateUtil.qualify
-import static org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsDomainBinder.UNDERSCORE
+import static org.grails.orm.hibernate.cfg.domainbinding.util.DefaultColumnNameFetcher.FOREIGN_KEY_SUFFIX
+import static org.grails.orm.hibernate.cfg.domainbinding.util.DefaultColumnNameFetcher.UNDERSCORE
import static org.grails.orm.hibernate.cfg.domainbinding.util.CascadeBehavior.ALL
import static org.grails.orm.hibernate.cfg.domainbinding.util.CascadeBehavior.ALL_DELETE_ORPHAN
import static org.grails.orm.hibernate.cfg.domainbinding.util.CascadeBehavior.NONE
@@ -240,21 +240,21 @@ interface HibernateToManyProperty extends PropertyWithMapping<PropertyConfig>, H
ColumnConfig column = joinTable?.column
String columnName = column?.name
return columnName != null ? columnName : namingStrategy.resolveColumnName(name) +
- GrailsDomainBinder.UNDERSCORE +
+ UNDERSCORE +
IndexedCollection.DEFAULT_ELEMENT_COLUMN_NAME
}
/**
- * Only reached for a unidirectional {@code hasMany} join table (via {@code CollectionWithJoinTableBinder}).
- * A bidirectional many-to-many join table's foreign-key columns instead go through
- * {@code DefaultColumnNameFetcher#resolveForeignKeyForPropertyDomainClass}, unaffected by this method.
+ * The key column of a unidirectional {@code hasMany} join table. A bidirectional many-to-many join table's foreign-key
+ * columns instead go through {@code DefaultColumnNameFetcher#resolveForeignKeyForPropertyDomainClass}, unaffected by
+ * this method.
*/
default String resolveJoinTableForeignKeyColumnName(PersistentEntityNamingStrategy namingStrategy) {
PropertyConfig mapped = hibernateMappedForm
ColumnConfig columnConfig = mapped?.joinTableColumnConfig
String columnName = columnConfig?.name
return columnName != null ? columnName : resolveAssociatedEntityTableName(namingStrategy) +
- GrailsDomainBinder.FOREIGN_KEY_SUFFIX
+ FOREIGN_KEY_SUFFIX
}
/**
@@ -283,9 +283,9 @@ interface HibernateToManyProperty extends PropertyWithMapping<PropertyConfig>, H
columnName = namingStrategy.resolveColumnName(referencedType.simpleName)
}
else {
- // Both callers of joinTableColumName (BasicCollectionElementBinder, EnumTypeBinder) operate on
- // a HibernateBasicProperty, so referencedType is always the collection's basic element type here,
- // never an associated entity - resolveAssociatedEntityTableName does not apply to this path.
+ // joinTableColumName is only called for a HibernateBasicProperty, so referencedType is always the
+ // collection's basic element type here, never an associated entity - resolveAssociatedEntityTableName
+ // does not apply to this path.
String clazz = namingStrategy.resolveColumnName(referencedType.name)
String prop = namingStrategy.resolveColumnName(name)
columnName = new BackticksRemover().apply(prop) + UNDERSCORE + new BackticksRemover().apply(clazz)
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateVersionProperty.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateVersionProperty.groovy
index 1a1cf0fe02..e6152bdc54 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateVersionProperty.groovy
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateVersionProperty.groovy
@@ -26,8 +26,7 @@ import java.beans.PropertyDescriptor
/**
* Specialisation of {@link HibernateSimpleProperty} used for the optimistic-locking
- * version property. Having a distinct type allows binders (e.g. {@link
- * org.grails.orm.hibernate.cfg.domainbinding.binder.VersionBinder}) to distinguish the
+ * version property. Having a distinct type allows the binding to distinguish the
* version slot from ordinary simple properties and apply version-specific defaults
* (integer type, {@code undefined} null-value, etc.).
*/
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ConstraintFacets.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ConstraintFacets.groovy
index bea0593a0f..5f5ab14f88 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ConstraintFacets.groovy
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ConstraintFacets.groovy
@@ -29,7 +29,7 @@ import groovy.transform.CompileStatic
* before the primary key, which Hibernate then drops after taking its column order for the primary key ({@code null} when there is
* no such key).</p>
*
- * <p>The indexes come from {@code index:} on a column ({@code IndexBinder}), the unique keys from {@code unique:} with
+ * <p>The indexes come from {@code index:} on a column (bound by {@code IndexBinder}), the unique keys from {@code unique:} with
* a group of properties ({@code CreateKeyForProps}). A plain {@code unique: true} is a unique column, not a unique key.</p>
*
* @since 9.0
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 01e77175f4..ff6a19e672 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
@@ -68,11 +68,9 @@ import org.grails.datastore.mapping.model.PersistentProperty
import org.grails.datastore.mapping.model.types.Embedded
import org.grails.orm.hibernate.cfg.HibernateSimpleIdentity
import org.grails.orm.hibernate.cfg.PersistentEntityNamingStrategy
-import org.grails.orm.hibernate.cfg.domainbinding.binder.ColumnConfigToColumnBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.ManyToManyOwnerValidator
-import org.grails.orm.hibernate.cfg.domainbinding.binder.NumericColumnConstraintsBinder
-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.column.ColumnConfigToColumnBinder
+import org.grails.orm.hibernate.cfg.domainbinding.column.NumericColumnConstraintsBinder
+import org.grails.orm.hibernate.cfg.domainbinding.column.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
@@ -118,7 +116,7 @@ class GeneratedDomainClassBinder implements SessionFactoryBuilderFactory {
private final String dataSourceName
private final GeneratedDomainClassLoader classLoader
- private final PropertyBinder propertyBinder = new PropertyBinder()
+ private final PropertyAccessorName propertyAccessorName = new PropertyAccessorName()
private final Map<String, Generated> generatedByName = new HashMap<String, Generated>()
private final MultiTenantFilterDefinitionBinder filterDefinitionBinder = new MultiTenantFilterDefinitionBinder()
private final UniqueNameGenerator uniqueNameGenerator = new UniqueNameGenerator()
@@ -499,7 +497,7 @@ class GeneratedDomainClassBinder implements SessionFactoryBuilderFactory {
/**
* A to-one foreign key to an entity with a composite identifier names the referenced columns, in the order of the identifier's
- * parts sorted by name: the domain binder's {@code CompositeIdentifierToManyToOneBinder} creates it with the referenced columns it
+ * parts sorted by name: the classic composite foreign key binder creates it with the referenced columns it
* collected after {@code Component.sortProperties()}. The key Hibernate derives refers to the primary key without naming its
* columns, and before the schema is built Hibernate puts the columns of such a key in the order it gives the primary key
* (by size and name); a key that names its referenced columns keeps the order it was created in, which is the sorted order of
@@ -643,7 +641,7 @@ class GeneratedDomainClassBinder implements SessionFactoryBuilderFactory {
for (Property property : component.getProperties()) {
HibernatePersistentProperty part = entity.compositeIdentity.find { HibernatePersistentProperty candidate -> candidate.name == property.name }
if (part != null) {
- property.propertyAccessorName = propertyBinder.accessorName(part)
+ property.propertyAccessorName = propertyAccessorName.accessorName(part)
if (property.value instanceof ManyToOne && part instanceof HibernateToOneProperty) {
alignJoinColumns(property.value, generator.toOneFacets((HibernateToOneProperty) part).joinColumns())
}
@@ -675,7 +673,7 @@ class GeneratedDomainClassBinder implements SessionFactoryBuilderFactory {
PersistentProperty<?> persistentProperty = owner.identity?.name == property.name ?
owner.identity : owner.getPropertyByName(property.name)
if (persistentProperty instanceof HibernatePersistentProperty) {
- property.propertyAccessorName = propertyBinder.accessorName((HibernatePersistentProperty) persistentProperty)
+ property.propertyAccessorName = propertyAccessorName.accessorName((HibernatePersistentProperty) persistentProperty)
}
if (property.value instanceof ManyToOne && persistentProperty instanceof HibernateToOneProperty) {
alignJoinColumns(property.value, generator.toOneFacets((HibernateToOneProperty) persistentProperty).joinColumns())
@@ -690,7 +688,7 @@ class GeneratedDomainClassBinder implements SessionFactoryBuilderFactory {
alignCollectionIndexes((Collection) property.value, (HibernatePersistentProperty) persistentProperty, qualifier)
}
if (property.value instanceof Component && persistentProperty instanceof Embedded) {
- // PropertyBinder marks the property lazy when the mapping says lazy: true; @Basic(fetch = LAZY) on an @Embedded is ignored
+ // the classic property binder marks the property lazy when the mapping says lazy: true; @Basic(fetch = LAZY) on an @Embedded is ignored
// by Hibernate's annotation binder, so the mapping's flag is set on the bound property
if (persistentProperty instanceof HibernatePersistentProperty && ((HibernatePersistentProperty) persistentProperty).isLazy()) {
property.lazy = true
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GormMappingContributor.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GormMappingContributor.groovy
new file mode 100644
index 0000000000..9c882540aa
--- /dev/null
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GormMappingContributor.groovy
@@ -0,0 +1,114 @@
+/*
+ * 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 org.grails.orm.hibernate.cfg.domainbinding.jpa
+
+import groovy.transform.CompileStatic
+import org.hibernate.boot.ResourceStreamLocator
+import org.hibernate.boot.spi.AdditionalMappingContributions
+import org.hibernate.boot.spi.AdditionalMappingContributor
+import org.hibernate.boot.spi.InFlightMetadataCollector
+import org.hibernate.boot.spi.MetadataBuildingContext
+import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment
+
+import org.grails.orm.hibernate.cfg.MappingCacheHolder
+import org.grails.orm.hibernate.cfg.PersistentEntityNamingStrategy
+import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentEntity
+import org.grails.orm.hibernate.cfg.domainbinding.util.NamingStrategyProvider
+import org.grails.orm.hibernate.cfg.domainbinding.util.NamingStrategyWrapper
+
+/**
+ * The {@link AdditionalMappingContributor} through which GORM hands its domain classes to Hibernate: when Hibernate asks for
+ * the additional mappings, it resolves the naming strategy of the session factory against the JDBC environment and lets
+ * {@link GeneratedDomainClassBinder} generate the classes of the entities and bind them. It also caches the mapping of every
+ * entity it is given when it is created, which is what the rest of the datastore reads.
+ *
+ * @since 9.0
+ */
+@CompileStatic
+class GormMappingContributor implements AdditionalMappingContributor {
+
+ static final String CONTRIBUTOR_NAME = 'GORM'
+
+ private final String sessionFactoryName
+ private final List<HibernatePersistentEntity> persistentEntities
+ private final NamingStrategyProvider namingStrategyProvider
+ private final GeneratedDomainClassBinder binder
+ private PersistentEntityNamingStrategy namingStrategy
+ private MetadataBuildingContext metadataBuildingContext
+
+ /**
+ * @param sessionFactoryName the name the physical naming strategy of the session factory is registered under
+ * @param persistentEntities the entities to bind; each must already carry the name of the data source
+ * @param mappingCacheHolder the holder the mapping of every entity is cached in
+ * @param binder the binder that generates the classes of the entities and binds them
+ */
+ GormMappingContributor(
+ String sessionFactoryName,
+ List<HibernatePersistentEntity> persistentEntities,
+ NamingStrategyProvider namingStrategyProvider,
+ MappingCacheHolder mappingCacheHolder,
+ GeneratedDomainClassBinder binder) {
+ this.sessionFactoryName = sessionFactoryName
+ this.persistentEntities = persistentEntities
+ this.namingStrategyProvider = namingStrategyProvider
+ this.binder = binder
+ for (HibernatePersistentEntity persistentEntity : persistentEntities) {
+ mappingCacheHolder.cacheMapping(persistentEntity)
+ }
+ }
+
+ @Override
+ String getContributorName() {
+ return CONTRIBUTOR_NAME
+ }
+
+ @Override
+ void contribute(
+ AdditionalMappingContributions contributions,
+ InFlightMetadataCollector metadataCollector,
+ ResourceStreamLocator resourceStreamLocator,
+ MetadataBuildingContext buildingContext) {
+ this.metadataBuildingContext = buildingContext
+ binder.contribute(contributions, buildingContext, persistentEntities, getNamingStrategy(), getJdbcEnvironment())
+ }
+
+ /**
+ * The naming strategy of the session factory, wrapped for the JDBC environment of the last bootstrap; available once
+ * Hibernate has asked for the contributions.
+ */
+ PersistentEntityNamingStrategy getNamingStrategy() {
+ if (namingStrategy == null) {
+ namingStrategy = new NamingStrategyWrapper(
+ namingStrategyProvider.getPhysicalNamingStrategy(sessionFactoryName), getJdbcEnvironment())
+ }
+ return namingStrategy
+ }
+
+ /**
+ * The building context of the last bootstrap, {@code null} before Hibernate has asked for the contributions.
+ */
+ MetadataBuildingContext getMetadataBuildingContext() {
+ return metadataBuildingContext
+ }
+
+ JdbcEnvironment getJdbcEnvironment() {
+ return metadataBuildingContext.metadataCollector.database.jdbcEnvironment
+ }
+
+}
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 9f8be96a6d..f93748de56 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
@@ -135,11 +135,10 @@ import org.grails.orm.hibernate.cfg.Mapping
import org.grails.orm.hibernate.cfg.NaturalId
import org.grails.orm.hibernate.cfg.PersistentEntityNamingStrategy
import org.grails.orm.hibernate.cfg.PropertyConfig
-import org.grails.orm.hibernate.cfg.domainbinding.binder.ColumnConfigToColumnBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsDomainBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.IndexBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.NumericColumnConstraintsBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.StringColumnConstraintsBinder
+import org.grails.orm.hibernate.cfg.domainbinding.column.ColumnConfigToColumnBinder
+import org.grails.orm.hibernate.cfg.domainbinding.column.IndexBinder
+import org.grails.orm.hibernate.cfg.domainbinding.column.NumericColumnConstraintsBinder
+import org.grails.orm.hibernate.cfg.domainbinding.column.StringColumnConstraintsBinder
import org.grails.orm.hibernate.cfg.domainbinding.generator.GrailsIdentityGenerator
import org.grails.orm.hibernate.cfg.domainbinding.generator.GrailsIncrementGenerator
import org.grails.orm.hibernate.cfg.domainbinding.generator.GrailsNativeGenerator
@@ -546,7 +545,7 @@ class GrailsDomainGenerator {
}
/**
- * Describes the composite identifier of a root entity as {@code CompositeIdBinder} binds it: one identifier component with a
+ * Describes the composite identifier of a root entity as the classic composite identifier binder binds it: one identifier component with a
* property for every part, in the order the mapping names them. The columns of a part are the ones the part would have as an
* ordinary property, except that they are never null: the binder's component is the primary key, and Hibernate makes every
* column of a primary key not null.
@@ -617,7 +616,7 @@ class GrailsDomainGenerator {
'Native Domain Binding chapter of the manual'
} else if (!(part instanceof HibernateSimpleProperty || part instanceof HibernateTenantIdProperty) || isDerived(part)) {
// the tenant id of a multi-tenant entity is bound like any other column of the key, and the tenant filter
- // compares that column (CompositeIdBinder gives it no special treatment either)
+ // compares that column (the classic composite identifier binder gives it no special treatment either)
return "Composite identifier part [${part.name}] of [${entity.name}] is a ${part.getClass().simpleName}, which the " +
'generator does not support yet'
} else if (!supports(part)) {
@@ -751,7 +750,7 @@ class GrailsDomainGenerator {
}
/**
- * Decides the second-level cache of a root entity as {@code RootPersistentClassCommonValuesBinder} configures it: only a
+ * Decides the second-level cache of a root entity as the classic root binder configures it: only a
* cache that the mapping enables, only on the root (the cache of a subclass is not read, and Hibernate refuses
* {@code @Cache} on one), with the usage of the mapping, lazy properties included unless the mapping says {@code non-lazy},
* and the class immutable for the {@code read-only} usage.
@@ -768,7 +767,7 @@ class GrailsDomainGenerator {
}
/**
- * Decides the natural identifier the domain binder binds for the entity, as {@code NaturalIdentifierBinder} reads it from the
+ * Decides the natural identifier the domain binder binds for the entity, as the classic natural identifier binder reads it from the
* 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
@@ -841,8 +840,8 @@ class GrailsDomainGenerator {
/**
* Decides the indexes and multi-column unique keys the domain binder puts on the table the entity owns. The binder's own
* {@code IndexBinder} and {@code CreateKeyForProps} run, on a scratch table with the entity's table name, for every column
- * the binder passes through {@code ColumnBinder} (a simple property, the identifier, the version, a to-one foreign key, each
- * leaf of an embedded type) or {@code EnumTypeBinder} (an enum, which only gets an index from the binder and a unique group
+ * the binder passes through the classic column binder (a simple property, the identifier, the version, a to-one foreign key, each
+ * leaf of an embedded type) or the classic enum binder (an enum, which only gets an index from the binder and a unique group
* from the generator), in the order the binder binds them, so the names ({@code <table>_<column>_idx}, {@code UK} and a hash) and the column order are the binder's. The
* single-table subclasses of a hierarchy share the table of the root, so their columns are part of the root's constraints.
*
@@ -860,7 +859,7 @@ class GrailsDomainGenerator {
collectConstraintSites(contributor, identity, version, properties)
applyConstraintSites(table, identity + version, unbound)
if (contributor.isRoot()) {
- // RootPersistentClassCommonValuesBinder creates the primary key after the identifier and the version, and
+ // the classic root binder creates the primary key after the identifier and the version, and
// Hibernate then drops a unique key that repeats exactly the columns of the primary key
PrimaryKey primaryKey = new PrimaryKey(table)
identity.each { ConstraintSite site -> primaryKey.addColumn(new Column(site.columnName)) }
@@ -885,7 +884,7 @@ class GrailsDomainGenerator {
Set<String> before = new HashSet<String>(table.uniqueKeys.keySet())
keyForProps.createKeyForProps(site.property, site.path, table, site.columnName)
if (site.enumeration) {
- // EnumTypeBinder never calls CreateKeyForProps: the key is the mapping's, not the binder's
+ // the classic enum binder never calls CreateKeyForProps: the key is the mapping's, not the binder's
unbound.addAll(table.uniqueKeys.keySet() - before)
}
}
@@ -907,7 +906,7 @@ class GrailsDomainGenerator {
if (contributor.identity instanceof HibernateSimpleIdentityProperty) {
collectConstraintSites((HibernatePersistentProperty) contributor.identity, '', identity)
} else if (compositeIdentifier(contributor)) {
- // CompositeIdBinder binds the parts of the identifier one after the other, like any property
+ // the classic composite identifier binder binds the parts of the identifier one after the other, like any property
for (HibernatePersistentProperty part : contributor.compositeIdentity) {
collectConstraintSites(part, '', identity)
}
@@ -941,7 +940,7 @@ class GrailsDomainGenerator {
}
}
- /** One column the binder passes through {@code ColumnBinder} or {@code EnumTypeBinder}: where its index and unique group come from. */
+ /** One column the binder passes through the classic column binder or the classic enum binder: where its index and unique group come from. */
private static final class ConstraintSite {
final HibernatePersistentProperty property
@@ -963,7 +962,7 @@ class GrailsDomainGenerator {
/**
* Decides where the entity sits in its inheritance hierarchy the way the domain binder does: the strategy is the
* one the entity's own accessors report ({@code isUnionSubclass}, {@code isJoinedSubclass}, else single table),
- * the discriminator is the one {@code DiscriminatorPropertyBinder} binds on the root of a single-table
+ * the discriminator is the one the classic discriminator binder binds on the root of a single-table
* hierarchy that has subclasses, a subclass's discriminator value is the entity's own
* {@code getDiscriminatorValue}, and a joined subclass's key column is named like its identifier column.
*
@@ -1008,7 +1007,7 @@ class GrailsDomainGenerator {
}
/**
- * Mirrors {@code ConfiguredDiscriminatorBinder} and {@code DefaultDiscriminatorBinder}: a formula, else a column
+ * Mirrors the classic configured discriminator binder and the classic default discriminator binder: a formula, else a column
* that is named {@code class} unless configured and takes its length and SQL type from the column config.
*/
private DiscriminatorFacets discriminatorFacets(GrailsHibernatePersistentEntity entity) {
@@ -1024,7 +1023,7 @@ class GrailsDomainGenerator {
Column column = new Column()
columnConfigBinder.bindColumnConfigToColumn(column, columnConfig, null)
return new DiscriminatorFacets(
- columnConfig?.name != null ? columnConfig.name : GrailsDomainBinder.DEFAULT_DISCRIMINATOR_COLUMN_NAME,
+ columnConfig?.name != null ? columnConfig.name : GrailsHibernatePersistentEntity.DEFAULT_DISCRIMINATOR_COLUMN_NAME,
null, typeName, type, column.length?.intValue(), column.sqlType, insertable,
column.precision?.intValue(), column.scale?.intValue())
}
@@ -1151,8 +1150,8 @@ class GrailsDomainGenerator {
boolean explicit = name != null && (isEnum || type == null || name != type.name)
Map<String, String> parameters = [:]
if (isEnum) {
- // EnumTypeBinder replaces the configured type parameters with the enum class
- parameters[GrailsDomainBinder.ENUM_CLASS_PROP] = type.name
+ // the classic enum binder replaces the configured type parameters with the enum class
+ parameters[IdentityEnumType.PARAM_ENUM_CLASS] = type.name
} else if (!element) {
// the binder gives a collection element its type name only, never the type parameters
Properties typeParams = property.hibernateMappedForm.typeParams
@@ -1250,7 +1249,7 @@ class GrailsDomainGenerator {
}
/**
- * Decides the multi-tenant filter the domain binder gives the entity, as {@code MultiTenantFilterBinder} does: only an
+ * Decides the multi-tenant filter the domain binder gives the entity, as the classic tenant filter binder does: only an
* entity whose multi-tenancy is active (it has a tenant id, which GORM only sets in discriminator mode) is filtered,
* and only a root, or a joined or table-per-class subclass that declares the tenant id itself; the single-table
* subclasses share the root's filter. The condition compares the filter parameter with the tenant id property's
@@ -1377,7 +1376,7 @@ class GrailsDomainGenerator {
/**
* @return why the generator cannot describe the collection whose owner or associated entity has a composite identifier, or
* {@code null} when it can: the key columns of a collection of the owner are one for each identifier property
- * ({@code DependentKeyValueBinder}), and a collection mapped by the foreign key of the other side copies the columns of
+ * (the classic dependent key binder), and a collection mapped by the foreign key of the other side copies the columns of
* that foreign key. A many-to-many, a map and a join table to an entity with a composite identifier are not described:
* the binder names the element columns from the column configs of the collection property, which the key reads too
* (the key of such a collection gets the element's columns).
@@ -1413,7 +1412,7 @@ class GrailsDomainGenerator {
}
/**
- * The binder binds the key column of a collection like any other column ({@code DependentKeyValueBinder} runs {@code ColumnBinder}
+ * The binder binds the key column of a collection like any other column (the classic dependent key binder runs the classic column binder
* on the collection property), so an {@code index:} on the property becomes an index of the collection table over the key column,
* named as the mapping says ({@code IndexBinder}), and for a collection of enums the element column is indexed too, before the key.
* A {@code unique} group on the property would name columns of the owner's table, which the collection table does not have: the
@@ -1455,7 +1454,7 @@ class GrailsDomainGenerator {
/**
* The binder binds a collection property as one column of the owner's table, typed with the mapping's {@code type}, when the type
* is a class that is not a collection type (a {@code UserType}, for example) or {@code serializable}
- * ({@code GrailsPropertyBinder}): it is no collection then, and has the index, the unique group and the column settings of any
+ * (the classic property dispatcher): it is no collection then, and has the index, the unique group and the column settings of any
* other column. Any other {@code type} stays a type of the collection, which no collection of values accepts (see
* {@link #mappedCollectionTypeProblem}).
*/
@@ -1567,9 +1566,9 @@ class GrailsDomainGenerator {
}
/**
- * Mirrors {@code CollectionKeyBinder}: a single join table key is a plain column named by the key; otherwise the key
+ * Mirrors the classic collection key binder: a single join table key is a plain column named by the key; otherwise the key
* is bound like the property's own column (name from the column config or the naming strategy, the column config's
- * facets, uniqueness). It is nullable, as {@code CollectionKeyColumnUpdater} makes it, and always updatable.
+ * facets, uniqueness). It is nullable, as the classic key column updater makes it, and always updatable.
*
* <p>That updater also makes the key NOT updatable when the owner has more than one unidirectional to-many property,
* which is a defect rather than a rule to copy: Hibernate's collection persister disables inserting and deleting the
@@ -1588,13 +1587,13 @@ class GrailsDomainGenerator {
/**
* The key columns of a collection: one, or one for each identifier property when the owner has a composite identifier
- * ({@code DependentKeyValueBinder} binds them like the foreign key to a composite identifier, from the column configs of the
+ * (the classic dependent key binder binds them like the foreign key to a composite identifier, from the column configs of the
* collection property; a collection mapped by the foreign key of the other side copies the columns of that foreign key).
*/
private List<ColumnFacets> collectionKeyColumns(HibernateToManyProperty property) {
GrailsHibernatePersistentEntity owner = property.hibernateOwner
if (property instanceof HibernateToManyEntityProperty && property.shouldBindWithForeignKey()) {
- // CollectionKeyBinder copies the foreign key columns of the other side into the key; the key updater makes them nullable
+ // the classic collection key binder copies the foreign key columns of the other side into the key; the key updater makes them nullable
return toOneColumnsFacets((HibernateToOneProperty) property.hibernateInverseSide).collect { ColumnFacets column ->
new ColumnFacets(column.name(), true, false, true, true, null, null, null, null, null, null, null, null)
}
@@ -1637,8 +1636,8 @@ class GrailsDomainGenerator {
}
/**
- * Mirrors {@code BasicCollectionElementBinder} for a set, a bag and a list (the element is named after the property
- * and the element class, nullable, with the join table column config's facets), and {@code MapSecondPassBinder} for a
+ * Mirrors the classic basic element binder for a set, a bag and a list (the element is named after the property
+ * and the element class, nullable, with the join table column config's facets), and the classic map second pass for a
* map (a not-null column named {@code <property>_elt} unless the join table names it).
*/
private ColumnFacets collectionElementFacets(HibernateBasicProperty property, CollectionKind kind) {
@@ -1710,8 +1709,8 @@ class GrailsDomainGenerator {
}
/**
- * Mirrors {@code ListSecondPassBinder} (a nullable index column named by {@code getIndexColumnName}) and
- * {@code MapSecondPassBinder} (the same name, plus the index column config's facets); {@code null} for a set or a bag.
+ * Mirrors the classic list second pass (a nullable index column named by {@code getIndexColumnName}) and
+ * the classic map second pass (the same name, plus the index column config's facets); {@code null} for a set or a bag.
*/
private ColumnFacets collectionIndexFacets(HibernateToManyProperty property, CollectionKind kind) {
if (!kind.indexed) {
@@ -1729,7 +1728,7 @@ class GrailsDomainGenerator {
}
/**
- * {@code ManyToOneBinder.prepareCircularManyToMany} gives a circular many-to-many that names no join key the key
+ * the classic many-to-one binder's circular rule gives a circular many-to-many that names no join key the key
* {@code <property>_id}, by changing the mapping while it binds. The generator runs without that mutation, so it applies
* the rule itself, to the name of the element column (the binder binds it after the rename of the other side) and, for the
* key column, only where the binder renamed the key before it bound it, see {@link #boundBeforeInverseSide}.
@@ -1763,7 +1762,7 @@ class GrailsDomainGenerator {
/**
* Whether the binder binds the collection of this many-to-many side as the one that writes the join table: the owning side
- * ({@code belongsTo}), and a map, which {@code MapSecondPassBinder} always makes not inverse (a map side stores its rows with
+ * ({@code belongsTo}), and a map, which the classic map second pass always makes not inverse (a map side stores its rows with
* the key of the map whether or not the mapping says it owns the relationship).
*/
private static boolean ownsManyToMany(HibernateManyToManyProperty property) {
@@ -1826,7 +1825,7 @@ class GrailsDomainGenerator {
/**
* Decides how the binder binds a collection of entities. A bidirectional collection is mapped by the foreign key of the
- * other side ({@code CollectionKeyBinder} copies that column into the key) and is inverse, except an indexed list, which
+ * other side (the classic collection key binder copies that column into the key) and is inverse, except an indexed list, which
* the binder keeps owned (its index is a column of the target's table that only the collection writes). A
* unidirectional collection is a join table whose element is a many-to-one: the binder binds it as one whatever the
* name says, so it is a {@code @ManyToMany}. Using {@code @OneToMany} with a join table would add a unique constraint on the
@@ -1871,11 +1870,11 @@ class GrailsDomainGenerator {
key = circularKeyName((HibernateManyToManyProperty) property, key)
}
if (compositeIdentifier(property.hibernateOwner)) {
- // DependentKeyValueBinder: one key column for each identifier property of the owner
+ // the classic dependent key binder: one key column for each identifier property of the owner
keys = collectionKeyColumns(property)
key = keys[0]
}
- // ManyToOneBinder binds the element like the other side's own column: its name rules and its (never) nullable column
+ // the classic many-to-one binder binds the element like the other side's own column: its name rules and its (never) nullable column
// (named by the other side's column rules alone: the other side refers to this owner, whose identifier may be composite)
element = circularKeyName(other, toOneColumnFacets(other, '', firstColumnConfig(other.hibernateMappedForm)))
if (compositeIdentifier(target)) {
@@ -1904,7 +1903,7 @@ class GrailsDomainGenerator {
mappedBy = ownsManyToMany(property) ? null : other.name
} else if (property.shouldBindWithForeignKey()) {
HibernateToOneProperty inverse = (HibernateToOneProperty) property.hibernateInverseSide
- // CollectionKeyBinder copies the other side's foreign key column into the key; the key updater makes it nullable
+ // the classic collection key binder copies the other side's foreign key column into the key; the key updater makes it nullable
keys = collectionKeyColumns(property)
key = keys[0]
mappedBy = kind == CollectionKind.LIST ? null : inverse.name
@@ -1917,7 +1916,7 @@ class GrailsDomainGenerator {
keys = collectionKeyColumns(property)
key = keys[0]
if (property.bidirectional) {
- // BidirectionalMapElementBinder binds the element like the many-to-one of the other side (its column name rules)
+ // the classic bidirectional map element binder binds the element like the many-to-one of the other side (its column name rules)
ColumnFacets inverseColumn = toOneColumnFacets((HibernateToOneProperty) property.hibernateInverseSide)
element = new ColumnFacets(
inverseColumn.name(), inverseColumn.nullable(), inverseColumn.unique(), true, true, null, null, null,
@@ -2002,7 +2001,7 @@ class GrailsDomainGenerator {
/**
* The foreign key to an entity with a composite identifier has one column for each identifier property
- * ({@code CompositeIdentifierToManyToOneBinder}). The generator reproduces that when the identifier properties are simple
+ * (the classic composite foreign key binder). The generator reproduces that when the identifier properties are simple
* columns or foreign keys to entities with a simple identifier, and the mapping states either no columns or exactly one for
* each identifier property, all named.
*
@@ -2035,7 +2034,7 @@ class GrailsDomainGenerator {
if (deepPart != null) {
return "the composite identifier of the associated entity [${target.name}] has a part [${deepPart.name}] whose own composite " +
'identifier refers to a composite identifier: the binder names the columns of a foreign key to a composite identifier ' +
- 'only one level deep (CompositeIdentifierToManyToOneBinder.tryExpandNestedComposite), so it gives the foreign key ' +
+ 'only one level deep (as the classic binding of Grails 8 did), so it gives the foreign key ' +
'fewer columns than the key'
}
List<ColumnConfig> columns = property.hibernateMappedForm.columns
@@ -2050,7 +2049,7 @@ class GrailsDomainGenerator {
/**
* The column configs the binder binds the foreign key to an entity with a composite identifier with. A mapping that states
- * them names them; otherwise {@code CompositeIdentifierToManyToOneBinder} (which adds them to the mapping, as it binds)
+ * them names them; otherwise the classic composite foreign key binder (which adds them to the mapping, as it binds)
* names one for each identifier property after the table of the associated entity and the default column name of the
* identifier property.
*/
@@ -2108,7 +2107,7 @@ class GrailsDomainGenerator {
/**
* The binder binds a many-to-one as a {@code ManyToOne} value, and so it does a one-to-one that is not a valid Hibernate
- * one-to-one ({@code ForeignKeyOneToOneBinder}): the foreign key is a column of the owner's table and only the
+ * one-to-one (the classic foreign key one-to-one binder): the foreign key is a column of the owner's table and only the
* uniqueness differs.
*/
private static boolean boundAsManyToOne(HibernateToOneProperty property) {
@@ -2117,7 +2116,7 @@ class GrailsDomainGenerator {
}
/**
- * The binder binds a valid one-to-one ({@code OneToOneBinder}) as a Hibernate {@code OneToOne}. Its foreign key lives on
+ * The binder binds a valid one-to-one (the classic one-to-one binder) as a Hibernate {@code OneToOne}. Its foreign key lives on
* the other side (which is bound as a many-to-one above), so this side has no column and only names the property that
* holds the key.
*/
@@ -2130,7 +2129,7 @@ class GrailsDomainGenerator {
* entity, whether it is lazy, how it is fetched, whether the foreign key may be null, what happens when the row it
* points at is missing, the cascade and the join column.
*
- * <p>{@code ColumnBinder} makes the foreign key column nullable as {@code isAssociationColumnNullable} says (always, for
+ * <p>the classic column binder makes the foreign key column nullable as {@code isAssociationColumnNullable} says (always, for
* the associations handled here) and only then lets a subclass override it: a table-per-hierarchy subclass is always
* nullable, any other subclass follows the property's {@code nullable}. A root entity's association with
* {@code nullable: false} therefore keeps a nullable column, and only its {@code Property.optional} is false, which
@@ -2145,7 +2144,7 @@ class GrailsDomainGenerator {
PropertyConfig mapped = property.hibernateMappedForm
if (boundAsOneToOne(property)) {
HibernateOneToOneProperty oneToOne = (HibernateOneToOneProperty) property
- // OneToOneBinder never sets the value's lazy flag (it stays true) nor an ignore-not-found, and constrained is false
+ // the classic one-to-one binder never sets the value's lazy flag (it stays true) nor an ignore-not-found, and constrained is false
return new ToOneFacets(
property.hibernateAssociatedEntity.name,
true,
@@ -2209,7 +2208,7 @@ class GrailsDomainGenerator {
}
boolean unique = mapped.isUnique() && !mapped.isUniqueWithinGroup()
if (property instanceof HibernateOneToOneProperty && mapped.isUniqueWithinGroup()) {
- // ForeignKeyOneToOneBinder: a column in a unique group is unique on its own only when the other side is a valid one-to-one
+ // the classic foreign key one-to-one binder: a column in a unique group is unique on its own only when the other side is a valid one-to-one
HibernateOneToOneProperty inverse = ((HibernateOneToOneProperty) property).hibernateInverseSide
unique = property.isBidirectional() && inverse != null && inverse.isValidHibernateOneToOne()
}
@@ -2283,7 +2282,7 @@ class GrailsDomainGenerator {
}
/**
- * Decides the columns of an embedded property for the owner that declares it, the way {@code ComponentBinder}
+ * Decides the columns of an embedded property for the owner that declares it, the way the classic component binder
* binds them: one leaf for every property of the embedded type, nested embedded types included, each named from
* the property path and nullable when the binder makes it so. A derived (formula) leaf has no column facets.
*
@@ -2332,7 +2331,7 @@ class GrailsDomainGenerator {
/**
* The facets of one column of a component: the binder's own column rules with the component path in the name and
- * the parent property's nullability, then {@code ComponentUpdater}'s rule that makes the columns of every
+ * the parent property's nullability, then the classic component updater's rule that makes the columns of every
* enclosing component nullable when that component is.
*/
private ColumnFacets componentColumnFacets(
@@ -2345,8 +2344,8 @@ class GrailsDomainGenerator {
}
/**
- * {@code ComponentUpdater} makes every column of an enclosing component nullable when that component is. The binder also writes
- * the component as a whole only when its property is insertable and updatable ({@code PropertyBinder}), so a column is written
+ * the classic component updater makes every column of an enclosing component nullable when that component is. The binder also writes
+ * the component as a whole only when its property is insertable and updatable (the classic property binder), so a column is written
* only when every enclosing embedded property allows it as well.
*/
private static ColumnFacets nullableInComponent(ColumnFacets facets, List<HibernateEmbeddedProperty> enclosing) {
@@ -2361,7 +2360,7 @@ class GrailsDomainGenerator {
facets.write(), facets.comment())
}
- /** The properties {@code ComponentBinder} binds for an embedded property: the embedded type's, minus the owner's. */
+ /** The properties the classic component binder binds for an embedded property: the embedded type's, minus the owner's. */
private static List<HibernatePersistentProperty> embeddedPeers(HibernateEmbeddedProperty property) {
GrailsHibernatePersistentEntity type = (GrailsHibernatePersistentEntity) property.associatedEntity
return type.getHibernatePersistentProperties(property.owner.javaClass)
@@ -2448,7 +2447,7 @@ class GrailsDomainGenerator {
mappedForm.isUnique() && !mappedForm.isUniqueWithinGroup())
}
- /** Mirrors {@code EnumTypeBinder}: the column config's length, precision, scale, SQL type and uniqueness, plus the comment, default and read and write expressions it forgets. */
+ /** Mirrors the classic enum binder: the column config's length, precision, scale, SQL type and uniqueness, plus the comment, default and read and write expressions it forgets. */
private ColumnFacets enumColumnFacets(HibernateEnumProperty property, String path) {
PropertyConfig mappedForm = property.hibernateMappedForm
Column column = new Column()
@@ -2457,7 +2456,7 @@ class GrailsDomainGenerator {
columnConfigBinder.bindColumnConfigToColumn(column, columnConfig, mappedForm)
}
if (columnConfig != null) {
- // EnumTypeBinder ignores the comment, the default and the read and write expressions of the column config (a binder
+ // the classic enum binder ignores the comment, the default and the read and write expressions of the column config (a binder
// defect of Grails 8); the generator states what the mapping asks for
column.comment = columnConfig.comment
column.defaultValue = columnConfig.defaultValue
@@ -2541,7 +2540,7 @@ class GrailsDomainGenerator {
annotations << AnnotationDescription.Builder.ofType(DynamicUpdate).build()
}
if (entity.isRoot() && !facets.versioned()) {
- // VersionBinder sets the lock style NONE for a root without a version; Hibernate's default is VERSION
+ // the classic version binder sets the lock style NONE for a root without a version; Hibernate's default is VERSION
annotations << AnnotationDescription.Builder.ofType(OptimisticLocking).define('type', OptimisticLockType.NONE).build()
}
if (facets.batchSize() > 0) {
@@ -2657,7 +2656,7 @@ class GrailsDomainGenerator {
annotations << AnnotationDescription.Builder.ofType(HibernateNaturalId).define('mutable', naturalMutable).build()
}
if (!(property instanceof HibernateSimpleIdentityProperty) && property.isLazy()) {
- // PropertyBinder marks the property lazy when the mapping says lazy: true (the version never is)
+ // the classic property binder marks the property lazy when the mapping says lazy: true (the version never is)
annotations << AnnotationDescription.Builder.ofType(Basic).define('fetch', FetchType.LAZY).build()
}
TypeFacets type = typeFacets(property)
@@ -3419,7 +3418,7 @@ class GrailsDomainGenerator {
/**
* @return whether the binder binds the property as a Hibernate {@code Formula} with no column, which is what
- * {@code SimpleValueBinder} does for every derived property except an enum and the tenant id (which stays a
+ * the classic simple value binder does for every derived property except an enum and the tenant id (which stays a
* column)
*/
boolean isDerived(HibernatePersistentProperty property) {
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ManyToManyOwnerValidator.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ManyToManyOwnerValidator.groovy
similarity index 92%
rename from grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ManyToManyOwnerValidator.groovy
rename to grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ManyToManyOwnerValidator.groovy
index 68b15f148d..58a102187b 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ManyToManyOwnerValidator.groovy
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ManyToManyOwnerValidator.groovy
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.grails.orm.hibernate.cfg.domainbinding.binder
+package org.grails.orm.hibernate.cfg.domainbinding.jpa
import groovy.transform.CompileStatic
import org.hibernate.MappingException
@@ -56,8 +56,8 @@ class ManyToManyOwnerValidator {
if (!(otherSide instanceof HibernateManyToManyProperty) || otherSide.isOwningSide()) {
return
}
- // a Map-valued side is never inverse once its second pass has run: MapSecondPassBinder makes it write the
- // join table, so a relationship with a Map on either side is stored even without belongsTo
+ // a Map-valued side is never inverse: the generated classes make it write the join table (as the classic binding
+ // of Grails 8 did), so a relationship with a Map on either side is stored even without belongsTo
if (Map.isAssignableFrom(manyToMany.type) || Map.isAssignableFrom(otherSide.type)) {
return
}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/PropertyAccessorName.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/PropertyAccessorName.groovy
new file mode 100644
index 0000000000..6327fd0c8b
--- /dev/null
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/PropertyAccessorName.groovy
@@ -0,0 +1,57 @@
+/*
+ * 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 org.grails.orm.hibernate.cfg.domainbinding.jpa
+
+import groovy.transform.CompileStatic
+import org.codehaus.groovy.transform.trait.Traits
+import org.hibernate.boot.spi.AccessType
+
+import org.grails.datastore.mapping.reflect.EntityReflector
+import org.grails.orm.hibernate.access.TraitPropertyAccessStrategy
+import org.grails.orm.hibernate.cfg.PropertyConfig
+import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty
+
+/**
+ * Decides how Hibernate reads and writes a property of a real domain instance: the mapping's {@code accessType}
+ * ({@code property} unless the mapping says {@code field}), and the trait accessor for a trait-implemented getter read by
+ * field. {@link GeneratedDomainClassBinder} puts the name on the bound {@code Property} once the generated classes are bound,
+ * since the real class is what Hibernate instantiates.
+ *
+ * @since 9.0
+ */
+@CompileStatic
+class PropertyAccessorName {
+
+ /**
+ * @param persistentProperty the GORM property
+ * @return the Hibernate property accessor name
+ */
+ String accessorName(HibernatePersistentProperty persistentProperty) {
+ PropertyConfig config = persistentProperty.hibernateMappedForm
+ AccessType accessType = AccessType.getAccessStrategy(config != null ? config.accessType : new PropertyConfig().accessType)
+ return accessType == AccessType.FIELD ?
+ Optional.ofNullable(persistentProperty.reader)
+ .map { EntityReflector.PropertyReader reader -> reader.getter() }
+ .map { getter -> getter.getAnnotation(Traits.Implemented) }
+ .map { annotation -> TraitPropertyAccessStrategy.name }
+ .orElse(accessType.type) :
+ accessType.type
+ }
+
+}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/UniqueKeyFacets.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/UniqueKeyFacets.groovy
index 45ed98047e..0f0419f620 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/UniqueKeyFacets.groovy
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/UniqueKeyFacets.groovy
@@ -25,7 +25,7 @@ import groovy.transform.CompileStatic
* {@link GrailsDomainGenerator} writes it into {@code @Table(uniqueConstraints)}.
*
* <p>{@code bound} is {@code false} for a key the mapping asks for and the binder does not create: a unique group on an enum
- * property, which {@code EnumTypeBinder} never gives a key. The generator states it all the same, because the option is the
+ * property, which the classic enum binder never gives a key. The generator states it all the same, because the option is the
* mapping's and the binder's omission is a defect, not a rule to copy.</p>
*
* @since 9.0
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/BasicCollectionElementBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/BasicCollectionElementBinder.groovy
deleted file mode 100644
index 220daf8532..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/BasicCollectionElementBinder.groovy
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.secondpass
-
-import groovy.transform.CompileStatic
-import jakarta.annotation.Nonnull
-import org.hibernate.boot.spi.MetadataBuildingContext
-import org.hibernate.mapping.BasicValue
-import org.hibernate.mapping.Collection
-import org.hibernate.mapping.Column
-
-import org.grails.orm.hibernate.cfg.ColumnConfig
-import org.grails.orm.hibernate.cfg.PersistentEntityNamingStrategy
-import org.grails.orm.hibernate.cfg.PropertyConfig
-import org.grails.orm.hibernate.cfg.domainbinding.binder.ColumnConfigToColumnBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.EnumTypeBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.SimpleValueColumnBinder
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateBasicProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateEnumProperty
-import org.grails.orm.hibernate.cfg.domainbinding.util.SimpleValueColumnFetcher
-
-import static org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsDomainBinder.EMPTY_PATH
-
-/** Binds the element value for a basic (scalar or enum) collection. */
-@CompileStatic
-class BasicCollectionElementBinder {
-
- private final MetadataBuildingContext metadataBuildingContext
- private final PersistentEntityNamingStrategy namingStrategy
- private final EnumTypeBinder enumTypeBinder
- private final SimpleValueColumnBinder simpleValueColumnBinder
- private final SimpleValueColumnFetcher simpleValueColumnFetcher
- private final ColumnConfigToColumnBinder columnConfigToColumnBinder
-
- /** Creates a new {@link BasicCollectionElementBinder} instance. */
- BasicCollectionElementBinder(
- MetadataBuildingContext metadataBuildingContext,
- PersistentEntityNamingStrategy namingStrategy,
- EnumTypeBinder enumTypeBinder,
- SimpleValueColumnBinder simpleValueColumnBinder,
- SimpleValueColumnFetcher simpleValueColumnFetcher,
- ColumnConfigToColumnBinder columnConfigToColumnBinder) {
- this.metadataBuildingContext = metadataBuildingContext
- this.namingStrategy = namingStrategy
- this.enumTypeBinder = enumTypeBinder
- this.simpleValueColumnBinder = simpleValueColumnBinder
- this.simpleValueColumnFetcher = simpleValueColumnFetcher
- this.columnConfigToColumnBinder = columnConfigToColumnBinder
- }
-
- /** Creates and binds a {@link BasicValue} element for the given basic collection property. */
- BasicValue bind(@Nonnull HibernateBasicProperty property) {
- if (property instanceof HibernateEnumProperty) {
- return enumTypeBinder.bindEnumType((HibernateEnumProperty) property, EMPTY_PATH)
- }
- else {
- String columnName = property.joinTableColumName(namingStrategy)
- final Class<?> referencedType = property.componentType
- String typeName = property.getTypeName(referencedType)
- Collection collection = property.collection
- BasicValue element = simpleValueColumnBinder.bindSimpleValue(
- metadataBuildingContext, collection.collectionTable, typeName, columnName, true)
- Optional<ColumnConfig> columnConfigOptional = property.columnConfigOptional
- if (columnConfigOptional.isPresent()) {
- Column column = simpleValueColumnFetcher.getColumnForSimpleValue(element)
- final PropertyConfig mappedForm = property.hibernateMappedForm
- columnConfigToColumnBinder.bindColumnConfigToColumn(column, columnConfigOptional.get(), mappedForm)
- }
- return element
- }
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/BidirectionalMapElementBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/BidirectionalMapElementBinder.groovy
deleted file mode 100644
index 0d83614374..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/BidirectionalMapElementBinder.groovy
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.secondpass
-
-import groovy.transform.CompileStatic
-import org.hibernate.mapping.Collection
-import org.hibernate.mapping.ManyToOne
-
-import org.grails.orm.hibernate.cfg.domainbinding.binder.CollectionForPropertyConfigBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.ManyToOneBinder
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateManyToOneProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyProperty
-
-import static org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsDomainBinder.EMPTY_PATH
-
-/** Binds the element of a bidirectional one-to-many Map association. */
-@CompileStatic
-class BidirectionalMapElementBinder {
-
- private final ManyToOneBinder manyToOneBinder
- private final CollectionForPropertyConfigBinder collectionForPropertyConfigBinder
-
- /** Creates a new {@link BidirectionalMapElementBinder} instance. */
- BidirectionalMapElementBinder(
- ManyToOneBinder manyToOneBinder, CollectionForPropertyConfigBinder collectionForPropertyConfigBinder) {
- this.manyToOneBinder = manyToOneBinder
- this.collectionForPropertyConfigBinder = collectionForPropertyConfigBinder
- }
-
- /** Binds the ManyToOne element for a bidirectional Map collection. */
- void bind(HibernateToManyProperty property) {
- Collection collection = property.collection
- HibernateManyToOneProperty otherSide = (HibernateManyToOneProperty) property.hibernateInverseSide
- ManyToOne element = manyToOneBinder.bindManyToOne(otherSide, collection.collectionTable, EMPTY_PATH)
- element.referencedEntityName = otherSide.owner.name
- collection.element = element
- collectionForPropertyConfigBinder.bindCollectionForPropertyConfig(property)
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/BidirectionalOneToManyLinker.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/BidirectionalOneToManyLinker.groovy
deleted file mode 100644
index af16eaec4a..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/BidirectionalOneToManyLinker.groovy
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.secondpass
-
-import groovy.transform.CompileStatic
-import org.hibernate.mapping.Collection
-import org.hibernate.mapping.Column
-import org.hibernate.mapping.DependantValue
-import org.hibernate.mapping.PersistentClass
-
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty
-import org.grails.orm.hibernate.cfg.domainbinding.util.GrailsPropertyResolver
-
-/** Links bidirectional one-to-many associations by copying columns. */
-@CompileStatic
-class BidirectionalOneToManyLinker {
-
- private final GrailsPropertyResolver grailsPropertyResolver
-
- /** Creates a new {@link BidirectionalOneToManyLinker} instance. */
- BidirectionalOneToManyLinker(GrailsPropertyResolver grailsPropertyResolver) {
- this.grailsPropertyResolver = grailsPropertyResolver
- }
-
- /** Link. */
- void link(
- Collection collection,
- PersistentClass associatedClass,
- DependantValue key,
- HibernatePersistentProperty otherSide) {
- collection.inverse = true
-
- for (Column column : grailsPropertyResolver.getProperty(associatedClass, otherSide.name).value.columns) {
- Column mappingColumn = new Column()
- mappingColumn.name = column.name
- mappingColumn.length = column.length
- mappingColumn.nullable = otherSide.isNullable()
- mappingColumn.sqlType = column.sqlType
-
- mappingColumn.value = key
- key.addColumn(mappingColumn)
- key.table.addColumn(mappingColumn)
- }
- key.sortProperties()
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionKeyBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionKeyBinder.groovy
deleted file mode 100644
index a183397469..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionKeyBinder.groovy
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.secondpass
-
-import groovy.transform.CompileStatic
-import org.hibernate.mapping.Collection
-import org.hibernate.mapping.DependantValue
-import org.hibernate.mapping.PersistentClass
-
-import org.grails.datastore.mapping.model.types.EmbeddedCollection
-import org.grails.datastore.mapping.model.types.ToOne
-import org.grails.orm.hibernate.cfg.JoinTable
-import org.grails.orm.hibernate.cfg.PropertyConfig
-import org.grails.orm.hibernate.cfg.domainbinding.binder.SimpleValueColumnBinder
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateAssociation
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateManyToManyProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyProperty
-
-/** Binds the collection key value for a to-many association. */
-@CompileStatic
-class CollectionKeyBinder {
-
- private final BidirectionalOneToManyLinker bidirectionalOneToManyLinker
- private final DependentKeyValueBinder dependentKeyValueBinder
- private final SimpleValueColumnBinder simpleValueColumnBinder
- private final PrimaryKeyValueCreator primaryKeyValueCreator
-
- /** Creates a new {@link CollectionKeyBinder} instance. */
- CollectionKeyBinder(
- BidirectionalOneToManyLinker bidirectionalOneToManyLinker,
- DependentKeyValueBinder dependentKeyValueBinder,
- SimpleValueColumnBinder simpleValueColumnBinder,
- PrimaryKeyValueCreator primaryKeyValueCreator) {
- this.bidirectionalOneToManyLinker = bidirectionalOneToManyLinker
- this.dependentKeyValueBinder = dependentKeyValueBinder
- this.simpleValueColumnBinder = simpleValueColumnBinder
- this.primaryKeyValueCreator = primaryKeyValueCreator
- }
-
- /** Creates the {@link DependantValue} key, sets it on the collection, and binds it. */
- DependantValue bind(HibernateToManyProperty property) {
- Collection collection = property.collection
- DependantValue key = primaryKeyValueCreator.createPrimaryKeyValue(collection)
- collection.key = key
- if (property.isBidirectional()) {
- HibernateAssociation inverseSide = property.hibernateInverseSide
- if (inverseSide instanceof ToOne && property.shouldBindWithForeignKey()) {
- PersistentClass associatedClass = inverseSide.hibernateOwner.persistentClass
- bidirectionalOneToManyLinker.link(collection, associatedClass, key, inverseSide)
- }
- else if (inverseSide instanceof HibernateManyToManyProperty ||
- Map.isAssignableFrom(property.type)) {
- dependentKeyValueBinder.bind(property, key)
- }
- }
- else {
- PropertyConfig mappedForm = property.hibernateMappedForm
- if (mappedForm.hasJoinKeyMapping()) {
- JoinTable joinTable = mappedForm.joinTable
- def keys = joinTable.keys
- if (keys != null && keys.size() > 1) {
- // Composite key: delegate to DependentKeyValueBinder
- dependentKeyValueBinder.bind(property, key)
- }
- else {
- // Single key: use SimpleValueColumnBinder
- simpleValueColumnBinder.bindSimpleValue(
- key,
- 'long',
- (joinTable.keys != null && !joinTable.keys.isEmpty()) ? joinTable.keys.get(0).name : null,
- true)
- }
- }
- else if (property instanceof EmbeddedCollection) {
- // For embedded (value-type) collections the DependantValue already wraps the owner PK;
- // do not override the type name with the element class name.
- key.typeName = null
- }
- else {
- dependentKeyValueBinder.bind(property, key)
- }
- }
- return key
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionKeyColumnUpdater.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionKeyColumnUpdater.groovy
deleted file mode 100644
index 91e33c0f70..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionKeyColumnUpdater.groovy
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.secondpass
-
-import groovy.transform.CompileStatic
-import org.hibernate.mapping.Column
-import org.hibernate.mapping.DependantValue
-
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyCollectionProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyProperty
-
-/**
- * Forces columns to be nullable and decides whether the key is updatable.
- *
- * <p>The key of an entity collection is a foreign key in the target table, which several unidirectional collections
- * of one owner must not all update. The key of a collection of basic values or enums lives in a table of its own
- * and must stay updatable, because Hibernate writes no rows for a collection whose key is not.</p>
- */
-@CompileStatic
-class CollectionKeyColumnUpdater {
-
- private final CollectionKeyBinder collectionKeyBinder
-
- /** Creates a new {@link CollectionKeyColumnUpdater} instance. */
- CollectionKeyColumnUpdater(CollectionKeyBinder collectionKeyBinder) {
- this.collectionKeyBinder = collectionKeyBinder
- }
-
- /** Creates the key, sets it on the collection, and updates its columns. */
- void bind(HibernateToManyProperty property) {
- DependantValue key = collectionKeyBinder.bind(property)
- for (Column column : key.columns) {
- if (column != null) {
- column.nullable = true
- }
- }
- long unidirectionalCount = 0
- for (def p : property.hibernateOwner.persistentPropertiesToBind) {
- if (p instanceof HibernateToManyProperty && !((HibernateToManyProperty) p).isBidirectional()) {
- unidirectionalCount++
- }
- }
-
- key.updateable = property instanceof HibernateToManyCollectionProperty || unidirectionalCount <= 1
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionSecondPassBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionSecondPassBinder.groovy
deleted file mode 100644
index 1e85a38f3a..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionSecondPassBinder.groovy
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.secondpass
-
-import groovy.transform.CompileStatic
-import jakarta.annotation.Nonnull
-import org.hibernate.mapping.Collection
-import org.hibernate.mapping.Component
-
-import org.grails.orm.hibernate.cfg.domainbinding.binder.ComponentBinder
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateEmbeddedCollectionProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateManyToManyProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateOneToManyProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyCollectionProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyEntityProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyProperty
-
-/**
- * Refactored from CollectionBinder to handle collection second pass binding.
- */
-// CollectionSecondPassBinder receives its ComponentBinder reference via setComponentBinder()
-// post-construction, mirroring the GrailsPropertyBinder ↔ ComponentBinder circular dependency. A future
-// major release can introduce a shared binding context or factory that all binders receive at construction
-// time, eliminating the need for post-construction wiring.
-@CompileStatic
-@SuppressWarnings('PMD.DataflowAnomalyAnalysis')
-class CollectionSecondPassBinder {
-
- private final HibernateToManyEntityOrderByBinder hibernateToManyEntityOrderByBinder
- private final ToManyEntityMultiTenantFilterBinder hibernateToManyEntityMultiTenantFilterBinder
- private final CollectionKeyColumnUpdater collectionKeyColumnUpdater
- private final BidirectionalMapElementBinder bidirectionalMapElementBinder
- private final ManyToOneElementBinder manyToManyElementBinder
- private final UnidirectionalOneToManyBinder unidirectionalOneToManyBinder
- private final CollectionWithJoinTableBinder collectionWithJoinTableBinder
- private ComponentBinder componentBinder
-
- CollectionSecondPassBinder(
- CollectionKeyColumnUpdater collectionKeyColumnUpdater,
- UnidirectionalOneToManyBinder unidirectionalOneToManyBinder,
- CollectionWithJoinTableBinder collectionWithJoinTableBinder,
- BidirectionalMapElementBinder bidirectionalMapElementBinder,
- ManyToOneElementBinder manyToManyElementBinder,
- HibernateToManyEntityOrderByBinder hibernateToManyEntityOrderByBinder,
- ToManyEntityMultiTenantFilterBinder hibernateToManyEntityMultiTenantFilterBinder) {
- this.collectionKeyColumnUpdater = collectionKeyColumnUpdater
- this.unidirectionalOneToManyBinder = unidirectionalOneToManyBinder
- this.collectionWithJoinTableBinder = collectionWithJoinTableBinder
- this.bidirectionalMapElementBinder = bidirectionalMapElementBinder
- this.manyToManyElementBinder = manyToManyElementBinder
- this.hibernateToManyEntityOrderByBinder = hibernateToManyEntityOrderByBinder
- this.hibernateToManyEntityMultiTenantFilterBinder = hibernateToManyEntityMultiTenantFilterBinder
- }
-
- void setComponentBinder(ComponentBinder componentBinder) {
- this.componentBinder = componentBinder
- }
-
- void bindCollectionSecondPass(@Nonnull HibernateToManyProperty property) {
-
- if (property instanceof HibernateEmbeddedCollectionProperty && componentBinder != null) {
- HibernateEmbeddedCollectionProperty embeddedCollectionProperty = (HibernateEmbeddedCollectionProperty) property
- Component component = componentBinder.bindEmbeddedCollectionComponent(embeddedCollectionProperty)
- embeddedCollectionProperty.collection.element = component
- }
- else if (property instanceof HibernateToManyEntityProperty) {
- HibernateToManyEntityProperty entityProperty = (HibernateToManyEntityProperty) property
- hibernateToManyEntityOrderByBinder.bind(entityProperty)
- if (entityProperty.isManyToMany() && entityProperty.isBidirectional()) {
- manyToManyElementBinder.bind((HibernateManyToManyProperty) entityProperty)
- }
- else if (entityProperty.isBidirectionalToManyMap() && entityProperty.isBidirectional()) {
- bidirectionalMapElementBinder.bind(entityProperty)
- }
- else if (entityProperty.isOneToMany() && entityProperty.isUnidirectionalOneToMany()) {
- unidirectionalOneToManyBinder.bind((HibernateOneToManyProperty) entityProperty)
- }
- hibernateToManyEntityMultiTenantFilterBinder.bind(entityProperty)
- }
- else if (property instanceof HibernateToManyCollectionProperty && ((HibernateToManyCollectionProperty) property).supportsJoinColumnMapping()) {
- collectionWithJoinTableBinder.bindCollectionWithJoinTable((HibernateToManyCollectionProperty) property)
- }
-
- collectionKeyColumnUpdater.bind(property)
- Collection collection = property.collection
- collection.sorted = property.isSorted()
- collection.cacheConcurrencyStrategy = property.cacheUsage
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionWithJoinTableBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionWithJoinTableBinder.groovy
deleted file mode 100644
index cee517e4cd..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/CollectionWithJoinTableBinder.groovy
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.secondpass
-
-import groovy.transform.CompileStatic
-import jakarta.annotation.Nonnull
-import org.hibernate.mapping.Collection
-import org.hibernate.mapping.SimpleValue
-
-import org.grails.orm.hibernate.cfg.HibernateCompositeIdentity
-import org.grails.orm.hibernate.cfg.PersistentEntityNamingStrategy
-import org.grails.orm.hibernate.cfg.domainbinding.binder.CollectionForPropertyConfigBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.CompositeIdentifierToManyToOneBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.SimpleValueColumnBinder
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateBasicProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyProperty
-
-import static org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsDomainBinder.EMPTY_PATH
-
-/** Binds a collection with a join table. */
-@CompileStatic
-@SuppressWarnings('PMD.DataflowAnomalyAnalysis')
-class CollectionWithJoinTableBinder {
-
- private final PersistentEntityNamingStrategy namingStrategy
- private final UnidirectionalOneToManyInverseValuesBinder unidirectionalOneToManyInverseValuesBinder
- private final CompositeIdentifierToManyToOneBinder compositeIdentifierToManyToOneBinder
- private final CollectionForPropertyConfigBinder collectionForPropertyConfigBinder
- private final SimpleValueColumnBinder simpleValueColumnBinder
- private final BasicCollectionElementBinder basicCollectionElementBinder
-
- /** Creates a new {@link CollectionWithJoinTableBinder} instance. */
- CollectionWithJoinTableBinder(
- PersistentEntityNamingStrategy namingStrategy,
- UnidirectionalOneToManyInverseValuesBinder unidirectionalOneToManyInverseValuesBinder,
- CompositeIdentifierToManyToOneBinder compositeIdentifierToManyToOneBinder,
- CollectionForPropertyConfigBinder collectionForPropertyConfigBinder,
- SimpleValueColumnBinder simpleValueColumnBinder,
- BasicCollectionElementBinder basicCollectionElementBinder) {
- this.namingStrategy = namingStrategy
- this.unidirectionalOneToManyInverseValuesBinder = unidirectionalOneToManyInverseValuesBinder
- this.compositeIdentifierToManyToOneBinder = compositeIdentifierToManyToOneBinder
- this.collectionForPropertyConfigBinder = collectionForPropertyConfigBinder
- this.simpleValueColumnBinder = simpleValueColumnBinder
- this.basicCollectionElementBinder = basicCollectionElementBinder
- }
-
- /** Bind collection with join table. */
- void bindCollectionWithJoinTable(@Nonnull HibernateToManyProperty property) {
- Collection collection = property.collection
- collection.inverse = false
- SimpleValue element
- if (property instanceof HibernateBasicProperty) {
- element = basicCollectionElementBinder.bind((HibernateBasicProperty) property)
- }
- else {
- element = unidirectionalOneToManyInverseValuesBinder.bind(property)
- final GrailsHibernatePersistentEntity domainClass = property.hibernateAssociatedEntity
- if (domainClass != null) {
- Optional<HibernateCompositeIdentity> compositeIdentity = domainClass.hibernateCompositeIdentity
- if (compositeIdentity.isPresent()) {
- HibernateCompositeIdentity ci = compositeIdentity.get()
- compositeIdentifierToManyToOneBinder.bindCompositeIdentifierToManyToOne(
- property, element, ci, domainClass, EMPTY_PATH)
- }
- else {
- simpleValueColumnBinder.bindSimpleValue(
- element, 'long', property.resolveJoinTableForeignKeyColumnName(namingStrategy), true)
- }
- }
- }
-
- collection.element = element
- collectionForPropertyConfigBinder.bindCollectionForPropertyConfig(property)
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/DependentKeyValueBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/DependentKeyValueBinder.groovy
deleted file mode 100644
index 292c3c5300..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/DependentKeyValueBinder.groovy
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.secondpass
-
-import groovy.transform.CompileStatic
-import org.hibernate.mapping.DependantValue
-
-import org.grails.orm.hibernate.cfg.HibernateCompositeIdentity
-import org.grails.orm.hibernate.cfg.domainbinding.binder.CompositeIdentifierToManyToOneBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.SimpleValueBinder
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyProperty
-
-import static org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsDomainBinder.EMPTY_PATH
-
-/** Binds a dependent key value for collection associations. */
-@CompileStatic
-class DependentKeyValueBinder {
-
- private final SimpleValueBinder simpleValueBinder
- private final CompositeIdentifierToManyToOneBinder compositeIdentifierToManyToOneBinder
-
- DependentKeyValueBinder(
- SimpleValueBinder simpleValueBinder,
- CompositeIdentifierToManyToOneBinder compositeIdentifierToManyToOneBinder) {
- this.simpleValueBinder = simpleValueBinder
- this.compositeIdentifierToManyToOneBinder = compositeIdentifierToManyToOneBinder
- }
-
- void bind(HibernateToManyProperty property, DependantValue key) {
- GrailsHibernatePersistentEntity refDomainClass = property.hibernateOwner
-
- Optional<HibernateCompositeIdentity> compositeIdentity = property.supportsJoinColumnMapping() ?
- refDomainClass.hibernateCompositeIdentity :
- Optional.empty()
-
- compositeIdentity.ifPresentOrElse(
- { HibernateCompositeIdentity ci ->
- compositeIdentifierToManyToOneBinder.bindCompositeIdentifierToManyToOne(
- property, key, ci, refDomainClass, EMPTY_PATH)
- },
- { -> simpleValueBinder.bindSimpleValue(property, null, key, EMPTY_PATH) })
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/HibernateToManyEntityOrderByBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/HibernateToManyEntityOrderByBinder.groovy
deleted file mode 100644
index 93e181ca63..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/HibernateToManyEntityOrderByBinder.groovy
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.secondpass
-
-import groovy.transform.CompileStatic
-import org.hibernate.mapping.Collection
-import org.hibernate.mapping.OneToMany
-import org.hibernate.mapping.PersistentClass
-
-import org.grails.orm.hibernate.cfg.domainbinding.binder.CollectionForPropertyConfigBinder
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyEntityProperty
-import org.grails.orm.hibernate.cfg.domainbinding.util.OrderByClauseBuilder
-
-/**
- * Binds the order-by clause to a collection, and the discriminator where condition to a one-to-many
- * collection of a table-per-hierarchy subclass.
- */
-@CompileStatic
-class HibernateToManyEntityOrderByBinder {
-
- private final OrderByClauseBuilder orderByClauseBuilder
- private final CollectionForPropertyConfigBinder collectionForPropertyConfigBinder
-
- /** Creates a new {@link HibernateToManyEntityOrderByBinder} instance. */
- HibernateToManyEntityOrderByBinder() {
- this.orderByClauseBuilder = new OrderByClauseBuilder()
- this.collectionForPropertyConfigBinder = new CollectionForPropertyConfigBinder()
- }
-
- /**
- * Binds the order-by clause and, for a one-to-many collection of a table-per-hierarchy subclass,
- * the discriminator where condition to the given collection.
- */
- void bind(HibernateToManyEntityProperty property) {
- Collection collection = property.collection
- PersistentClass associatedClass = property.associatedClass
- GrailsHibernatePersistentEntity referenced = property.hibernateAssociatedEntity
-
- if (property.hasSort()) {
- HibernatePersistentProperty sortBy = referenced.getHibernatePropertyByName(property.sort)
- String order = property.order != null ? property.order : 'asc'
- collection.orderBy = orderByClauseBuilder.buildOrderByClause(
- sortBy.name, associatedClass, collection.role, order)
- }
-
- if (!collection.isOneToMany()) {
- return
- }
- // the where condition applies to the collection table, which only holds the discriminator
- // column when the collection is mapped by a foreign key in the element's table
- if (referenced.isTablePerHierarchySubclass()) {
- String discriminatorColumnName = referenced.discriminatorColumnName
- Set<String> discSet = referenced.buildDiscriminatorSet()
- String clause = discSet.join(',')
- collection.where = discriminatorColumnName + ' in (' + clause + ')'
- }
- OneToMany oneToMany = (OneToMany) collection.element
- oneToMany.associatedClass = associatedClass
- if (property.shouldBindWithForeignKey()) {
- collection.collectionTable = associatedClass.table
- }
- collectionForPropertyConfigBinder.bindCollectionForPropertyConfig(property)
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/ListSecondPass.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/ListSecondPass.groovy
deleted file mode 100644
index 2f3384d6b5..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/ListSecondPass.groovy
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.secondpass
-
-import groovy.transform.CompileStatic
-import org.hibernate.MappingException
-import org.hibernate.boot.spi.SecondPass
-
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyProperty
-
-@CompileStatic
-@SuppressWarnings('PMD.NonSerializableClass')
-class ListSecondPass implements SecondPass, GrailsSecondPass, Serializable {
-
- private static final long serialVersionUID = -3024674993774205193L
-
- protected final HibernateToManyProperty property
- private final ListSecondPassBinder listSecondPassBinder
-
- ListSecondPass(ListSecondPassBinder listSecondPassBinder, HibernateToManyProperty property) {
- this.listSecondPassBinder = listSecondPassBinder
- this.property = property
- }
-
- @Override
- void doSecondPass(Map persistentClasses) throws MappingException {
- listSecondPassBinder.bindListSecondPass(property)
- createCollectionKeys(property.collection)
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/ListSecondPassBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/ListSecondPassBinder.groovy
deleted file mode 100644
index 62d3237bfa..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/ListSecondPassBinder.groovy
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.secondpass
-
-import groovy.transform.CompileStatic
-import jakarta.annotation.Nonnull
-import org.hibernate.boot.spi.InFlightMetadataCollector
-import org.hibernate.boot.spi.MetadataBuildingContext
-import org.hibernate.mapping.Backref
-import org.hibernate.mapping.BasicValue
-import org.hibernate.mapping.DependantValue
-import org.hibernate.mapping.IndexBackref
-import org.hibernate.mapping.PersistentClass
-import org.hibernate.mapping.Table
-
-import org.grails.datastore.mapping.model.PersistentEntity
-import org.grails.orm.hibernate.cfg.PersistentEntityNamingStrategy
-import org.grails.orm.hibernate.cfg.domainbinding.binder.SimpleValueColumnBinder
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateAssociation
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyProperty
-import org.grails.orm.hibernate.cfg.domainbinding.util.BackticksRemover
-
-import static org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsDomainBinder.UNDERSCORE
-
-/** Refactored from CollectionBinder to handle list second pass binding. */
-@CompileStatic
-@SuppressWarnings('PMD.DataflowAnomalyAnalysis')
-class ListSecondPassBinder {
-
- private static final String DEFAULT_INDEX_TYPE = 'integer'
-
- private final MetadataBuildingContext metadataBuildingContext
- private final CollectionSecondPassBinder collectionSecondPassBinder
- private final PersistentEntityNamingStrategy namingStrategy
- private final SimpleValueColumnBinder simpleValueColumnBinder
- private final InFlightMetadataCollector mappings
- private final BackticksRemover backticksRemover = new BackticksRemover()
-
- ListSecondPassBinder(
- MetadataBuildingContext metadataBuildingContext,
- PersistentEntityNamingStrategy namingStrategy,
- CollectionSecondPassBinder collectionSecondPassBinder,
- SimpleValueColumnBinder simpleValueColumnBinder,
- InFlightMetadataCollector mappings) {
- this.metadataBuildingContext = metadataBuildingContext
- this.collectionSecondPassBinder = collectionSecondPassBinder
- this.namingStrategy = namingStrategy
- this.simpleValueColumnBinder = simpleValueColumnBinder
- this.mappings = mappings
- }
-
- void bindListSecondPass(@Nonnull HibernateToManyProperty property) {
- property.validateOwningSide()
- collectionSecondPassBinder.bindCollectionSecondPass(property)
- org.hibernate.mapping.List list = (org.hibernate.mapping.List) property.collection
- bindIndexColumn(property)
- list.baseIndex = 0
- list.inverse = false
- list.element.createForeignKey()
- bindBackReferences(property, list)
- }
-
- private void bindIndexColumn(HibernateToManyProperty property) {
- org.hibernate.mapping.List list = (org.hibernate.mapping.List) property.collection
- Table collectionTable = list.collectionTable
- String columnName = property.getIndexColumnName(namingStrategy)
- String type = property.getIndexColumnType(DEFAULT_INDEX_TYPE)
-
- BasicValue indexValue = simpleValueColumnBinder.bindSimpleValue(
- metadataBuildingContext, collectionTable, type, columnName, true)
- list.index = indexValue
- }
-
- private void bindBackReferences(HibernateToManyProperty property, org.hibernate.mapping.List list) {
- if (!property.isBidirectional()) {
- return
- }
-
- HibernateAssociation inverseSide = property.hibernateInverseSide
- String entityName = inverseSide.hibernateOwner.name
- PersistentClass referenced = mappings.getEntityBinding(entityName)
-
- if (referenced != null) {
- boolean compositeIdProperty = inverseSide.isCompositeIdProperty()
-
- if (!compositeIdProperty) {
- addBackref(property, list, referenced)
- }
-
- if (shouldAddIndexBackref(list, compositeIdProperty)) {
- addIndexBackref(property, list, referenced)
- }
- }
- }
-
- private void addBackref(HibernateToManyProperty property, org.hibernate.mapping.List list, PersistentClass referenced) {
- Backref prop = new Backref()
- final PersistentEntity owner = property.owner
- prop.entityName = owner.name
-
- String name = UNDERSCORE.toString() +
- backticksRemover.apply(owner.javaClass.simpleName) +
- UNDERSCORE +
- backticksRemover.apply(property.name) +
- 'Backref'
-
- prop.name = name
- prop.selectable = false
- prop.updatable = false
- prop.insertable = false
- prop.collectionRole = list.role
- prop.value = list.key
-
- DependantValue value = (DependantValue) prop.value
- if (!property.isCircular()) {
- value.nullable = false
- }
- value.updateable = true
- prop.optional = false
-
- referenced.addProperty(prop)
- }
-
- private boolean shouldAddIndexBackref(org.hibernate.mapping.List list, boolean compositeIdProperty) {
- return (!list.key.isNullable() && !list.isInverse()) || compositeIdProperty
- }
-
- private void addIndexBackref(HibernateToManyProperty property, org.hibernate.mapping.List list, PersistentClass referenced) {
- IndexBackref ib = new IndexBackref()
- ib.name = UNDERSCORE.toString() + property.name + 'IndexBackref'
- ib.updatable = false
- ib.selectable = false
- ib.insertable = false
- ib.collectionRole = list.role
- ib.entityName = list.owner.entityName
- ib.value = list.index
- referenced.addProperty(ib)
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/ManyToOneElementBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/ManyToOneElementBinder.groovy
deleted file mode 100644
index b8ad188670..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/ManyToOneElementBinder.groovy
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.secondpass
-
-import groovy.transform.CompileStatic
-import org.hibernate.mapping.Collection
-import org.hibernate.mapping.ManyToOne
-
-import org.grails.orm.hibernate.cfg.domainbinding.binder.CollectionForPropertyConfigBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.ManyToOneBinder
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateManyToManyProperty
-
-import static org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsDomainBinder.EMPTY_PATH
-
-/** Binds the element of a bidirectional many-to-many association. */
-@CompileStatic
-class ManyToOneElementBinder {
-
- private final ManyToOneBinder manyToOneBinder
- private final CollectionForPropertyConfigBinder collectionForPropertyConfigBinder
-
- /** Creates a new {@link ManyToOneElementBinder} instance. */
- ManyToOneElementBinder(
- ManyToOneBinder manyToOneBinder, CollectionForPropertyConfigBinder collectionForPropertyConfigBinder) {
- this.manyToOneBinder = manyToOneBinder
- this.collectionForPropertyConfigBinder = collectionForPropertyConfigBinder
- }
-
- /** Binds the ManyToOne element for a bidirectional many-to-many collection. */
- void bind(HibernateManyToManyProperty property) {
- ManyToOne element = manyToOneBinder.bindManyToOne(property, EMPTY_PATH)
- Collection collection = property.collection
- collection.element = element
- collectionForPropertyConfigBinder.bindCollectionForPropertyConfig(property)
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/MapSecondPass.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/MapSecondPass.groovy
deleted file mode 100644
index 02ab989dc1..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/MapSecondPass.groovy
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.secondpass
-
-import groovy.transform.CompileStatic
-import org.hibernate.MappingException
-import org.hibernate.boot.spi.SecondPass
-
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyProperty
-
-@CompileStatic
-@SuppressWarnings('PMD.NonSerializableClass')
-class MapSecondPass implements SecondPass, GrailsSecondPass, Serializable {
-
- private static final long serialVersionUID = -3244991685626409031L
-
- protected final HibernateToManyProperty property
- private final MapSecondPassBinder mapSecondPassBinder
-
- MapSecondPass(MapSecondPassBinder mapSecondPassBinder, HibernateToManyProperty property) {
- this.mapSecondPassBinder = mapSecondPassBinder
- this.property = property
- }
-
- @Override
- void doSecondPass(Map persistentClasses) throws MappingException {
- mapSecondPassBinder.bindMapSecondPass(property)
- createCollectionKeys(property.collection)
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/MapSecondPassBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/MapSecondPassBinder.groovy
deleted file mode 100644
index 2225affca1..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/MapSecondPassBinder.groovy
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.secondpass
-
-import groovy.transform.CompileStatic
-import jakarta.annotation.Nonnull
-import org.hibernate.MappingException
-import org.hibernate.boot.spi.MetadataBuildingContext
-import org.hibernate.mapping.BasicValue
-import org.hibernate.mapping.Column
-
-import org.grails.orm.hibernate.cfg.ColumnConfig
-import org.grails.orm.hibernate.cfg.PersistentEntityNamingStrategy
-import org.grails.orm.hibernate.cfg.PropertyConfig
-import org.grails.orm.hibernate.cfg.domainbinding.binder.ColumnConfigToColumnBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.SimpleValueColumnBinder
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyCollectionProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyProperty
-import org.grails.orm.hibernate.cfg.domainbinding.util.SimpleValueColumnFetcher
-
-/** Refactored from CollectionBinder to handle map second pass binding. */
-@CompileStatic
-@SuppressWarnings('PMD.DataflowAnomalyAnalysis')
-class MapSecondPassBinder {
-
- private final MetadataBuildingContext metadataBuildingContext
- private final PersistentEntityNamingStrategy namingStrategy
- private final CollectionSecondPassBinder collectionSecondPassBinder
- private final SimpleValueColumnBinder simpleValueColumnBinder
- private final ColumnConfigToColumnBinder columnConfigToColumnBinder
- private final SimpleValueColumnFetcher simpleValueColumnFetcher
-
- MapSecondPassBinder(
- MetadataBuildingContext metadataBuildingContext,
- PersistentEntityNamingStrategy namingStrategy,
- CollectionSecondPassBinder collectionSecondPassBinder,
- SimpleValueColumnBinder simpleValueColumnBinder,
- ColumnConfigToColumnBinder columnConfigToColumnBinder,
- SimpleValueColumnFetcher simpleValueColumnFetcher) {
- this.metadataBuildingContext = metadataBuildingContext
- this.namingStrategy = namingStrategy
- this.collectionSecondPassBinder = collectionSecondPassBinder
- this.simpleValueColumnBinder = simpleValueColumnBinder
- this.columnConfigToColumnBinder = columnConfigToColumnBinder
- this.simpleValueColumnFetcher = simpleValueColumnFetcher
- }
-
- void bindMapSecondPass(@Nonnull HibernateToManyProperty property) {
- org.hibernate.mapping.Map map = (org.hibernate.mapping.Map) property.collection
- collectionSecondPassBinder.bindCollectionSecondPass(property)
-
- String type = property.getIndexColumnType('string')
- String columnName1 = property.getIndexColumnName(namingStrategy)
- BasicValue value = simpleValueColumnBinder.bindSimpleValue(
- metadataBuildingContext, map.collectionTable, type, columnName1, true)
- PropertyConfig mappedForm = property.hibernateMappedForm
- if (mappedForm.indexColumn != null) {
- Column column = simpleValueColumnFetcher.getColumnForSimpleValue(value)
- ColumnConfig columnConfig = getSingleColumnConfig(mappedForm.indexColumn)
- columnConfigToColumnBinder.bindColumnConfigToColumn(column, columnConfig, mappedForm)
- }
-
- if (!value.isTypeSpecified()) {
- throw new MappingException('map index element must specify a type: ' + map.role)
- }
- map.index = value
-
- if (property instanceof HibernateToManyCollectionProperty) {
- HibernateToManyCollectionProperty collectionProperty = (HibernateToManyCollectionProperty) property
- String typeName = collectionProperty.elementTypeName
- String columnName = collectionProperty.getMapElementName(namingStrategy)
- BasicValue elt = simpleValueColumnBinder.bindSimpleValue(
- metadataBuildingContext, map.collectionTable, typeName, columnName, false)
- map.element = elt
- }
-
- map.inverse = false
- }
-
- ColumnConfig getSingleColumnConfig(PropertyConfig propertyConfig) {
- if (propertyConfig != null) {
- List<ColumnConfig> columns = propertyConfig.columns
- if (columns != null && !columns.isEmpty()) {
- return columns.get(0)
- }
- }
- return null
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/PrimaryKeyValueCreator.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/PrimaryKeyValueCreator.groovy
deleted file mode 100644
index a1017b2779..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/PrimaryKeyValueCreator.groovy
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.secondpass
-
-import groovy.transform.CompileStatic
-import org.hibernate.boot.spi.MetadataBuildingContext
-import org.hibernate.mapping.Collection
-import org.hibernate.mapping.DependantValue
-import org.hibernate.mapping.KeyValue
-
-/** Creates primary key value for collection. */
-@CompileStatic
-class PrimaryKeyValueCreator {
-
- private final MetadataBuildingContext metadataBuildingContext
-
- PrimaryKeyValueCreator(MetadataBuildingContext metadataBuildingContext) {
- this.metadataBuildingContext = metadataBuildingContext
- }
-
- DependantValue createPrimaryKeyValue(Collection collection) {
- KeyValue keyValue
- String propertyRef = collection.referencedPropertyName
- // this is to support mapping by a property
- if (propertyRef == null) {
- keyValue = collection.owner.identifier
- }
- else {
- keyValue = (KeyValue) collection.owner.getProperty(propertyRef).value
- }
-
- DependantValue key = new DependantValue(metadataBuildingContext, collection.collectionTable, keyValue)
- key.typeName = null
- key.nullable = true
- key.updateable = true
-
- key.sorted = collection.isSorted()
- return key
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/SetSecondPass.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/SetSecondPass.groovy
deleted file mode 100644
index a47f1fc40a..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/SetSecondPass.groovy
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.secondpass
-
-import groovy.transform.CompileStatic
-import org.hibernate.MappingException
-import org.hibernate.boot.spi.SecondPass
-
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyProperty
-
-/**
- * Second pass class for grails relationships. This is required as all persistent classes need to be
- * loaded in the first pass and then relationships established in the second pass compile
- *
- * @author Graeme
- */
-@CompileStatic
-@SuppressWarnings('PMD.NonSerializableClass')
-class SetSecondPass implements SecondPass, GrailsSecondPass, Serializable {
-
- private static final long serialVersionUID = -5540526942092611348L
-
- protected final HibernateToManyProperty property
- private final CollectionSecondPassBinder collectionSecondPassBinder
-
- SetSecondPass(CollectionSecondPassBinder collectionSecondPassBinder, HibernateToManyProperty property) {
- this.collectionSecondPassBinder = collectionSecondPassBinder
- this.property = property
- }
-
- @Override
- void doSecondPass(Map persistentClasses) throws MappingException {
- collectionSecondPassBinder.bindCollectionSecondPass(property)
- createCollectionKeys(property.collection)
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/ToManyEntityMultiTenantFilterBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/ToManyEntityMultiTenantFilterBinder.groovy
deleted file mode 100644
index 3835692d1d..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/ToManyEntityMultiTenantFilterBinder.groovy
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.secondpass
-
-import groovy.transform.CompileStatic
-import org.hibernate.mapping.Collection
-
-import org.grails.datastore.mapping.model.config.GormProperties
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyEntityProperty
-import org.grails.orm.hibernate.cfg.domainbinding.util.DefaultColumnNameFetcher
-
-/** Applies multi-tenant filters to a collection based on the associated entity's tenancy. */
-@CompileStatic
-class ToManyEntityMultiTenantFilterBinder {
-
- private final DefaultColumnNameFetcher defaultColumnNameFetcher
-
- /** Creates a new {@link ToManyEntityMultiTenantFilterBinder} instance. */
- ToManyEntityMultiTenantFilterBinder(DefaultColumnNameFetcher defaultColumnNameFetcher) {
- this.defaultColumnNameFetcher = defaultColumnNameFetcher
- }
-
- /** Applies the multi-tenant filter to the collection if the associated entity is multi-tenant. */
- void bind(HibernateToManyEntityProperty entityProperty) {
- GrailsHibernatePersistentEntity referenced = entityProperty.hibernateAssociatedEntity
- if (referenced == null) {
- return
- }
- if (entityProperty.isOneToMany() && referenced.isMultiTenant()) {
- String filterCondition = referenced.getMultiTenantFilterCondition(defaultColumnNameFetcher)
- if (filterCondition != null) {
- Collection collection = entityProperty.collection
- if (entityProperty.isUnidirectionalOneToMany()) {
- collection.addManyToManyFilter(
- GormProperties.TENANT_IDENTITY,
- filterCondition,
- true,
- Collections.emptyMap(),
- Collections.emptyMap())
- }
- else {
- collection.addFilter(
- GormProperties.TENANT_IDENTITY,
- filterCondition,
- true,
- Collections.emptyMap(),
- Collections.emptyMap())
- }
- }
- }
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/UnidirectionalOneToManyBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/UnidirectionalOneToManyBinder.groovy
deleted file mode 100644
index 7c3475b129..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/UnidirectionalOneToManyBinder.groovy
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.secondpass
-
-import groovy.transform.CompileStatic
-import jakarta.annotation.Nonnull
-import org.hibernate.boot.spi.InFlightMetadataCollector
-import org.hibernate.mapping.Backref
-import org.hibernate.mapping.Collection
-import org.hibernate.mapping.ManyToOne
-import org.hibernate.mapping.OneToMany
-import org.hibernate.mapping.Value
-
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateOneToManyProperty
-import org.grails.orm.hibernate.cfg.domainbinding.util.BackticksRemover
-
-import static org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsDomainBinder.UNDERSCORE
-
-/** Binds unidirectional one-to-many associations. */
-@CompileStatic
-class UnidirectionalOneToManyBinder {
-
- private final CollectionWithJoinTableBinder collectionWithJoinTableBinder
- private final BackticksRemover backticksRemover = new BackticksRemover()
- private final InFlightMetadataCollector mappings
-
- UnidirectionalOneToManyBinder(
- CollectionWithJoinTableBinder collectionWithJoinTableBinder, InFlightMetadataCollector mappings) {
- this.collectionWithJoinTableBinder = collectionWithJoinTableBinder
- this.mappings = mappings
- }
-
- void bind(@Nonnull HibernateOneToManyProperty property) {
- Collection collection = property.collection
- if (!property.shouldBindWithForeignKey()) {
- collectionWithJoinTableBinder.bindCollectionWithJoinTable(property)
- }
- else {
- bindUnidirectionalOneToMany(property, collection)
- }
- }
-
- private void bindUnidirectionalOneToMany(
- @Nonnull HibernateOneToManyProperty property, @Nonnull Collection collection) {
- Value element = collection.element
- element.createForeignKey()
-
- String entityName = (element instanceof ManyToOne) ?
- ((ManyToOne) element).referencedEntityName :
- ((OneToMany) element).referencedEntityName
-
- collection.inverse = false
-
- mappings.getEntityBinding(entityName).addProperty(createBackref(property, collection))
- }
-
- private Backref createBackref(HibernateOneToManyProperty property, Collection collection) {
- GrailsHibernatePersistentEntity owner = (GrailsHibernatePersistentEntity) property.owner
- Backref backref = new Backref()
- backref.entityName = owner.name
- backref.name = UNDERSCORE.toString() + backticksRemover.apply(owner.javaClass.simpleName) +
- UNDERSCORE +
- backticksRemover.apply(property.name) +
- 'Backref'
- backref.updatable = false
- backref.insertable = true
- backref.collectionRole = collection.role
- backref.value = collection.key
- backref.optional = true
- return backref
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/UnidirectionalOneToManyInverseValuesBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/UnidirectionalOneToManyInverseValuesBinder.groovy
deleted file mode 100644
index 08082d22c1..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/secondpass/UnidirectionalOneToManyInverseValuesBinder.groovy
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.secondpass
-
-import groovy.transform.CompileStatic
-import org.hibernate.boot.spi.MetadataBuildingContext
-import org.hibernate.mapping.Collection
-import org.hibernate.mapping.ManyToOne
-
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyProperty
-
-/** Creates and binds a {@link ManyToOne} element for unidirectional to-many join-table associations. */
-@CompileStatic
-class UnidirectionalOneToManyInverseValuesBinder {
-
- private final MetadataBuildingContext metadataBuildingContext
-
- UnidirectionalOneToManyInverseValuesBinder(MetadataBuildingContext metadataBuildingContext) {
- this.metadataBuildingContext = metadataBuildingContext
- }
-
- ManyToOne bind(HibernateToManyProperty property) {
- Collection collection = property.collection
- ManyToOne manyToOne = new ManyToOne(metadataBuildingContext, collection.collectionTable)
- manyToOne.ignoreNotFound = property.ignoreNotFound
- manyToOne.lazy = property.isLazy()
- manyToOne.referencedEntityName = property.hibernateAssociatedEntity.name
- return manyToOne
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/DefaultColumnNameFetcher.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/DefaultColumnNameFetcher.groovy
index cfff008eaf..5a713007b9 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/DefaultColumnNameFetcher.groovy
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/DefaultColumnNameFetcher.groovy
@@ -31,8 +31,9 @@ import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyPrope
@SuppressWarnings('PMD.DataflowAnomalyAnalysis')
class DefaultColumnNameFetcher {
- private static final String FOREIGN_KEY_SUFFIX = '_id'
- private static final String UNDERSCORE = '_'
+ /** The suffix of a foreign key column named after the property or the entity it refers to. */
+ public static final String FOREIGN_KEY_SUFFIX = '_id'
+ public static final String UNDERSCORE = '_'
private final PersistentEntityNamingStrategy namingStrategyWrapper
private final BackticksRemover backticksRemover
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/GrailsPropertyResolver.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/GrailsPropertyResolver.groovy
deleted file mode 100644
index 8a9047fe18..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/GrailsPropertyResolver.groovy
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.util
-
-import groovy.transform.CompileStatic
-import org.hibernate.MappingException
-import org.hibernate.mapping.Component
-import org.hibernate.mapping.PersistentClass
-import org.hibernate.mapping.Property
-
-/** Utility class for resolving Grails properties from PersistentClass. */
-@CompileStatic
-class GrailsPropertyResolver {
-
- /**
- * Retrieves a property from a PersistentClass, with a fallback for composite primary keys.
- *
- * @param associatedClass The PersistentClass to get the property from.
- * @param propertyName The name of the property to retrieve.
- * @return The resolved Property.
- * @throws MappingException if the property cannot be found.
- */
- Property getProperty(PersistentClass associatedClass, String propertyName) throws MappingException {
- try {
- return associatedClass.getProperty(propertyName)
- }
- catch (MappingException e) {
- // maybe it's squirreled away in a composite primary key
- if (associatedClass.key instanceof Component) {
- return ((Component) associatedClass.key).getProperty(propertyName)
- }
- throw e
- }
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/MultiTenantFilterBinder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/MultiTenantFilterBinder.groovy
deleted file mode 100644
index eaba17a1c6..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/MultiTenantFilterBinder.groovy
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.util
-
-import groovy.transform.CompileStatic
-import jakarta.annotation.Nonnull
-import jakarta.annotation.Nullable
-import org.hibernate.boot.spi.InFlightMetadataCollector
-import org.hibernate.engine.spi.FilterDefinition
-import org.hibernate.mapping.BasicValue
-import org.hibernate.mapping.JoinedSubclass
-import org.hibernate.mapping.PersistentClass
-import org.hibernate.mapping.Property
-import org.hibernate.mapping.RootClass
-import org.hibernate.mapping.SingleTableSubclass
-import org.hibernate.mapping.Table
-import org.hibernate.mapping.UnionSubclass
-import org.hibernate.mapping.Value
-
-import org.grails.datastore.mapping.model.config.GormProperties
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentEntity
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty
-
-/**
- * Utility class for binding multi-tenant filters to the Hibernate meta model.
- *
- * @since 8.0
- */
-@CompileStatic
-class MultiTenantFilterBinder {
-
- private final GrailsPropertyResolver grailsPropertyResolver
- private final MultiTenantFilterDefinitionBinder filterDefinitionBinder
- private final InFlightMetadataCollector mappings
- private final DefaultColumnNameFetcher fetcher
-
- MultiTenantFilterBinder(
- @Nonnull GrailsPropertyResolver grailsPropertyResolver,
- @Nonnull MultiTenantFilterDefinitionBinder filterDefinitionBinder,
- @Nonnull InFlightMetadataCollector mappings,
- @Nonnull DefaultColumnNameFetcher fetcher) {
- this.grailsPropertyResolver = grailsPropertyResolver
- this.filterDefinitionBinder = filterDefinitionBinder
- this.mappings = mappings
- this.fetcher = fetcher
- }
-
- /**
- * Binds a multi-tenant filter to the given root class if necessary.
- *
- * @param entity The target persistent entity
- * @param rootClass The root class to add the filter to
- * @return The filter definition applied, or null if none
- */
- @Nullable
- FilterDefinition bind(@Nonnull HibernatePersistentEntity entity, @Nonnull RootClass rootClass) {
- return doBind(entity, rootClass)
- }
-
- /**
- * Binds a multi-tenant filter to the given single table subclass if necessary.
- *
- * @param entity The target persistent entity
- * @param subclass The single table subclass
- * @return null as it's redundant for single table subclasses
- */
- @Nullable
- FilterDefinition bind(@Nonnull HibernatePersistentEntity entity, @Nonnull SingleTableSubclass subclass) {
- return null // Redundant for SingleTableSubclass
- }
-
- /**
- * Binds a multi-tenant filter to the given joined subclass if necessary.
- *
- * @param entity The target persistent entity
- * @param subclass The joined subclass
- * @return The filter definition applied, or null if none
- */
- @Nullable
- FilterDefinition bind(@Nonnull HibernatePersistentEntity entity, @Nonnull JoinedSubclass subclass) {
- return doBind(entity, subclass)
- }
-
- /**
- * Binds a multi-tenant filter to the given union subclass if necessary.
- *
- * @param entity The target persistent entity
- * @param subclass The union subclass
- * @return The filter definition applied, or null if none
- */
- @Nullable
- FilterDefinition bind(@Nonnull HibernatePersistentEntity entity, @Nonnull UnionSubclass subclass) {
- return doBind(entity, subclass)
- }
-
- @Nullable
- private FilterDefinition doBind(
- @Nonnull HibernatePersistentEntity entity, @Nonnull PersistentClass persistentClass) {
-
- if (!entity.isMultiTenant()) {
- return null
- }
-
- HibernatePersistentProperty tenantId = entity.hibernateTenantId
- if (tenantId == null) {
- return null
- }
-
- String name = tenantId.name
- Property property = grailsPropertyResolver.getProperty(persistentClass, name)
- if (property == null || !shouldApplyFilter(entity, persistentClass, property)) {
- return null
- }
-
- String filterName = GormProperties.TENANT_IDENTITY
- FilterDefinition filterDefinition = mappings.getFilterDefinition(filterName)
- if (filterDefinition == null) {
- filterDefinition = filterDefinitionBinder.create(filterName, property).orElse(null)
- if (filterDefinition != null) {
- mappings.addFilterDefinition(filterDefinition)
- }
- }
-
- if (filterDefinition != null) {
- persistentClass.addFilter(
- filterName,
- entity.getMultiTenantFilterCondition(fetcher),
- true, // autoAliasInjection
- Collections.emptyMap(),
- Collections.emptyMap())
- }
- return filterDefinition
- }
-
- private boolean shouldApplyFilter(
- HibernatePersistentEntity entity, PersistentClass persistentClass, Property property) {
- if (!(property.value instanceof BasicValue)) {
- return false
- }
-
- boolean isRoot = persistentClass instanceof RootClass
-
- Table table = persistentClass.table
- Value propertyValue = property.value
- Table propertyTable = propertyValue != null ? propertyValue.table : null
-
- boolean isInherited = table != null && propertyTable != null && table != propertyTable
-
- if (isRoot || !isInherited) {
- return isRoot || !entity.isTablePerHierarchySubclass()
- }
- return false
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/NamingStrategyWrapper.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/NamingStrategyWrapper.groovy
index 716b262c6a..7113bb84a7 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/NamingStrategyWrapper.groovy
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/NamingStrategyWrapper.groovy
@@ -28,7 +28,7 @@ import org.grails.orm.hibernate.cfg.PersistentEntityNamingStrategy
import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity
import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty
-import static org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsDomainBinder.FOREIGN_KEY_SUFFIX
+import static org.grails.orm.hibernate.cfg.domainbinding.util.DefaultColumnNameFetcher.FOREIGN_KEY_SUFFIX
import static org.hibernate.boot.model.naming.Identifier.toIdentifier
/**
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/OrderByClauseBuilder.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/OrderByClauseBuilder.groovy
deleted file mode 100644
index a03c4b2a1d..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/OrderByClauseBuilder.groovy
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.util
-
-import groovy.transform.CompileStatic
-import org.hibernate.boot.model.internal.BinderHelper
-import org.hibernate.mapping.PersistentClass
-import org.hibernate.mapping.Property
-import org.hibernate.mapping.SingleTableSubclass
-import org.hibernate.mapping.Selectable
-
-import org.grails.datastore.mapping.model.DatastoreConfigurationException
-
-/** Utility class to build SQL order by clauses from HQL-style order by strings. */
-@CompileStatic
-@SuppressWarnings('PMD.DataflowAnomalyAnalysis')
-class OrderByClauseBuilder {
-
- String buildOrderByClause(
- String hqlOrderBy, PersistentClass associatedClass, String role, String defaultOrder) {
- if (hqlOrderBy == null) {
- return null
- }
-
- if (hqlOrderBy.isEmpty()) {
- List<String> parts = []
- for (Selectable selectable : associatedClass.identifier.selectables) {
- parts.add(selectable.text + ' asc')
- }
- return parts.join(', ')
- }
-
- List<SortEntry> entries = parseSortEntries(hqlOrderBy, role, defaultOrder)
-
- List<String> parts = []
- for (SortEntry entry : entries) {
- parts.add(buildPropertyOrderBy(entry, associatedClass))
- }
- return parts.join(', ')
- }
-
- private List<SortEntry> parseSortEntries(String hqlOrderBy, String role, String defaultOrder) {
- String[] tokens = hqlOrderBy.split('[ ,]+')
- List<SortEntry> entries = new ArrayList<>()
- SortEntry currentEntry = null
-
- for (String token : tokens) {
- if (token.isEmpty()) {
- continue
- }
-
- if (isDirectionToken(token)) {
- if (currentEntry == null || currentEntry.direction != null) {
- throw new DatastoreConfigurationException(
- "Error while parsing sort clause: ${hqlOrderBy} (${role})".toString())
- }
- currentEntry.direction = token.toLowerCase(Locale.ROOT)
- }
- else {
- if (currentEntry != null && currentEntry.direction == null) {
- currentEntry.direction = 'asc'
- }
- currentEntry = new SortEntry(token)
- entries.add(currentEntry)
- }
- }
-
- if (currentEntry != null && currentEntry.direction == null) {
- currentEntry.direction = defaultOrder
- }
-
- return entries
- }
-
- private String buildPropertyOrderBy(SortEntry entry, PersistentClass associatedClass) {
- Property p = BinderHelper.findPropertyByName(associatedClass, entry.property)
- if (p == null) {
- throw new DatastoreConfigurationException(
- "property from sort clause not found: ${associatedClass.entityName}.${entry.property}".toString())
- }
-
- String tablePrefix = getTablePrefix(p, associatedClass)
- String direction = entry.direction
-
- List<String> parts = []
- for (Selectable selectable : p.selectables) {
- parts.add(tablePrefix + selectable.text + ' ' + direction)
- }
- return parts.join(', ')
- }
-
- private String getTablePrefix(Property p, PersistentClass associatedClass) {
- PersistentClass pc = p.persistentClass
- if (pc == null ||
- pc == associatedClass ||
- (associatedClass instanceof SingleTableSubclass &&
- pc.mappedClass.isAssignableFrom(associatedClass.mappedClass))) {
- return ''
- }
- return pc.table.quotedName + '.'
- }
-
- private boolean isDirectionToken(String token) {
- return 'asc'.equalsIgnoreCase(token) || 'desc'.equalsIgnoreCase(token)
- }
-
- private static class SortEntry {
-
- final String property
- String direction
-
- SortEntry(String property) {
- this.property = property
- }
-
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/PropertyFromValueCreator.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/PropertyFromValueCreator.groovy
deleted file mode 100644
index 3ef4f2cd29..0000000000
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/PropertyFromValueCreator.groovy
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.util
-
-import groovy.transform.CompileStatic
-import org.hibernate.mapping.Property
-import org.hibernate.mapping.Value
-
-import org.grails.orm.hibernate.cfg.domainbinding.binder.PropertyBinder
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateEnumProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty
-
-@CompileStatic
-class PropertyFromValueCreator {
-
- private final PropertyBinder propertyBinder
-
- PropertyFromValueCreator() {
- this.propertyBinder = new PropertyBinder()
- }
-
- protected PropertyFromValueCreator(PropertyBinder propertyBinder) {
- this.propertyBinder = propertyBinder
- }
-
- Property createProperty(Value value, HibernatePersistentProperty grailsProperty) {
- // set type
- if (!(grailsProperty instanceof HibernateEnumProperty)) {
- value.setTypeUsingReflection(grailsProperty.ownerClassName, grailsProperty.name)
- }
-
- if (value.table != null) {
- value.createForeignKey()
- }
-
- return propertyBinder.bindProperty(grailsProperty, value)
- }
-
-}
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/TableForManyCalculator.groovy b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/TableForManyCalculator.groovy
index da546bbff6..ce21d9c317 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/TableForManyCalculator.groovy
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/TableForManyCalculator.groovy
@@ -32,7 +32,7 @@ import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateManyToManyP
import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty
import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyProperty
-import static org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsDomainBinder.UNDERSCORE
+import static org.grails.orm.hibernate.cfg.domainbinding.util.DefaultColumnNameFetcher.UNDERSCORE
@CompileStatic
@SuppressWarnings('PMD.DataflowAnomalyAnalysis')
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/HibernateGormDatastoreSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/HibernateGormDatastoreSpec.groovy
index a154d07667..a8d5e4895e 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/HibernateGormDatastoreSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/HibernateGormDatastoreSpec.groovy
@@ -22,13 +22,11 @@ package grails.gorm.tests
import org.apache.grails.data.hibernate7.core.GrailsDataHibernate7TckManager
import org.apache.grails.data.testing.tck.base.GrailsDataTckSpec
-import org.grails.datastore.mapping.core.connections.ConnectionSource
import org.grails.datastore.mapping.model.PersistentEntity
import org.grails.orm.hibernate.HibernateSession
import org.grails.orm.hibernate.HibernateDatastore
-import org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsDomainBinder
import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentEntity
+import org.grails.orm.hibernate.cfg.domainbinding.jpa.GormMappingContributor
import org.grails.orm.hibernate.cfg.HibernateMappingContext
import org.grails.orm.hibernate.query.HibernateQuery
@@ -77,40 +75,11 @@ class HibernateGormDatastoreSpec extends GrailsDataTckSpec<GrailsDataHibernate7T
collectorRegistries.clear()
}
- GrailsHibernatePersistentEntity createPersistentEntity(GrailsDomainBinder binder
- , String className
- , Map<String, Class> fieldProperties
- , Map<String, String> staticMapping
- , List<String> embeddedProps = []
- , Map<String, Class> hasManyMap = [:]
- , Map<String, Class> belongsToMap = [:]
-
- ) {
- def classLoader = new GroovyClassLoader()
- def classText = """
- package foo
- import grails.gorm.annotation.Entity
- import grails.gorm.hibernate.HibernateEntity
- @Entity
- class ${className} implements HibernateEntity<${className}> {
-
- ${fieldProperties.collect { name, type -> "${(type instanceof Class ? type : type.javaClass).name} ${name}" }.join('\n ')}
-
- static embedded = ${embeddedProps.inspect()}
- static hasMany = [${hasManyMap.collect { name, type -> "${name}: ${(type instanceof Class ? type : type.javaClass).name}" }.join(', ')}]
- static belongsTo = [${belongsToMap.collect { name, type -> "${name}: ${(type instanceof Class ? type : type.javaClass).name}" }.join(', ')}]
-
- static mapping = {
- ${staticMapping.collect { name, value -> "${name} ${value}" }.join('\n ')}
- }
- }
- """
-
- def clazz = classLoader.parseClass(classText)
- createPersistentEntity(clazz, binder)
- }
-
- GrailsHibernatePersistentEntity createPersistentEntity(Class clazz, GrailsDomainBinder binder) {
+ /**
+ * Adds a domain class to the mapping context of the datastore and caches its mapping, without binding it: for specs of
+ * the mapping model.
+ */
+ GrailsHibernatePersistentEntity createPersistentEntity(Class clazz) {
def entity = getMappingContext().addPersistentEntity(clazz) as GrailsHibernatePersistentEntity
if (entity != null) {
getMappingContext().getMappingCacheHolder().cacheMapping(entity)
@@ -118,10 +87,6 @@ class HibernateGormDatastoreSpec extends GrailsDataTckSpec<GrailsDataHibernate7T
entity
}
- GrailsHibernatePersistentEntity createPersistentEntity(Class clazz) {
- return createPersistentEntity(clazz, getGrailsDomainBinder())
- }
-
protected InFlightMetadataCollectorImpl getCollector() {
def bootstrapServiceRegistry = getServiceRegistry()
.getParentServiceRegistry()
@@ -146,13 +111,17 @@ class HibernateGormDatastoreSpec extends GrailsDataTckSpec<GrailsDataHibernate7T
manager.hibernateDatastore.getMappingContext()
}
- protected GrailsDomainBinder getGrailsDomainBinder() {
+ /**
+ * The contributor through which the datastore handed its domain classes to Hibernate: the naming strategy, the
+ * building context and the JDBC environment of the boot.
+ */
+ protected GormMappingContributor getMappingContributor() {
def registry = getServiceRegistry()
registry
.getParentServiceRegistry()
.getService(ClassLoaderService.class)
.loadJavaServices(AdditionalMappingContributor.class)
- .find { it instanceof GrailsDomainBinder }
+ .find { it instanceof GormMappingContributor }
}
protected ServiceRegistryImplementor getServiceRegistry() {
@@ -185,19 +154,6 @@ class HibernateGormDatastoreSpec extends GrailsDataTckSpec<GrailsDataHibernate7T
return new HibernateQuery(session, getPersistentEntity(clazz))
}
- /**
- * Triggers the first-pass Hibernate mapping for all registered entities.
- * This initializes the Hibernate Collection, Table, and Column objects
- * required for SecondPass binder tests.
- */
- protected void hibernateFirstPass() {
- def gdb = getGrailsDomainBinder()
- def collector = gdb.getMetadataBuildingContext().getMetadataCollector()
- List<HibernatePersistentEntity> entities = getMappingContext().getHibernatePersistentEntities()
- entities.each { it.setDataSourceName(ConnectionSource.DEFAULT) }
- gdb.contribute(collector, entities)
- }
-
/**
* Returns true when a Docker daemon is reachable on this machine.
* <p>
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/GrailsHibernatePersistentPropertySpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/GrailsHibernatePersistentPropertySpec.groovy
index ae58a2c221..e722f51294 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/GrailsHibernatePersistentPropertySpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/GrailsHibernatePersistentPropertySpec.groovy
@@ -177,7 +177,7 @@ class GrailsHibernatePersistentPropertySpec extends HibernateGormDatastoreSpec {
void "test getTypeName(SimpleValue) and getTypeParameters(SimpleValue)"() {
given:
- def domainBinder = getGrailsDomainBinder()
+ def domainBinder = getMappingContributor()
def metadataBuildingContext = domainBinder.getMetadataBuildingContext()
def table = new Table("TEST")
PersistentEntity entity = createPersistentEntity(TestEntityWithTypeName)
@@ -192,7 +192,7 @@ class GrailsHibernatePersistentPropertySpec extends HibernateGormDatastoreSpec {
void "test getTypeName(SimpleValue) with fallback"() {
given:
- def domainBinder = getGrailsDomainBinder()
+ def domainBinder = getMappingContributor()
def metadataBuildingContext = domainBinder.getMetadataBuildingContext()
def table = new Table("TEST2")
PersistentEntity entity = createPersistentEntity(TestEntityWithEnum)
@@ -206,7 +206,7 @@ class GrailsHibernatePersistentPropertySpec extends HibernateGormDatastoreSpec {
void "test getTypeName(SimpleValue) for DependantValue"() {
given:
- def domainBinder = getGrailsDomainBinder()
+ def domainBinder = getMappingContributor()
def metadataBuildingContext = domainBinder.getMetadataBuildingContext()
def table = new Table("TEST3")
PersistentEntity entity = createPersistentEntity(BMTOWLMAuthor)
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/MappingSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/MappingSpec.groovy
index 49549f20fb..3b842b8478 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/MappingSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/MappingSpec.groovy
@@ -31,10 +31,9 @@ class MappingSpec extends HibernateGormDatastoreSpec {
@Unroll
void "test isCompositeIdProperty should return #expectedResult for #description"() {
given: "A persistent entity and its mapping"
- def binder = grailsDomainBinder
// Ensure all related entities are processed by the mapping context
- createPersistentEntity(Author, binder)
- def entity = createPersistentEntity(domainClass, binder)
+ createPersistentEntity(Author)
+ def entity = createPersistentEntity(domainClass)
def mapping = (Mapping) entity.getMappedForm()
def property = entity.getPropertyByName(propertyName)
@@ -55,8 +54,7 @@ class MappingSpec extends HibernateGormDatastoreSpec {
@Unroll
void "test isIdentityProperty should return #expectedResult for #description"() {
given: "A persistent entity and its property"
- def binder = grailsDomainBinder
- def entity = createPersistentEntity(domainClass, binder)
+ def entity = createPersistentEntity(domainClass)
def property = entity.getPropertyByName(propertyName)
when: "The method is called on the property itself"
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/NaturalIdSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/NaturalIdSpec.groovy
index a7e8ee5cf1..6755b004e6 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/NaturalIdSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/NaturalIdSpec.groovy
@@ -39,7 +39,7 @@ class NaturalIdSpec extends HibernateGormDatastoreSpec {
property.value = value
def column = new Column("id1")
def table = new Table("test_table")
- def rootClass = new RootClass(getGrailsDomainBinder().getMetadataBuildingContext())
+ def rootClass = new RootClass(getMappingContributor().getMetadataBuildingContext())
rootClass.addProperty(property)
rootClass.table = table
value.getSelectables() >> [column]
@@ -73,7 +73,7 @@ class NaturalIdSpec extends HibernateGormDatastoreSpec {
def column2 = new Column("id2")
def table = new Table("test_table")
- def rootClass = new RootClass(getGrailsDomainBinder().getMetadataBuildingContext())
+ def rootClass = new RootClass(getMappingContributor().getMetadataBuildingContext())
rootClass.addProperty(property1)
rootClass.addProperty(property2)
rootClass.table = table
@@ -100,7 +100,7 @@ class NaturalIdSpec extends HibernateGormDatastoreSpec {
given:
def naturalId = new NaturalId(propertyNames: [], mutable: false)
def table = new Table("test_table")
- def rootClass = new RootClass(getGrailsDomainBinder().getMetadataBuildingContext())
+ def rootClass = new RootClass(getMappingContributor().getMetadataBuildingContext())
rootClass.table = table
when:
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/BasicValueCreatorSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/BasicValueCreatorSpec.groovy
index a234b68cf9..7b9bacdc83 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/BasicValueCreatorSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/BasicValueCreatorSpec.groovy
@@ -48,7 +48,7 @@ class BasicValueCreatorSpec extends HibernateGormDatastoreSpec {
PersistentEntityNamingStrategy namingStrategy
def setup() {
- metadataBuildingContext = getGrailsDomainBinder().getMetadataBuildingContext()
+ metadataBuildingContext = getMappingContributor().getMetadataBuildingContext()
jdbcEnvironment = Mock(JdbcEnvironment)
namingStrategy = Mock(PersistentEntityNamingStrategy)
grailsSequenceWrapper = Mock(GrailsSequenceWrapper)
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CascadeBehaviorFetcherSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CascadeBehaviorFetcherSpec.groovy
index 1b441b50b5..a6b8ee3afb 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CascadeBehaviorFetcherSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CascadeBehaviorFetcherSpec.groovy
@@ -99,8 +99,8 @@ class CascadeBehaviorFetcherSpec extends HibernateGormDatastoreSpec {
@Unroll
void "test cascade behavior fetcher for #description"() {
given: "A persistent property from the test entity"
- createPersistentEntity(childClass, grailsDomainBinder)
- def testProperty = createPersistentEntity(ownerClass, grailsDomainBinder)
+ createPersistentEntity(childClass)
+ def testProperty = createPersistentEntity(ownerClass)
.getPropertyByName(associationName)
when: "Getting the cascade behavior"
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ClassBinderSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ClassBinderSpec.groovy
deleted file mode 100644
index b4ce18d5c7..0000000000
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ClassBinderSpec.groovy
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding
-
-import grails.gorm.tests.HibernateGormDatastoreSpec
-import org.hibernate.mapping.RootClass
-
-import org.grails.orm.hibernate.cfg.domainbinding.binder.ClassBinder
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentEntity
-
-class ClassBinderSpec extends HibernateGormDatastoreSpec {
-
-
- void "Test defaults"() {
- when:
-
- def collector = getCollector()
- def grailsDomainBinder = getGrailsDomainBinder()
-
- def simpleName = "Book"
- def persistentName = "foo.Book"
- def persistentEntity = createPersistentEntity(grailsDomainBinder,simpleName, [:], [:])
- def root = new RootClass(grailsDomainBinder.metadataBuildingContext);
- def binder = new ClassBinder(collector)
-
- binder.bindClass(persistentEntity as org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentEntity, root)
- then:
- root.getEntityName() == persistentName
- root.getJpaEntityName() == simpleName
- root.getProxyInterfaceName() == persistentName
- root.getClassName() == persistentName
- root.isLazy()
- !root.useDynamicInsert()
- !root.useDynamicUpdate()
- !root.hasSelectBeforeUpdate()
- root.getBatchSize() == 0
- collector.getImports()[simpleName] == persistentName
- }
-
- void "Test autoImport true"() {
- when:
-
- def collector = getCollector()
- def grailsDomainBinder = getGrailsDomainBinder()
-
- def simpleName = "Book"
- def persistentName = "foo.Book"
- def persistentEntity = createPersistentEntity(grailsDomainBinder,simpleName, [:], [autoImport: "true"])
- def root = new RootClass(grailsDomainBinder.metadataBuildingContext);
- def binder = new ClassBinder(collector)
-
- binder.bindClass(persistentEntity as org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentEntity, root)
- then:
- root.getEntityName() == persistentName
- root.getJpaEntityName() == simpleName
- root.getProxyInterfaceName() == persistentName
- root.getClassName() == persistentName
- root.isLazy()
- !root.useDynamicInsert()
- !root.useDynamicUpdate()
- !root.hasSelectBeforeUpdate()
- root.getBatchSize() == 0
- collector.getImports()[simpleName] == persistentName
- }
-
- void "Test autoImport false"() {
- when:
-
- def collector = getCollector()
- def grailsDomainBinder = getGrailsDomainBinder()
-
- def simpleName = "Book"
- def persistentName = "foo.Book"
- def persistentEntity = createPersistentEntity(grailsDomainBinder, simpleName, [:], [autoImport: "false"])
- def root = new RootClass(grailsDomainBinder.metadataBuildingContext);
- def binder = new ClassBinder(collector)
-
- binder.bindClass(persistentEntity as org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentEntity, root)
- then:
- root.getEntityName() == persistentName
- root.getJpaEntityName() == persistentName
- root.getProxyInterfaceName() == persistentName
- root.getClassName() == persistentName
- root.isLazy()
- !root.useDynamicInsert()
- !root.useDynamicUpdate()
- !root.hasSelectBeforeUpdate()
- root.getBatchSize() == 0
- !collector.getImports()[simpleName]
- }
-
- void "Test dynamic update and insert true"() {
- when:
-
- def collector = getCollector()
- def grailsDomainBinder = getGrailsDomainBinder()
-
- def simpleName = "Book"
- def persistentName = "foo.Book"
- def persistentEntity = createPersistentEntity(grailsDomainBinder,simpleName, [:], [dynamicUpdate: "true", dynamicInsert: "true", batchSize: "10"])
- def root = new RootClass(grailsDomainBinder.metadataBuildingContext);
- def binder = new ClassBinder(collector)
-
- binder.bindClass(persistentEntity as org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentEntity, root)
- then:
- root.getEntityName() == persistentName
- root.getJpaEntityName() == simpleName
- root.getProxyInterfaceName() == persistentName
- root.getClassName() == persistentName
- root.isLazy()
- root.useDynamicInsert()
- root.useDynamicUpdate()
- !root.hasSelectBeforeUpdate()
- root.getBatchSize() == 10
- collector.getImports()[simpleName] == persistentName
- }
-
- void "Test abstract entity sets abstract flag"() {
- given:
- def collector = getCollector()
- def grailsDomainBinder = getGrailsDomainBinder()
- def root = new RootClass(grailsDomainBinder.metadataBuildingContext)
- def binder = new ClassBinder(collector)
-
- def mockEntity = Mock(HibernatePersistentEntity)
- mockEntity.getName() >> "foo.Animal"
- mockEntity.isAbstract() >> true
- mockEntity.getHibernateMappedForm() >> null
-
- when:
- binder.bindClass(mockEntity, root)
-
- then:
- root.isAbstract()
- }
-
- void "Test null mappedForm uses collector defaults"() {
- when:
- def collector = getCollector()
- def grailsDomainBinder = getGrailsDomainBinder()
-
- // Create entity with no mapping block so mappedForm returns defaults (no dynamicUpdate/Insert/batchSize)
- def persistentEntity = createPersistentEntity(grailsDomainBinder, "Widget", [:], [:])
- def root = new RootClass(grailsDomainBinder.metadataBuildingContext)
- def binder = new ClassBinder(collector)
-
- // Force mappedForm to null via mock to exercise the else branch
- def mockEntity = Mock(org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentEntity)
- mockEntity.getName() >> "foo.Widget"
- mockEntity.isAbstract() >> false
- mockEntity.getHibernateMappedForm() >> null
-
- binder.bindClass(mockEntity, root)
-
- then:
- !root.useDynamicInsert()
- !root.useDynamicUpdate()
- root.getBatchSize() == 0
- }
-}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CollectionBinderFixtures.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CollectionBinderFixtures.groovy
new file mode 100644
index 0000000000..517ccae600
--- /dev/null
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CollectionBinderFixtures.groovy
@@ -0,0 +1,87 @@
+/*
+ * 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 org.grails.orm.hibernate.cfg.domainbinding
+
+import grails.gorm.annotation.Entity
+
+/**
+ * Domain classes of the former {@code CollectionBinderSpec}, a unit spec of the classic domain binder of Grails 8: they stay as fixtures of the
+ * differential specs, which compare native binding with the recorded classic schema of every scanned entity.
+ */
+@Entity
+class CBNamedOwner {
+ Long id
+ static hasMany = [others: CBNamedInverse]
+ static mapping = {
+ others joinTable: [name: 'cb_named_join', schema: 'cb_schema', key: 'owner_ref', column: 'inverse_ref']
+ }
+}
+
+@Entity
+class CBNamedInverse {
+ Long id
+ static hasMany = [owners: CBNamedOwner]
+ static belongsTo = CBNamedOwner
+}
+
+@Entity
+class CBOwnNameOwner {
+ Long id
+ static hasMany = [others: CBOwnNameInverse]
+ static mapping = {
+ others joinTable: [name: 'cb_owner_name', schema: 'cb_schema']
+ }
+}
+
+@Entity
+class CBOwnNameInverse {
+ Long id
+ static hasMany = [owners: CBOwnNameOwner]
+ static belongsTo = CBOwnNameOwner
+ static mapping = {
+ owners joinTable: [name: 'cb_inverse_own_name']
+ }
+}
+
+@Entity
+class Person {
+ Long id
+ String name
+ static hasMany = [pets: Pet]
+}
+
+@Entity
+class Pet {
+ Long id
+ String name
+ static belongsTo = [owner: Person]
+}
+
+@Entity
+class CBManyToManyA {
+ Long id
+ static hasMany = [others: CBManyToManyB]
+}
+
+@Entity
+class CBManyToManyB {
+ Long id
+ static hasMany = [owners: CBManyToManyA]
+ static belongsTo = CBManyToManyA
+}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CollectionBinderSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CollectionBinderSpec.groovy
deleted file mode 100644
index 656c1d0fb4..0000000000
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CollectionBinderSpec.groovy
+++ /dev/null
@@ -1,227 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding
-
-import grails.gorm.annotation.Entity
-import grails.gorm.tests.HibernateGormDatastoreSpec
-import org.grails.orm.hibernate.cfg.domainbinding.binder.CollectionBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.ManyToOneBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.ManyToOneValuesBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.CompositeIdentifierToManyToOneBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.EnumTypeBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.SimpleValueBinder
-import org.grails.orm.hibernate.cfg.domainbinding.collectionType.CollectionHolder
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyEntityProperty
-import org.grails.orm.hibernate.cfg.domainbinding.util.ColumnNameForPropertyAndPathFetcher
-import org.grails.orm.hibernate.cfg.domainbinding.util.DefaultColumnNameFetcher
-import org.grails.orm.hibernate.cfg.domainbinding.util.SimpleValueColumnFetcher
-import org.grails.orm.hibernate.cfg.domainbinding.util.BackticksRemover
-import org.grails.orm.hibernate.cfg.domainbinding.util.TableForManyCalculator
-import org.hibernate.boot.spi.InFlightMetadataCollector
-import org.hibernate.mapping.OneToMany
-import org.hibernate.mapping.Table
-
-class CollectionBinderSpec extends HibernateGormDatastoreSpec {
-
- CollectionBinder binder
- InFlightMetadataCollector mockCollector
- TableForManyCalculator mockCalculator
-
- void setup() {
- def gdb = getGrailsDomainBinder()
- def mbc = gdb.getMetadataBuildingContext()
- def ns = gdb.getNamingStrategy()
- def je = gdb.getJdbcEnvironment()
- mockCollector = Mock(InFlightMetadataCollector) {
- getMetadataBuildingOptions() >> mbc.getMetadataCollector().getMetadataBuildingOptions()
- getBootstrapContext() >> mbc.getMetadataCollector().getBootstrapContext()
- getDatabase() >> mbc.getMetadataCollector().getDatabase()
- addTable(_, _, _, _, _, _, _) >> { schema, catalog, name, sub, isAbstract, context, isView ->
- return new Table("test", name).with {
- setSchema(schema)
- setCatalog(catalog)
- return it
- }
- }
- }
-
- def svb = new SimpleValueBinder(mbc, ns, je)
- def svcf = new SimpleValueColumnFetcher()
- def backticksRemover = new BackticksRemover()
- def dcnf = new DefaultColumnNameFetcher(ns, backticksRemover)
- def cnfpapf = new ColumnNameForPropertyAndPathFetcher(ns, dcnf, backticksRemover)
- def etb = new EnumTypeBinder(mbc, cnfpapf, ns)
- def citmto = new CompositeIdentifierToManyToOneBinder(new org.grails.orm.hibernate.cfg.domainbinding.util.ForeignKeyColumnCountCalculator(), ns, dcnf, backticksRemover, svb)
- def mtob = new ManyToOneBinder(mbc, ns, svb, new ManyToOneValuesBinder(), citmto)
- def ch = new CollectionHolder(mbc)
- mockCalculator = Mock(TableForManyCalculator)
-
- binder = new CollectionBinder(mbc, ns, svb, etb, mtob, citmto, svcf, ch, mockCollector, mockCalculator)
- }
-
- def setupSpec() {
- manager.registerDomainClasses(Person, Pet, CBManyToManyA, CBManyToManyB, CBNamedOwner, CBNamedInverse, CBOwnNameOwner, CBOwnNameInverse)
- }
-
- void "test bindCollection delegates configuration to property.setCollection"() {
- given:
- def personEntity = mappingContext.getPersistentEntity(Person.name) as GrailsHibernatePersistentEntity
- def petsProp = personEntity.getPropertyByName("pets") as HibernateToManyEntityProperty
-
- when:
- def collection = binder.bindCollection(petsProp, "my.path")
-
- then:
- 1 * mockCollector.addCollectionBinding(_)
- collection.role == "${Person.name}.my.path.pets".toString()
- collection.fetchMode == petsProp.getFetchMode()
- collection.batchSize == petsProp.getBatchSize()
-
- and: "Property has been initialized"
- petsProp.getCollection() == collection
- }
-
- void "test bindCollection for many-to-many uses calculator"() {
- given:
- def entityA = mappingContext.getPersistentEntity(CBManyToManyA.name) as GrailsHibernatePersistentEntity
- def othersProp = entityA.getPropertyByName("others") as HibernateToManyProperty
-
- mockCalculator.getTableName(othersProp) >> "custom_join_table"
- mockCalculator.getJoinTableSchema(othersProp) >> "custom_schema"
- mockCalculator.getJoinTableCatalog(othersProp) >> "custom_catalog"
-
- when:
- def collection = binder.bindCollection(othersProp, "")
-
- then:
- 1 * mockCollector.addCollectionBinding(_)
- collection.collectionTable.name == "custom_join_table"
- collection.collectionTable.schema == "custom_schema"
- collection.collectionTable.catalog == "custom_catalog"
- }
-
- void "the inverse side of a many-to-many adopts the join table the owner configures"() {
- given:
- def inverseEntity = mappingContext.getPersistentEntity(CBNamedInverse.name) as GrailsHibernatePersistentEntity
- def ownersProp = inverseEntity.getPropertyByName("owners") as HibernateToManyProperty
-
- when:
- binder.bindCollection(ownersProp, "")
-
- then:
- def joinTable = ownersProp.hibernateMappedForm.joinTable
- joinTable.name == "cb_named_join"
- joinTable.schema == "cb_schema"
- joinTable.keys*.name == ["inverse_ref"]
- joinTable.column.name == "owner_ref"
- }
-
- void "the owning side keeps its own join table configuration when the inverse side is bound"() {
- given:
- def ownerEntity = mappingContext.getPersistentEntity(CBNamedOwner.name) as GrailsHibernatePersistentEntity
- def othersProp = ownerEntity.getPropertyByName("others") as HibernateToManyProperty
-
- when:
- binder.bindCollection(othersProp, "")
-
- then:
- def joinTable = othersProp.hibernateMappedForm.joinTable
- joinTable.name == "cb_named_join"
- joinTable.keys*.name == ["owner_ref"]
- joinTable.column.name == "inverse_ref"
- }
-
- void "an inverse side that names its own join table is not overwritten by the owner's"() {
- given:
- def inverseEntity = mappingContext.getPersistentEntity(CBOwnNameInverse.name) as GrailsHibernatePersistentEntity
- def ownersProp = inverseEntity.getPropertyByName("owners") as HibernateToManyProperty
-
- when:
- binder.bindCollection(ownersProp, "")
-
- then:
- def joinTable = ownersProp.hibernateMappedForm.joinTable
- joinTable.name == "cb_inverse_own_name"
- joinTable.schema == null
- }
-}
-
-@Entity
-class CBNamedOwner {
- Long id
- static hasMany = [others: CBNamedInverse]
- static mapping = {
- others joinTable: [name: 'cb_named_join', schema: 'cb_schema', key: 'owner_ref', column: 'inverse_ref']
- }
-}
-
-@Entity
-class CBNamedInverse {
- Long id
- static hasMany = [owners: CBNamedOwner]
- static belongsTo = CBNamedOwner
-}
-
-@Entity
-class CBOwnNameOwner {
- Long id
- static hasMany = [others: CBOwnNameInverse]
- static mapping = {
- others joinTable: [name: 'cb_owner_name', schema: 'cb_schema']
- }
-}
-
-@Entity
-class CBOwnNameInverse {
- Long id
- static hasMany = [owners: CBOwnNameOwner]
- static belongsTo = CBOwnNameOwner
- static mapping = {
- owners joinTable: [name: 'cb_inverse_own_name']
- }
-}
-
-@Entity
-class Person {
- Long id
- String name
- static hasMany = [pets: Pet]
-}
-
-@Entity
-class Pet {
- Long id
- String name
- static belongsTo = [owner: Person]
-}
-
-@Entity
-class CBManyToManyA {
- Long id
- static hasMany = [others: CBManyToManyB]
-}
-
-@Entity
-class CBManyToManyB {
- Long id
- static hasMany = [owners: CBManyToManyA]
- static belongsTo = CBManyToManyA
-}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CollectionForPropertyConfigBinderSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CollectionForPropertyConfigBinderSpec.groovy
deleted file mode 100644
index 90c8d7cd75..0000000000
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CollectionForPropertyConfigBinderSpec.groovy
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding
-
-import grails.gorm.tests.HibernateGormDatastoreSpec
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyProperty
-import org.hibernate.FetchMode
-import org.hibernate.mapping.RootClass
-import org.hibernate.mapping.Set
-import spock.lang.Subject
-import spock.lang.Unroll
-
-import org.grails.orm.hibernate.cfg.domainbinding.binder.CollectionForPropertyConfigBinder
-
-class CollectionForPropertyConfigBinderSpec extends HibernateGormDatastoreSpec {
-
- @Subject
- CollectionForPropertyConfigBinder binder = new CollectionForPropertyConfigBinder()
-
-
-
-
- @Unroll
- def "should bind lazy settings based on fetch mode '#fetchMode.name()'} and an explicit lazy config of #lazySetting"() {
- given: "A hibernate collection and a mocked property"
- def owner = new RootClass(grailsDomainBinder.metadataBuildingContext)
- def collection = new Set(grailsDomainBinder.metadataBuildingContext, owner)
- def property = Mock(HibernateToManyProperty)
-
- // Set initial state
- collection.setLazy(false)
- collection.setExtraLazy(false)
-
- and: "the property is stubbed"
- property.getFetchMode() >> fetchMode
- property.getLazy() >> lazySetting
- property.getCollection() >> collection
- property.isLazy() >> expectedIsLazy
-
- when: "the binder is applied"
- binder.bindCollectionForPropertyConfig(property)
-
- then: "the collection's lazy and extraLazy properties are set according to the binder's logic"
- collection.isLazy() == expectedIsLazy
- collection.isExtraLazy() == expectedIsExtraLazy
-
- where:
- fetchMode | lazySetting || expectedIsLazy | expectedIsExtraLazy
- FetchMode.JOIN | true || false | true
- FetchMode.JOIN | false || false | false
- FetchMode.JOIN | null || false | false
- FetchMode.SELECT | true || true | true
- FetchMode.SELECT | false || true | false
- FetchMode.SELECT | null || true | false
-// FetchMode.SUBSELECT | true || true | true
- }
-
-
-
-}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ColumnBinderFixtures.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ColumnBinderFixtures.groovy
new file mode 100644
index 0000000000..f58fa23c64
--- /dev/null
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ColumnBinderFixtures.groovy
@@ -0,0 +1,131 @@
+/*
+ * 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 org.grails.orm.hibernate.cfg.domainbinding
+
+import grails.gorm.annotation.Entity
+
+/**
+ * Domain classes of the former {@code ColumnBinderSpec}, a unit spec of the classic domain binder of Grails 8: they stay as fixtures of the
+ * differential specs, which compare native binding with the recorded classic schema of every scanned entity.
+ */
+@Entity
+class CBBook {
+ String title
+ static hasMany = [authors: CBAuthor]
+ static mapping = {
+ authors joinTable: [name: "cb_book_authors", key: "book_id", column: "author_id"]
+ }
+ static constraints = {
+ title nullable: false
+ authors nullable: true
+ }
+}
+
+@Entity
+class CBAuthor {
+ String name
+ static constraints = {
+ name nullable: false
+ }
+}
+
+@Entity
+class CBNumericBase {
+}
+
+@Entity
+class CBNumericSub extends CBNumericBase {
+ Integer num
+ static constraints = {
+ num nullable: false
+ }
+}
+
+@Entity
+class CBOwner {
+ static hasOne = [pet: CBPet]
+}
+
+@Entity
+class CBPet {
+ String name
+ CBOwner owner
+}
+
+@Entity
+class CBFace {
+ CBNose nose
+}
+
+@Entity
+class CBNose {
+ CBFace face
+}
+
+@Entity
+class CBCircular {
+ CBCircular parent
+}
+
+@Entity
+class CBNullableEntity {
+ String nullableProp
+ static constraints = {
+ nullableProp nullable: true
+ }
+}
+
+@Entity
+class CBUniqueEntity {
+ String uniqueProp
+ String notUniqueProp
+ static mapping = {
+ uniqueProp unique: true
+ notUniqueProp unique: false
+ }
+}
+
+@Entity
+class CBBaseNonTph {
+ static mapping = {
+ tablePerHierarchy false
+ }
+}
+
+@Entity
+class CBSubNonTph extends CBBaseNonTph {
+ String subProp
+ static constraints = {
+ subProp nullable: false
+ }
+}
+
+@Entity
+class CBByteArrayEntity {
+ byte[] data
+}
+
+@Entity
+class CBUniqueGroupEntity {
+ String groupedProp
+ static mapping = {
+ groupedProp unique: 'group1'
+ }
+}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ColumnBinderSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ColumnBinderSpec.groovy
deleted file mode 100644
index 7c4a51cf48..0000000000
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ColumnBinderSpec.groovy
+++ /dev/null
@@ -1,626 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding
-
-import grails.gorm.annotation.Entity
-import grails.gorm.tests.HibernateGormDatastoreSpec
-import org.grails.orm.hibernate.cfg.ColumnConfig
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty
-import org.hibernate.mapping.Column
-import org.hibernate.mapping.Table
-
-import org.grails.orm.hibernate.cfg.domainbinding.binder.ColumnBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.IndexBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.NumericColumnConstraintsBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.StringColumnConstraintsBinder
-import org.grails.orm.hibernate.cfg.domainbinding.util.ColumnNameForPropertyAndPathFetcher
-import org.grails.orm.hibernate.cfg.domainbinding.util.CreateKeyForProps
-
-class ColumnBinderSpec extends HibernateGormDatastoreSpec {
-
- def "association ManyToMany without userType uses fetched name and is not nullable"() {
- given:
- def columnNameFetcher = Mock(ColumnNameForPropertyAndPathFetcher)
- def stringBinder = Mock(StringColumnConstraintsBinder)
- def numericBinder = Mock(NumericColumnConstraintsBinder)
- def keyCreator = Mock(CreateKeyForProps)
- def indexBinder = Mock(IndexBinder)
-
- def binder = new ColumnBinder(
- columnNameFetcher,
- stringBinder,
- numericBinder,
- keyCreator,
- indexBinder
- )
-
- def entity = createPersistentEntity(CBBook)
- def prop = entity.getPropertyByName("authors")
- def column = new Column()
- def table = new Table()
-
- // stubs
- columnNameFetcher.getColumnNameForPropertyAndPath(prop, null, null) >> "mtm_fk"
-
- when:
- binder.bindColumn(prop, null, column, null, null, table, null)
-
- then:
- column.getName() == "mtm_fk"
- column.isNullable() == true
- 1 * keyCreator.createKeyForProps(prop, null, table, "mtm_fk")
- 1 * indexBinder.bindIndex("mtm_fk", column, null, table)
- }
-
- def "numeric non-association property applies config, numeric constraints, unique and subclass TPH nullable"() {
- given:
- def columnNameFetcher = Mock(ColumnNameForPropertyAndPathFetcher)
- def stringBinder = Mock(StringColumnConstraintsBinder)
- def numericBinder = Mock(NumericColumnConstraintsBinder)
- def keyCreator = Mock(CreateKeyForProps)
- def indexBinder = Mock(IndexBinder)
-
- def binder = new ColumnBinder(
- columnNameFetcher,
- stringBinder,
- numericBinder,
- keyCreator,
- indexBinder
- )
-
- def entity = createPersistentEntity(CBNumericSub)
- def prop = entity.getPropertyByName("num")
- def parentProp = Mock(HibernatePersistentProperty)
- def column = new Column("test")
- def table = new Table()
- def cc = new ColumnConfig(comment: "cmt", defaultValue: "def", read: "r", write: "w")
-
- // stubs
- columnNameFetcher.getColumnNameForPropertyAndPath(prop, "p", cc) >> "num_col"
- parentProp.isNullable() >> true // should make column initially nullable
-
- when:
- binder.bindColumn(prop, parentProp, column, cc, "p", table, null)
-
- then:
- column.getName() == "num_col"
- column.isNullable() == true // due to subclass TPH logic
- column.getComment() == "cmt"
- column.getDefaultValue() == "def"
- column.getCustomRead() == "r"
- column.getCustomWrite() == "w"
-
- 1 * numericBinder.bindNumericColumnConstraints(column, cc, _, Integer)
- 1 * keyCreator.createKeyForProps(prop, "p", table, "num_col")
- 1 * indexBinder.bindIndex("num_col", column, cc, table)
- }
-
- def "one-to-one inverse non-owning with hasOne keeps existing name and sets nullable=false"() {
- given:
- def columnNameFetcher = Mock(ColumnNameForPropertyAndPathFetcher)
- def stringBinder = Mock(StringColumnConstraintsBinder)
- def numericBinder = Mock(NumericColumnConstraintsBinder)
- def keyCreator = Mock(CreateKeyForProps)
- def indexBinder = Mock(IndexBinder)
-
- def binder = new ColumnBinder(
- columnNameFetcher,
- stringBinder,
- numericBinder,
- keyCreator,
- indexBinder
- )
-
- createPersistentEntity(CBOwner)
- def entity = createPersistentEntity(CBPet)
- def prop = entity.getPropertyByName("owner")
- def column = new Column("pre_existing")
- def table = new Table()
-
- // stubs
- columnNameFetcher.getColumnNameForPropertyAndPath(prop, null, null) >> "fetched_col"
-
- when:
- binder.bindColumn(prop, null, column, null, null, table, null)
-
- then:
- column.getName() == "pre_existing" // should not overwrite existing name
- column.isNullable() == false
- 1 * keyCreator.createKeyForProps(prop, null, table, "fetched_col")
- 1 * indexBinder.bindIndex("fetched_col", column, null, table)
- }
-
- def "string property triggers string constraints binder only"() {
- given:
- def columnNameFetcher = Mock(ColumnNameForPropertyAndPathFetcher)
- def stringBinder = Mock(StringColumnConstraintsBinder)
- def numericBinder = Mock(NumericColumnConstraintsBinder)
- def keyCreator = Mock(CreateKeyForProps)
- def indexBinder = Mock(IndexBinder)
-
- def binder = new ColumnBinder(
- columnNameFetcher,
- stringBinder,
- numericBinder,
- keyCreator,
- indexBinder
- )
-
- def entity = createPersistentEntity(CBBook)
- def prop = entity.getPropertyByName("title")
- def column = new Column("test")
- def table = new Table()
-
- columnNameFetcher.getColumnNameForPropertyAndPath(prop, null, null) >> "str_col"
-
- when:
- binder.bindColumn(prop, null, column, null, null, table, "text")
-
- then:
- column.getName() == "str_col"
- column.isNullable() == false
- 1 * stringBinder.bindStringColumnConstraints(column, _, "text")
- 1 * keyCreator.createKeyForProps(prop, null, table, "str_col")
- 1 * indexBinder.bindIndex("str_col", column, null, table)
- }
-
- def "one-to-one inverse non-owning without hasOne sets nullable=true"() {
- given:
- def columnNameFetcher = Mock(ColumnNameForPropertyAndPathFetcher)
- def stringBinder = Mock(StringColumnConstraintsBinder)
- def numericBinder = Mock(NumericColumnConstraintsBinder)
- def keyCreator = Mock(CreateKeyForProps)
- def indexBinder = Mock(IndexBinder)
-
- def binder = new ColumnBinder(
- columnNameFetcher,
- stringBinder,
- numericBinder,
- keyCreator,
- indexBinder
- )
-
- createPersistentEntity(CBFace)
- def entity = createPersistentEntity(CBNose)
- def prop = entity.getPropertyByName("face")
- def column = new Column()
- def table = new Table()
-
- columnNameFetcher.getColumnNameForPropertyAndPath(prop, null, null) >> "one_to_one_fk"
-
- when:
- binder.bindColumn(prop, null, column, null, null, table, null)
-
- then:
- column.getName() == "one_to_one_fk"
- column.isNullable() == true
- 1 * keyCreator.createKeyForProps(prop, null, table, "one_to_one_fk")
- 1 * indexBinder.bindIndex("one_to_one_fk", column, null, table)
- }
-
- def "to-one circular association sets nullable=true"() {
- given:
- def columnNameFetcher = Mock(ColumnNameForPropertyAndPathFetcher)
- def stringBinder = Mock(StringColumnConstraintsBinder)
- def numericBinder = Mock(NumericColumnConstraintsBinder)
- def keyCreator = Mock(CreateKeyForProps)
- def indexBinder = Mock(IndexBinder)
-
- def binder = new ColumnBinder(
- columnNameFetcher,
- stringBinder,
- numericBinder,
- keyCreator,
- indexBinder
- )
-
- def entity = createPersistentEntity(CBCircular)
- def prop = entity.getPropertyByName("parent")
- def column = new Column()
- def table = new Table()
-
- columnNameFetcher.getColumnNameForPropertyAndPath(prop, null, null) >> "to_one_fk"
-
- when:
- binder.bindColumn(prop, null, column, null, null, table, null)
-
- then:
- column.getName() == "to_one_fk"
- column.isNullable() == true
- 1 * keyCreator.createKeyForProps(prop, null, table, "to_one_fk")
- 1 * indexBinder.bindIndex("to_one_fk", column, null, table)
- }
-
- def "association default nullable falls back to property.isNullable()"() {
- given:
- def columnNameFetcher = Mock(ColumnNameForPropertyAndPathFetcher)
- def stringBinder = Mock(StringColumnConstraintsBinder)
- def numericBinder = Mock(NumericColumnConstraintsBinder)
- def keyCreator = Mock(CreateKeyForProps)
- def indexBinder = Mock(IndexBinder)
-
- def binder = new ColumnBinder(
- columnNameFetcher,
- stringBinder,
- numericBinder,
- keyCreator,
- indexBinder
- )
-
- def entity = createPersistentEntity(CBBook)
- def prop = entity.getPropertyByName("authors")
- def column = new Column()
- def table = new Table()
-
- columnNameFetcher.getColumnNameForPropertyAndPath(prop, null, null) >> "assoc_fk"
-
- when:
- binder.bindColumn(prop, null, column, null, null, table, null)
-
- then:
- column.getName() == "assoc_fk"
- column.isNullable() == true
- 1 * keyCreator.createKeyForProps(prop, null, table, "assoc_fk")
- 1 * indexBinder.bindIndex("assoc_fk", column, null, table)
- }
-
- def "non-association nullable computed as property OR parent (prop=true, parent=false)"() {
- given:
- def columnNameFetcher = Mock(ColumnNameForPropertyAndPathFetcher)
- def stringBinder = Mock(StringColumnConstraintsBinder)
- def numericBinder = Mock(NumericColumnConstraintsBinder)
- def keyCreator = Mock(CreateKeyForProps)
- def indexBinder = Mock(IndexBinder)
-
- def binder = new ColumnBinder(
- columnNameFetcher,
- stringBinder,
- numericBinder,
- keyCreator,
- indexBinder
- )
-
- def entity = createPersistentEntity(CBNullableEntity)
- def prop = entity.getPropertyByName("nullableProp")
- def parentProp = Mock(HibernatePersistentProperty)
- def column = new Column("test")
- def table = new Table()
-
- columnNameFetcher.getColumnNameForPropertyAndPath(prop, null, null) >> "na_col"
- parentProp.isNullable() >> false
-
- when:
- binder.bindColumn(prop, parentProp, column, null, null, table, null)
-
- then:
- column.getName() == "na_col"
- column.isNullable() == true
- 1 * keyCreator.createKeyForProps(prop, null, table, "na_col")
- 1 * indexBinder.bindIndex("na_col", column, null, table)
- }
-
- def "non-association nullable computed as property OR parent (prop=false, parent=true)"() {
- given:
- def columnNameFetcher = Mock(ColumnNameForPropertyAndPathFetcher)
- def stringBinder = Mock(StringColumnConstraintsBinder)
- def numericBinder = Mock(NumericColumnConstraintsBinder)
- def keyCreator = Mock(CreateKeyForProps)
- def indexBinder = Mock(IndexBinder)
-
- def binder = new ColumnBinder(
- columnNameFetcher,
- stringBinder,
- numericBinder,
- keyCreator,
- indexBinder
- )
-
- def entity = createPersistentEntity(CBBook)
- def prop = entity.getPropertyByName("title")
- def parentProp = Mock(HibernatePersistentProperty)
- def column = new Column("test")
- def table = new Table()
-
- columnNameFetcher.getColumnNameForPropertyAndPath(prop, null, null) >> "na_col2"
- parentProp.isNullable() >> true
-
- when:
- binder.bindColumn(prop, parentProp, column, null, null, table, null)
-
- then:
- column.getName() == "na_col2"
- column.isNullable() == true
- 1 * keyCreator.createKeyForProps(prop, null, table, "na_col2")
- 1 * indexBinder.bindIndex("na_col2", column, null, table)
- }
-
- def "non-association nullable computed as property OR parent (both false)"() {
- given:
- def columnNameFetcher = Mock(ColumnNameForPropertyAndPathFetcher)
- def stringBinder = Mock(StringColumnConstraintsBinder)
- def numericBinder = Mock(NumericColumnConstraintsBinder)
- def keyCreator = Mock(CreateKeyForProps)
- def indexBinder = Mock(IndexBinder)
-
- def binder = new ColumnBinder(
- columnNameFetcher,
- stringBinder,
- numericBinder,
- keyCreator,
- indexBinder
- )
-
- def entity = createPersistentEntity(CBBook)
- def prop = entity.getPropertyByName("title")
- def parentProp = Mock(HibernatePersistentProperty)
- def column = new Column("test")
- def table = new Table()
-
- columnNameFetcher.getColumnNameForPropertyAndPath(prop, null, null) >> "na_col3"
- parentProp.isNullable() >> false
-
- when:
- binder.bindColumn(prop, parentProp, column, null, null, table, null)
-
- then:
- column.getName() == "na_col3"
- column.isNullable() == false
- 1 * keyCreator.createKeyForProps(prop, null, table, "na_col3")
- 1 * indexBinder.bindIndex("na_col3", column, null, table)
- }
-
- def "uniqueness handling scenarios"() {
- given:
- def columnNameFetcher = Mock(ColumnNameForPropertyAndPathFetcher)
- def stringBinder = Mock(StringColumnConstraintsBinder)
- def numericBinder = Mock(NumericColumnConstraintsBinder)
- def keyCreator = Mock(CreateKeyForProps)
- def indexBinder = Mock(IndexBinder)
-
- def binder = new ColumnBinder(
- columnNameFetcher,
- stringBinder,
- numericBinder,
- keyCreator,
- indexBinder
- )
-
- def entity = createPersistentEntity(CBUniqueEntity)
- def column = new Column("test")
- def table = new Table()
-
- def propUnique = entity.getPropertyByName("uniqueProp")
- columnNameFetcher.getColumnNameForPropertyAndPath(propUnique, null, null) >> "u_col"
-
- def propNotUnique = entity.getPropertyByName("notUniqueProp")
- columnNameFetcher.getColumnNameForPropertyAndPath(propNotUnique, null, null) >> "nu_col"
-
- when:
- binder.bindColumn(propUnique, null, column, null, null, table, null)
-
- then:
- column.isUnique()
-
- when:
- def column2 = new Column("test2")
- binder.bindColumn(propNotUnique, null, column2, null, null, table, null)
-
- then:
- !column2.isUnique()
- }
-
- def "owner not root with tablePerHierarchy=false sets nullable to property.isNullable()"() {
- given:
- def columnNameFetcher = Mock(ColumnNameForPropertyAndPathFetcher)
- def stringBinder = Mock(StringColumnConstraintsBinder)
- def numericBinder = Mock(NumericColumnConstraintsBinder)
- def keyCreator = Mock(CreateKeyForProps)
- def indexBinder = Mock(IndexBinder)
-
- def binder = new ColumnBinder(
- columnNameFetcher,
- stringBinder,
- numericBinder,
- keyCreator,
- indexBinder
- )
-
- def entity = createPersistentEntity(CBSubNonTph)
- def prop = entity.getPropertyByName("subProp")
- def column = new Column("test")
- def table = new Table()
-
- columnNameFetcher.getColumnNameForPropertyAndPath(prop, null, null) >> "sub_col"
-
- when:
- binder.bindColumn(prop, null, column, null, null, table, null)
-
- then:
- column.getName() == "sub_col"
- !column.isNullable()
- 1 * keyCreator.createKeyForProps(prop, null, table, "sub_col")
- 1 * indexBinder.bindIndex("sub_col", column, null, table)
- }
-
- def "byte array property triggers string constraints binder"() {
- given:
- def columnNameFetcher = Mock(ColumnNameForPropertyAndPathFetcher)
- def stringBinder = Mock(StringColumnConstraintsBinder)
- def numericBinder = Mock(NumericColumnConstraintsBinder)
- def keyCreator = Mock(CreateKeyForProps)
- def indexBinder = Mock(IndexBinder)
-
- def binder = new ColumnBinder(
- columnNameFetcher,
- stringBinder,
- numericBinder,
- keyCreator,
- indexBinder
- )
-
- def entity = createPersistentEntity(CBByteArrayEntity)
- def prop = entity.getPropertyByName("data")
- def column = new Column("test")
- def table = new Table()
-
- columnNameFetcher.getColumnNameForPropertyAndPath(prop, null, null) >> "data_col"
-
- when:
- binder.bindColumn(prop, null, column, null, null, table, null)
-
- then:
- 1 * stringBinder.bindStringColumnConstraints(column, _, null)
- }
-
- def "uniqueness is false when uniqueWithinGroup is true"() {
- given:
- def columnNameFetcher = Mock(ColumnNameForPropertyAndPathFetcher)
- def stringBinder = Mock(StringColumnConstraintsBinder)
- def numericBinder = Mock(NumericColumnConstraintsBinder)
- def keyCreator = Mock(CreateKeyForProps)
- def indexBinder = Mock(IndexBinder)
-
- def binder = new ColumnBinder(
- columnNameFetcher,
- stringBinder,
- numericBinder,
- keyCreator,
- indexBinder
- )
-
- def entity = createPersistentEntity(CBUniqueGroupEntity)
- def prop = entity.getPropertyByName("groupedProp")
- def column = new Column("test")
- def table = new Table()
-
- columnNameFetcher.getColumnNameForPropertyAndPath(prop, null, null) >> "g_col"
-
- when:
- binder.bindColumn(prop, null, column, null, null, table, null)
-
- then:
- !column.isUnique()
- }
-}
-
-@Entity
-class CBBook {
- String title
- static hasMany = [authors: CBAuthor]
- static mapping = {
- authors joinTable: [name: "cb_book_authors", key: "book_id", column: "author_id"]
- }
- static constraints = {
- title nullable: false
- authors nullable: true
- }
-}
-
-@Entity
-class CBAuthor {
- String name
- static constraints = {
- name nullable: false
- }
-}
-
-@Entity
-class CBNumericBase {
-}
-
-@Entity
-class CBNumericSub extends CBNumericBase {
- Integer num
- static constraints = {
- num nullable: false
- }
-}
-
-@Entity
-class CBOwner {
- static hasOne = [pet: CBPet]
-}
-
-@Entity
-class CBPet {
- String name
- CBOwner owner
-}
-
-@Entity
-class CBFace {
- CBNose nose
-}
-
-@Entity
-class CBNose {
- CBFace face
-}
-
-@Entity
-class CBCircular {
- CBCircular parent
-}
-
-@Entity
-class CBNullableEntity {
- String nullableProp
- static constraints = {
- nullableProp nullable: true
- }
-}
-
-@Entity
-class CBUniqueEntity {
- String uniqueProp
- String notUniqueProp
- static mapping = {
- uniqueProp unique: true
- notUniqueProp unique: false
- }
-}
-
-@Entity
-class CBBaseNonTph {
- static mapping = {
- tablePerHierarchy false
- }
-}
-
-@Entity
-class CBSubNonTph extends CBBaseNonTph {
- String subProp
- static constraints = {
- subProp nullable: false
- }
-}
-
-@Entity
-class CBByteArrayEntity {
- byte[] data
-}
-
-@Entity
-class CBUniqueGroupEntity {
- String groupedProp
- static mapping = {
- groupedProp unique: 'group1'
- }
-}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ColumnConfigToColumnBinderSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ColumnConfigToColumnBinderSpec.groovy
index 2e5a098729..02547e0c5d 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ColumnConfigToColumnBinderSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ColumnConfigToColumnBinderSpec.groovy
@@ -24,7 +24,7 @@ import org.grails.orm.hibernate.cfg.PropertyConfig
import org.hibernate.mapping.Column
import spock.lang.Specification
-import org.grails.orm.hibernate.cfg.domainbinding.binder.ColumnConfigToColumnBinder
+import org.grails.orm.hibernate.cfg.domainbinding.column.ColumnConfigToColumnBinder
class ColumnConfigToColumnBinderSpec extends Specification {
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ComponentBinderSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ComponentBinderSpec.groovy
deleted file mode 100644
index 79bbdd28e3..0000000000
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ComponentBinderSpec.groovy
+++ /dev/null
@@ -1,217 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding
-
-import grails.gorm.tests.HibernateGormDatastoreSpec
-import org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsPropertyBinder
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity
-import org.grails.orm.hibernate.cfg.MappingCacheHolder
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateEmbeddedCollectionProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateEmbeddedProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateSimpleProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateIdentityProperty
-import org.grails.orm.hibernate.cfg.domainbinding.binder.ComponentBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.ComponentUpdater
-import org.hibernate.mapping.BasicValue
-import org.hibernate.mapping.Component
-import org.hibernate.mapping.PersistentClass
-import org.hibernate.mapping.RootClass
-import org.hibernate.mapping.Table
-import org.hibernate.mapping.Value
-import spock.lang.Subject
-
-class ComponentBinderSpec extends HibernateGormDatastoreSpec {
-
- // Mock Collaborators
- MappingCacheHolder mappingCacheHolder = Mock(MappingCacheHolder)
- ComponentUpdater componentUpdater = Mock(ComponentUpdater)
- GrailsPropertyBinder grailsPropertyBinder = Mock(GrailsPropertyBinder)
-
- @Subject
- ComponentBinder binder
-
- def setup() {
- def metadataBuildingContext = getGrailsDomainBinder().getMetadataBuildingContext()
- binder = new ComponentBinder(metadataBuildingContext, mappingCacheHolder, componentUpdater)
- binder.setGrailsPropertyBinder(grailsPropertyBinder)
- }
-
- def "should bind component and its properties"() {
- given:
- def metadataBuildingContext = getGrailsDomainBinder().getMetadataBuildingContext()
- def root = new RootClass(metadataBuildingContext)
- root.setEntityName("MyEntity")
- root.setTable(new Table("my_entity"))
-
- def associatedEntity = GroovyMock(GrailsHibernatePersistentEntity)
- def embeddedProp = mockEmbeddedProperty(associatedEntity, "address", Address, root)
-
- // Ensure the associated entity also knows its class for initialization logic
- associatedEntity.getPersistentClass() >> root
-
- def prop1 = Mock(HibernateSimpleProperty)
- prop1.getName() >> "street"
- prop1.getType() >> String
-
- associatedEntity.getHibernateParentProperty(MyEntity) >> Optional.empty()
- associatedEntity.getHibernatePersistentProperties(MyEntity) >> [prop1]
-
- when:
- def component = binder.bindComponent(embeddedProp, "")
-
- then:
- component.getComponentClassName() == Address.name
- component.getRoleName() == Address.name + ".address"
- 1 * mappingCacheHolder.cacheMapping(associatedEntity)
- 1 * grailsPropertyBinder.bindProperty(prop1, embeddedProp, "address") >> new BasicValue(metadataBuildingContext, root.getTable())
- 1 * componentUpdater.updateComponent(_ as Component, embeddedProp, prop1, _ as Value)
- }
-
- def "should skip identity properties during binding"() {
- given:
- def metadataBuildingContext = getGrailsDomainBinder().getMetadataBuildingContext()
- def root = new RootClass(metadataBuildingContext)
- root.setTable(new Table("my_entity"))
-
- def associatedEntity = GroovyMock(GrailsHibernatePersistentEntity)
- def embeddedProp = mockEmbeddedProperty(associatedEntity, "address", Address, root)
-
- associatedEntity.getPersistentClass() >> root
-
- // HibernatePersistentProperty includes ID properties; usually filtered by the loop logic
- def idProp = Mock(HibernateIdentityProperty)
- idProp.getName() >> "id"
-
- def normalProp = Mock(HibernateSimpleProperty)
- normalProp.getName() >> "street"
- normalProp.getType() >> String
-
- associatedEntity.getHibernateParentProperty(MyEntity) >> Optional.empty()
- associatedEntity.getHibernatePersistentProperties(MyEntity) >> [normalProp]
-
- when:
- binder.bindComponent(embeddedProp, "")
-
- then:
- // Logic check: if idProp is not in the list returned by getHibernatePersistentProperties, it's skipped
- 0 * componentUpdater.updateComponent(_, _, idProp, _)
- 1 * componentUpdater.updateComponent(_, _, normalProp, _)
- }
-
- def "should set parent property when component has reference back to owner"() {
- given:
- def metadataBuildingContext = getGrailsDomainBinder().getMetadataBuildingContext()
- def root = new RootClass(metadataBuildingContext)
- root.setTable(new Table("my_entity"))
-
- def associatedEntity = GroovyMock(GrailsHibernatePersistentEntity)
- def embeddedProp = mockEmbeddedProperty(associatedEntity, "address", Address, root)
-
- associatedEntity.getPersistentClass() >> root
-
- def parentProp = Mock(HibernateSimpleProperty)
- parentProp.getName() >> "myEntity"
-
- associatedEntity.getHibernateParentProperty(MyEntity) >> Optional.of(parentProp)
- associatedEntity.getHibernatePersistentProperties(MyEntity) >> []
-
- when:
- def component = binder.bindComponent(embeddedProp, "")
-
- then:
- component.getParentProperty() == "myEntity"
- }
-
- /**
- * Helper to reduce boilerplate.
- * The 'root' (PersistentClass) is required by the Component constructor to avoid NPE.
- */
- private HibernateEmbeddedProperty mockEmbeddedProperty(
- GrailsHibernatePersistentEntity associatedEntity,
- String name,
- Class type,
- PersistentClass root) {
-
- def embeddedProp = Mock(HibernateEmbeddedProperty)
- embeddedProp.getName() >> name
- embeddedProp.getType() >> type
- embeddedProp.getAssociatedEntity() >> associatedEntity
- embeddedProp.getPersistentClass() >> root // CRITICAL FIX
-
- embeddedProp.getOwner() >> Mock(GrailsHibernatePersistentEntity) {
- getJavaClass() >> MyEntity
- }
- return embeddedProp
- }
-
- private HibernateEmbeddedCollectionProperty mockEmbeddedCollectionProperty(
- GrailsHibernatePersistentEntity associatedEntity,
- String name,
- Class type,
- org.hibernate.mapping.Collection collection) {
-
- def prop = Mock(HibernateEmbeddedCollectionProperty)
- prop.getName() >> name
- prop.getType() >> type
- prop.getComponentType() >> type
- prop.getAssociatedEntity() >> associatedEntity
- prop.getCollection() >> collection
- prop.getOwner() >> Mock(GrailsHibernatePersistentEntity) {
- getJavaClass() >> MyEntity
- }
- return prop
- }
-
- def "bindEmbeddedCollectionComponent creates a Component element for the collection"() {
- given:
- def mbc = getGrailsDomainBinder().getMetadataBuildingContext()
- def ownerClass = new RootClass(mbc)
- ownerClass.setEntityName(MyEntity.name)
- ownerClass.setTable(new Table("my_entity"))
- def bag = new org.hibernate.mapping.Bag(mbc, ownerClass)
- bag.setCollectionTable(new Table("my_entity_dim"))
-
- def associatedEntity = GroovyMock(GrailsHibernatePersistentEntity)
- associatedEntity.getPersistentClass() >> ownerClass
-
- def widthProp = Mock(HibernateSimpleProperty)
- widthProp.getName() >> "width"
- widthProp.getType() >> int
- widthProp.getMappedForm() >> Mock(org.grails.orm.hibernate.cfg.PropertyConfig)
- widthProp.getType() >> int
-
- associatedEntity.getHibernatePersistentProperties(MyEntity) >> [widthProp]
-
- grailsPropertyBinder.bindProperty(widthProp, null, "dimensions") >> Mock(BasicValue)
-
- def prop = mockEmbeddedCollectionProperty(associatedEntity, "dimensions", Dimension, bag)
-
- when:
- def component = binder.bindEmbeddedCollectionComponent(prop)
-
- then:
- component != null
- component.componentClassName == Dimension.name
- 1 * mappingCacheHolder.cacheMapping(associatedEntity)
- }
-
- static class MyEntity {}
- static class Address {}
- static class Dimension { int width }
-}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CompositeIdBinderSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CompositeIdBinderSpec.groovy
deleted file mode 100644
index 215c1988dc..0000000000
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CompositeIdBinderSpec.groovy
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding
-
-import grails.gorm.tests.HibernateGormDatastoreSpec
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateCompositeIdentityProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateIdentityProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentEntity
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty
-import org.hibernate.mapping.Component
-import org.hibernate.mapping.RootClass
-import org.hibernate.mapping.Table
-import org.hibernate.mapping.Value
-import spock.lang.Subject
-import org.grails.orm.hibernate.cfg.domainbinding.binder.CompositeIdBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.ComponentUpdater
-import org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsPropertyBinder
-
-class CompositeIdBinderSpec extends HibernateGormDatastoreSpec {
-
- def componentUpdater = Mock(ComponentUpdater)
- def grailsPropertyBinder = Mock(GrailsPropertyBinder)
-
- @Subject
- CompositeIdBinder binder
-
- def setup() {
- binder = new CompositeIdBinder(
- getGrailsDomainBinder().getMetadataBuildingContext(),
- componentUpdater,
- grailsPropertyBinder
- )
- }
-
- def "should bind composite id using parts from HibernateCompositeIdentityProperty"() {
- given:
- def metadataBuildingContext = getGrailsDomainBinder().getMetadataBuildingContext()
- def rootClass = new RootClass(metadataBuildingContext)
- rootClass.setEntityName("MyEntity")
- rootClass.setTable(new Table("my_entity"))
-
- def prop1 = Mock(HibernatePersistentProperty)
- def prop2 = Mock(HibernatePersistentProperty)
- def compositeIdentityProperty = Mock(HibernateCompositeIdentityProperty) {
- getParts() >> ([prop1, prop2] as HibernatePersistentProperty[])
- }
- def domainClass = Mock(HibernatePersistentEntity) {
- getName() >> "MyEntity"
- getRootClass() >> rootClass
- getIdentityProperty() >> compositeIdentityProperty
- }
-
- when:
- binder.bindCompositeId(domainClass)
-
- then:
- rootClass.getIdentifier() instanceof Component
- rootClass.hasEmbeddedIdentifier()
- 2 * grailsPropertyBinder.bindProperty(_ as HibernatePersistentProperty, null, "") >> Mock(Value)
- 2 * componentUpdater.updateComponent(_ as Component, null, _ as HibernatePersistentProperty, _ as Value)
- }
-
- def "should throw MappingException when entity does not have composite identity"() {
- given:
- def metadataBuildingContext = getGrailsDomainBinder().getMetadataBuildingContext()
- def rootClass = new RootClass(metadataBuildingContext)
- rootClass.setEntityName("MyEntity")
- def domainClass = Mock(HibernatePersistentEntity) {
- getName() >> "MyEntity"
- getRootClass() >> rootClass
- getIdentityProperty() >> Mock(HibernateIdentityProperty)
- }
-
- when:
- binder.bindCompositeId(domainClass)
-
- then:
- thrown(org.hibernate.MappingException)
- }
-}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CompositeIdentifierToManyToOneBinderSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CompositeIdentifierToManyToOneBinderSpec.groovy
deleted file mode 100644
index 8fefa23fe1..0000000000
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CompositeIdentifierToManyToOneBinderSpec.groovy
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding
-
-
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToOneProperty
-import org.grails.orm.hibernate.cfg.ColumnConfig
-import org.grails.orm.hibernate.cfg.HibernateCompositeIdentity
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty
-import org.grails.orm.hibernate.cfg.PersistentEntityNamingStrategy
-import org.grails.orm.hibernate.cfg.PropertyConfig
-import org.hibernate.mapping.Column
-import org.hibernate.mapping.KeyValue
-import org.hibernate.mapping.RootClass
-import org.hibernate.mapping.SimpleValue
-import spock.lang.Specification
-
-import org.grails.orm.hibernate.cfg.domainbinding.binder.CompositeIdentifierToManyToOneBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.SimpleValueBinder
-import org.grails.orm.hibernate.cfg.domainbinding.util.BackticksRemover
-import org.grails.orm.hibernate.cfg.domainbinding.util.DefaultColumnNameFetcher
-import org.grails.orm.hibernate.cfg.domainbinding.util.ForeignKeyColumnCountCalculator
-
-class CompositeIdentifierToManyToOneBinderSpec extends Specification {
-
- def "Test bindCompositeIdentifierToManyToOne with nested composite ID"() {
- given:
- // 1. Stub all dependencies for the protected constructor
- def calculator = Stub(ForeignKeyColumnCountCalculator)
- def namingStrategy = Stub(PersistentEntityNamingStrategy)
- def columnNameFetcher = Stub(DefaultColumnNameFetcher)
- def backticksRemover = Stub(BackticksRemover)
- def simpleValueBinder = Mock(SimpleValueBinder) // Use Mock to verify interaction
- def metadataBuildingContext = Mock(org.hibernate.boot.spi.MetadataBuildingContext)
-
- // Instantiate the binder with stubs
- def binder = new CompositeIdentifierToManyToOneBinder(calculator, namingStrategy, columnNameFetcher, backticksRemover, simpleValueBinder)
-
- // 2. Set up stubs for the method arguments
- def association = Mock(HibernatePersistentProperty)
- def value = Mock(SimpleValue)
- def refDomainClass = Mock(GrailsHibernatePersistentEntity)
- def persistentClass = new RootClass(metadataBuildingContext)
- def identifier = Mock(KeyValue)
- def path = "/test"
-
- // Use a real CompositeIdentity object to avoid final method mocking issues
- def propertyNames = ["nestedEntity"] as String[]
- def compositeId = new HibernateCompositeIdentity()
- compositeId.setPropertyNames(propertyNames)
-
- // 3. Define the nested composite key scenario
- def propertyConfig = new PropertyConfig()
- association.getMappedForm() >> propertyConfig
- association.getHibernateMappedForm() >> propertyConfig
-
- calculator.calculateForeignKeyColumnCount(refDomainClass, propertyNames) >> 2
-
- def nestedEntityProp = Mock(HibernateToOneProperty)
- refDomainClass.getHibernatePropertyByName("nestedEntity") >> nestedEntityProp
- nestedEntityProp.name >> "nestedEntity"
-
- def nestedAssociatedEntity = Mock(GrailsHibernatePersistentEntity)
- nestedEntityProp.getHibernateAssociatedEntity() >> nestedAssociatedEntity
-
- def nestedPartA = Mock(HibernatePersistentProperty)
- def nestedPartB = Mock(HibernatePersistentProperty)
- def perArray = [nestedPartA, nestedPartB] as HibernatePersistentProperty[]
- nestedAssociatedEntity.getCompositeIdentity() >> perArray
-
- // 4. Mock the behavior of the dependency methods
- refDomainClass.getTableName(namingStrategy) >> "ref_table"
- namingStrategy.resolveColumnName("nestedEntity") >> "nested_entity_col"
- columnNameFetcher.getDefaultColumnName(nestedPartA) >> "part_a_col"
- columnNameFetcher.getDefaultColumnName(nestedPartB) >> "part_b_col"
-
- // Make backticks remover pass through the values for simplicity
- backticksRemover.apply(_) >> { String s -> s }
- refDomainClass.getPersistentClass() >> persistentClass
- refDomainClass.getName() >> "RefDomain"
- persistentClass.setIdentifier(identifier)
- identifier.getColumns() >> [new Column("part_a_col"), new Column("part_b_col")]
- value.getColumns() >> [new Column("ref_table_nested_entity_col_part_a_col"), new Column("ref_table_nested_entity_col_part_b_col")]
-
- // sortOrIndexForeignKeyColumns and getReferencedIdentifierColumns are now on the entity mock
- refDomainClass.sortOrIndexForeignKeyColumns(value) >> {}
- refDomainClass.getReferencedIdentifierColumns(propertyNames) >> [new Column("part_a_col"), new Column("part_b_col")]
- value.createForeignKeyOfEntity("RefDomain", _ as List<Column>) >> null
-
- when:
- binder.bindCompositeIdentifierToManyToOne(association as HibernatePersistentProperty, value, compositeId, refDomainClass, path)
-
- then:
- // 5. Verify the final generated column names
- def finalColumns = propertyConfig.getColumns()
- finalColumns.size() == 2
- finalColumns[0].getName() == "ref_table_nested_entity_col_part_a_col"
- finalColumns[1].getName() == "ref_table_nested_entity_col_part_b_col"
-
- and: // 6. Verify the call to the simple value binder
- 1 * simpleValueBinder.bindSimpleValue(_ as HibernatePersistentProperty, null, value, path)
- }
-
- def "Test bindCompositeIdentifierToManyToOne when column count matches"() {
- given:
- // 1. Use Mocks for dependencies that require interaction verification
- def calculator = Stub(ForeignKeyColumnCountCalculator)
- def namingStrategy = Mock(PersistentEntityNamingStrategy)
- def columnNameFetcher = Mock(DefaultColumnNameFetcher)
- def backticksRemover = Mock(BackticksRemover)
- def simpleValueBinder = Mock(SimpleValueBinder)
- def metadataBuildingContext = Mock(org.hibernate.boot.spi.MetadataBuildingContext)
-
- def binder = new CompositeIdentifierToManyToOneBinder(calculator, namingStrategy, columnNameFetcher, backticksRemover, simpleValueBinder)
-
- // 2. Set up arguments
- def association = Mock(HibernatePersistentProperty)
- def value = Mock(SimpleValue)
- def compositeId = new HibernateCompositeIdentity()
- compositeId.setPropertyNames(["prop1", "prop2"] as String[])
- def refDomainClass = Mock(GrailsHibernatePersistentEntity)
- def persistentClass = new RootClass(metadataBuildingContext)
- def identifier = Mock(KeyValue)
- def path = "/test"
-
- // 3. Set up the "match" condition
- def propertyConfig = new PropertyConfig()
- propertyConfig.getColumns().add(new ColumnConfig())
- propertyConfig.getColumns().add(new ColumnConfig())
- association.getMappedForm() >> propertyConfig
- association.getHibernateMappedForm() >> propertyConfig
-
- // The calculated length is the same as the number of columns already in the config
- calculator.calculateForeignKeyColumnCount(refDomainClass, _ as String[]) >> 2
- refDomainClass.getPersistentClass() >> persistentClass
- refDomainClass.getName() >> "RefDomain"
- persistentClass.setIdentifier(identifier)
- identifier.getColumns() >> [new Column("prop1"), new Column("prop2")]
- value.getColumns() >> [new Column("prop1"), new Column("prop2")]
-
- refDomainClass.sortOrIndexForeignKeyColumns(value) >> {}
- refDomainClass.getReferencedIdentifierColumns(_ as String[]) >> [new Column("prop1"), new Column("prop2")]
- value.createForeignKeyOfEntity("RefDomain", _ as List<Column>) >> null
-
- when:
- binder.bindCompositeIdentifierToManyToOne(association as HibernatePersistentProperty, value, compositeId, refDomainClass, path)
-
- then:
- // 4. Verify the column name generation logic is skipped
- 0 * refDomainClass.getTableName(_)
- 0 * namingStrategy._
- 0 * columnNameFetcher._
- 0 * backticksRemover._
-
- and: // 5. Verify the simple value binder is still called
- 1 * simpleValueBinder.bindSimpleValue(_ as HibernatePersistentProperty, null, value, path)
- }
-}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/DefaultColumnNameFetcherSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/DefaultColumnNameFetcherSpec.groovy
index bede05cc81..62f2518a2d 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/DefaultColumnNameFetcherSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/DefaultColumnNameFetcherSpec.groovy
@@ -33,19 +33,19 @@ class DefaultColumnNameFetcherSpec extends HibernateGormDatastoreSpec {
@Unroll
void "Test getDefaultColumnName for #description"() {
given:
- def namingStrategy =grailsDomainBinder.getNamingStrategy()
+ def namingStrategy =mappingContributor.getNamingStrategy()
def backticksRemover = new BackticksRemover()
def fetcher = new DefaultColumnNameFetcher(namingStrategy, backticksRemover)
// Setup related entities that might be needed by the main entity
- createPersistentEntity(AssociatedEntity, grailsDomainBinder)
- createPersistentEntity(SpecBaseEntity, grailsDomainBinder)
- createPersistentEntity(AManyToManyEntity, grailsDomainBinder) // Add the new clean
- createPersistentEntity(BManyToManyEntity, grailsDomainBinder) // A// entity
- createPersistentEntity(DefaultColumnNameFetcherSpecEntity, grailsDomainBinder)
- createPersistentEntity(InheritedEntity, grailsDomainBinder)
-
- def persistentEntity = createPersistentEntity(entityClass, grailsDomainBinder)
+ createPersistentEntity(AssociatedEntity)
+ createPersistentEntity(SpecBaseEntity)
+ createPersistentEntity(AManyToManyEntity) // Add the new clean
+ createPersistentEntity(BManyToManyEntity) // A// entity
+ createPersistentEntity(DefaultColumnNameFetcherSpecEntity)
+ createPersistentEntity(InheritedEntity)
+
+ def persistentEntity = createPersistentEntity(entityClass)
PersistentProperty property = persistentEntity.getPropertyByName(propertyName)
@@ -68,14 +68,14 @@ class DefaultColumnNameFetcherSpec extends HibernateGormDatastoreSpec {
void "single-arg constructor creates its own BackticksRemover"() {
given:
- def namingStrategy = grailsDomainBinder.getNamingStrategy()
+ def namingStrategy = mappingContributor.getNamingStrategy()
def fetcher = new DefaultColumnNameFetcher(namingStrategy)
- createPersistentEntity(AssociatedEntity, grailsDomainBinder)
- createPersistentEntity(SpecBaseEntity, grailsDomainBinder)
- createPersistentEntity(AManyToManyEntity, grailsDomainBinder)
- createPersistentEntity(BManyToManyEntity, grailsDomainBinder)
- createPersistentEntity(DefaultColumnNameFetcherSpecEntity, grailsDomainBinder)
- def persistentEntity = createPersistentEntity(DefaultColumnNameFetcherSpecEntity, grailsDomainBinder)
+ createPersistentEntity(AssociatedEntity)
+ createPersistentEntity(SpecBaseEntity)
+ createPersistentEntity(AManyToManyEntity)
+ createPersistentEntity(BManyToManyEntity)
+ createPersistentEntity(DefaultColumnNameFetcherSpecEntity)
+ def persistentEntity = createPersistentEntity(DefaultColumnNameFetcherSpecEntity)
def property = persistentEntity.getPropertyByName('name')
when:
@@ -86,13 +86,13 @@ class DefaultColumnNameFetcherSpec extends HibernateGormDatastoreSpec {
}
void "getDefaultColumnName for inherited true ManyToOne uses owner root entity prefix (L75-L78)"() {
given:
- def namingStrategy = grailsDomainBinder.getNamingStrategy()
+ def namingStrategy = mappingContributor.getNamingStrategy()
def backticksRemover = new BackticksRemover()
def fetcher = new DefaultColumnNameFetcher(namingStrategy, backticksRemover)
- createPersistentEntity(DCFNOwner, grailsDomainBinder)
- createPersistentEntity(DCFNKid, grailsDomainBinder)
- def entity = createPersistentEntity(DCFNSubKid, grailsDomainBinder)
+ createPersistentEntity(DCFNOwner)
+ createPersistentEntity(DCFNKid)
+ def entity = createPersistentEntity(DCFNSubKid)
def property = entity.getPropertyByName("parent")
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/EnumTypeBinderFixtures.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/EnumTypeBinderFixtures.groovy
new file mode 100644
index 0000000000..8966e49d5d
--- /dev/null
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/EnumTypeBinderFixtures.groovy
@@ -0,0 +1,83 @@
+/*
+ * 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 org.grails.orm.hibernate.cfg.domainbinding
+
+import java.sql.PreparedStatement
+import java.sql.ResultSet
+import java.sql.SQLException
+import org.hibernate.type.descriptor.WrapperOptions
+import org.hibernate.usertype.UserType
+import grails.persistence.Entity
+
+/**
+ * Domain classes of the former {@code EnumTypeBinderSpec}, a unit spec of the classic domain binder of Grails 8: they stay as fixtures of the
+ * differential specs, which compare native binding with the recorded classic schema of every scanned entity.
+ */
+// --- Supporting Classes ---
+
+enum Status01 { AVAILABLE, OUT_OF_STOCK }
+
+@Entity class Person01 {
+ Long id; Status01 status
+ static constraints = { status nullable: false }
+}
+@Entity class Person02 {
+ Long id; Status01 status
+ static mapping = { status enumType: "string" }
+}
+@Entity class Person03 {
+ Long id; Status01 status
+ static mapping = { status enumType: "ordinal" }
+}
+@Entity class Person04 {
+ Long id; Status01 status
+ static mapping = { status enumType: "identity", nullable: false }
+}
+@Entity class Person05 {
+ Long id; Status01 status
+ static mapping = { status type: UserTypeEnumType, nullable: false }
+}
+@Entity class PersonWithCollection {
+ Long id
+ Set<Status01> statuses
+}
+@Entity class PersonWithExplicitColumn {
+ Long id; Status01 status
+ static mapping = { status column: "status_col", index: "idx_status" }
+}
+@Entity class PersonWithColumnExtras {
+ Long id; Status01 status
+ static mapping = {
+ status comment: "the status", defaultValue: "'AVAILABLE'", read: "lower(status)", write: "upper(?)"
+ }
+}
+@Entity class Clown01 extends Person01 { String clownName }
+
+class UserTypeEnumType implements UserType {
+ @Override int getSqlType() { 0 }
+ @Override Class returnedClass() { Status01 }
+ @Override boolean equals(Object x, Object y) { x == y }
+ @Override int hashCode(Object x) { x.hashCode() }
+ @Override Object nullSafeGet(ResultSet rs, int position, WrapperOptions options) throws SQLException { null }
+ @Override void nullSafeSet(PreparedStatement st, Object value, int index, WrapperOptions options) throws SQLException {}
+ @Override Object deepCopy(Object value) { value }
+ @Override boolean isMutable() { false }
+ @Override Serializable disassemble(Object value) { (Serializable)value }
+ @Override Object assemble(Serializable cached, Object owner) { cached }
+}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/EnumTypeBinderSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/EnumTypeBinderSpec.groovy
deleted file mode 100644
index bb30982a1c..0000000000
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/EnumTypeBinderSpec.groovy
+++ /dev/null
@@ -1,266 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding
-
-import java.sql.PreparedStatement
-import java.sql.ResultSet
-import java.sql.SQLException
-
-import jakarta.persistence.EnumType
-
-import org.hibernate.mapping.RootClass
-import org.hibernate.mapping.Table
-import org.hibernate.type.descriptor.WrapperOptions
-import org.hibernate.usertype.UserType
-import spock.lang.Subject
-import spock.lang.Unroll
-
-import grails.gorm.tests.HibernateGormDatastoreSpec
-import grails.persistence.Entity
-import org.grails.datastore.mapping.model.PersistentProperty
-import org.grails.orm.hibernate.cfg.IdentityEnumType
-import org.grails.orm.hibernate.cfg.domainbinding.binder.ColumnConfigToColumnBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.EnumTypeBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsDomainBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.IndexBinder
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateBasicProperty
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateEnumProperty
-import org.grails.orm.hibernate.cfg.domainbinding.util.BackticksRemover
-import org.grails.orm.hibernate.cfg.domainbinding.util.ColumnNameForPropertyAndPathFetcher
-import org.grails.orm.hibernate.cfg.domainbinding.util.DefaultColumnNameFetcher
-
-class EnumTypeBinderSpec extends HibernateGormDatastoreSpec {
-
- def indexBinder = Mock(IndexBinder)
- def columnBinder = Mock(ColumnConfigToColumnBinder)
-
- @Subject
- EnumTypeBinder binder
-
- void setupSpec() {
- manager.registerDomainClasses(PersonWithColumnExtras)
- }
-
- def setup() {
- def grailsDomainBinder = getGrailsDomainBinder()
- def metadataBuildingContext = grailsDomainBinder.getMetadataBuildingContext()
- def namingStrategy = grailsDomainBinder.getNamingStrategy()
- def defaultColumnNameFetcher = new DefaultColumnNameFetcher(namingStrategy, new BackticksRemover())
- def columnNameFetcher = new ColumnNameForPropertyAndPathFetcher(namingStrategy, defaultColumnNameFetcher, new BackticksRemover())
- binder = new EnumTypeBinder(metadataBuildingContext, columnNameFetcher, indexBinder, columnBinder, namingStrategy)
- }
-
- private PersistentProperty setupProperty(Class clazz, String propertyName, Table table) {
- def grailsDomainBinder = getGrailsDomainBinder()
- def owner = createPersistentEntity(clazz, grailsDomainBinder) as GrailsHibernatePersistentEntity
-
- def rootClass = new RootClass(grailsDomainBinder.getMetadataBuildingContext())
- rootClass.setTable(table)
- owner.setPersistentClass(rootClass)
-
- return owner.getPropertyByName(propertyName)
- }
-
- def "should bind enum type for a collection element"() {
- given: "An entity with a collection of enums"
- def table = new Table("person_statuses")
- def property = setupProperty(PersonWithCollection, "statuses", table)
-
- expect: "The property is both a ToMany and an enum property"
- property instanceof HibernateBasicProperty == true
- property instanceof HibernateEnumProperty == true
-
- when: "the enum is bound for the collection column"
- // This will now successfully call property.getComponentType() internally
- def result = binder.bindEnumType(property as HibernateEnumProperty, GrailsDomainBinder.EMPTY_PATH)
-
- then: "The BasicValue is configured correctly"
- result.getEnumerationStyle() == EnumType.STRING
- result.getTypeParameters().getProperty(GrailsDomainBinder.ENUM_CLASS_PROP) == Status01.name
- }
-
- @Unroll
- def "should bind enum type as #expectedHibernateType when mapping specifies enumType as '#enumTypeMapping'"() {
- given: "A root entity and its enum property"
- def table = new Table("person")
- def property = setupProperty(clazz, "status", table)
-
- when: "the enum is bound via the standard path"
- def simpleValue = binder.bindEnumType(property as HibernateEnumProperty, "")
-
- then: "the correct hibernate type is set"
- simpleValue.getTypeName() == expectedHibernateType
- simpleValue.getEnumerationStyle() == expectedEnumStyle
- simpleValue.isNullable() == nullable
-
- where:
- clazz | enumTypeMapping | expectedHibernateType | expectedEnumStyle | nullable
- Person01 | "default" | null | EnumType.STRING | false
- Person02 | "string" | null | EnumType.STRING | true
- Person03 | "ordinal" | null | EnumType.ORDINAL | true
- Person04 | "identity" | IdentityEnumType.class.getName() | null | false
- Person05 | UserTypeEnumType | UserTypeEnumType.class.getName() | null | false
- }
-
- @Unroll
- def "should set column nullability"() {
- given: "A root entity and its enum property"
- def table = new Table("person")
- def property = setupProperty(clazz, "status", table)
-
- when: "the enum is bound"
- def simpleValue = binder.bindEnumType(property as HibernateEnumProperty, "")
-
- then:
- simpleValue.getColumns()[0].isNullable() == nullable
-
- where:
- clazz | nullable
- Person01 | false
- Person02 | true
- Clown01 | true
- }
-
- def "should bind enum type with explicit table"() {
- given: "A root entity and its enum property"
- def table = new Table("explicit_table")
- def property = setupProperty(Person01, "status", new Table("internal"))
-
-
- when: "the enum is bound with an explicit table"
- def simpleValue = binder.bindEnumType(property as HibernateEnumProperty, "myPath")
-
- then: "the provided table is used instead of the property's internal table"
- simpleValue.getTable() == table
- }
-
- def "should bind explicit column for enum"() {
- given:
- def table = new Table("person")
- def property = setupProperty(PersonWithExplicitColumn, "status", table)
-
- when:
- def simpleValue = binder.bindEnumType(property as HibernateEnumProperty, "")
-
- then:
- 1 * columnBinder.bindColumnConfigToColumn(_, _, _)
- 1 * indexBinder.bindIndex("status_col", _, _, _)
- }
-
- def "should apply the comment, default value and read and write expressions of the column config"() {
- given:
- def table = new Table("person")
- def property = setupProperty(PersonWithColumnExtras, "status", table)
-
- when:
- def column = binder.bindEnumType(property as HibernateEnumProperty, "").getColumns()[0] as org.hibernate.mapping.Column
-
- then:
- column.getComment() == "the status"
- column.getDefaultValue() == "'AVAILABLE'"
- column.getCustomRead() == "lower(status)"
- column.getCustomWrite() == "upper(?)"
- }
-
- def "should leave the column extras unset when the enum property has no column config"() {
- given:
- def table = new Table("person")
- def property = setupProperty(Person01, "status", table)
-
- when:
- def column = binder.bindEnumType(property as HibernateEnumProperty, "").getColumns()[0] as org.hibernate.mapping.Column
-
- then:
- column.getComment() == null
- column.getDefaultValue() == null
- column.getCustomRead() == null
- column.getCustomWrite() == null
- }
-
- def "the column extras of an enum property reach the bound column and the schema"() {
- given:
- def column = getPersistentEntity(PersonWithColumnExtras).persistentClass.getProperty("status").columns[0] as org.hibernate.mapping.Column
- def metadata = sessionFactory.currentSession
- .createNativeQuery("select column_default, remarks from information_schema.columns " +
- "where table_name = 'PERSON_WITH_COLUMN_EXTRAS' and column_name = 'STATUS'", Object[])
- .uniqueResult() as Object[]
-
- expect:
- column.getComment() == "the status"
- column.getDefaultValue() == "'AVAILABLE'"
- column.getCustomRead() == "lower(status)"
- column.getCustomWrite() == "upper(?)"
- metadata[0].toString().contains("AVAILABLE")
- metadata[1] == "the status"
- }
-}
-
-// --- Supporting Classes ---
-
-enum Status01 { AVAILABLE, OUT_OF_STOCK }
-
-@Entity class Person01 {
- Long id; Status01 status
- static constraints = { status nullable: false }
-}
-@Entity class Person02 {
- Long id; Status01 status
- static mapping = { status enumType: "string" }
-}
-@Entity class Person03 {
- Long id; Status01 status
- static mapping = { status enumType: "ordinal" }
-}
-@Entity class Person04 {
- Long id; Status01 status
- static mapping = { status enumType: "identity", nullable: false }
-}
-@Entity class Person05 {
- Long id; Status01 status
- static mapping = { status type: UserTypeEnumType, nullable: false }
-}
-@Entity class PersonWithCollection {
- Long id
- Set<Status01> statuses
-}
-@Entity class PersonWithExplicitColumn {
- Long id; Status01 status
- static mapping = { status column: "status_col", index: "idx_status" }
-}
-@Entity class PersonWithColumnExtras {
- Long id; Status01 status
- static mapping = {
- status comment: "the status", defaultValue: "'AVAILABLE'", read: "lower(status)", write: "upper(?)"
- }
-}
-@Entity class Clown01 extends Person01 { String clownName }
-
-class UserTypeEnumType implements UserType {
- @Override int getSqlType() { 0 }
- @Override Class returnedClass() { Status01 }
- @Override boolean equals(Object x, Object y) { x == y }
- @Override int hashCode(Object x) { x.hashCode() }
- @Override Object nullSafeGet(ResultSet rs, int position, WrapperOptions options) throws SQLException { null }
- @Override void nullSafeSet(PreparedStatement st, Object value, int index, WrapperOptions options) throws SQLException {}
- @Override Object deepCopy(Object value) { value }
- @Override boolean isMutable() { false }
- @Override Serializable disassemble(Object value) { (Serializable)value }
- @Override Object assemble(Serializable cached, Object owner) { cached }
-}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ForeignKeyOneToOneBinderSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ForeignKeyOneToOneBinderSpec.groovy
deleted file mode 100644
index 4cf1700327..0000000000
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ForeignKeyOneToOneBinderSpec.groovy
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding
-
-import grails.gorm.tests.HibernateGormDatastoreSpec
-import org.grails.datastore.mapping.model.MappingContext
-import org.grails.datastore.mapping.model.PersistentEntity
-import org.grails.orm.hibernate.cfg.Mapping
-import org.grails.orm.hibernate.cfg.PersistentEntityNamingStrategy
-import org.grails.orm.hibernate.cfg.PropertyConfig
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateOneToOneProperty
-import org.hibernate.MappingException
-import org.hibernate.mapping.Column
-import org.hibernate.mapping.ManyToOne
-import spock.lang.Unroll
-
-import org.grails.orm.hibernate.cfg.domainbinding.binder.CompositeIdentifierToManyToOneBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.ForeignKeyOneToOneBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.ManyToOneBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.ManyToOneValuesBinder
-import org.grails.orm.hibernate.cfg.domainbinding.binder.SimpleValueBinder
-import org.grails.orm.hibernate.cfg.domainbinding.util.SimpleValueColumnFetcher
-
-class ForeignKeyOneToOneBinderSpec extends HibernateGormDatastoreSpec {
-
- @Unroll
- def "bind sets alternate unique key and column uniqueness for #scenario"() {
- given:
- def namingStrategy = Mock(PersistentEntityNamingStrategy)
- def simpleValueBinder = Mock(SimpleValueBinder)
- def manyToOneValuesBinder = Mock(ManyToOneValuesBinder)
- def compositeBinder = Mock(CompositeIdentifierToManyToOneBinder)
- def columnFetcher = Mock(SimpleValueColumnFetcher)
-
- def manyToOneBinder = new ManyToOneBinder(
- getGrailsDomainBinder().getMetadataBuildingContext(),
- namingStrategy, simpleValueBinder, manyToOneValuesBinder, compositeBinder)
- def binder = new ForeignKeyOneToOneBinder(manyToOneBinder, columnFetcher)
-
- def property = Mock(TestFKOneToOne)
- def mapping = new Mapping()
- def refDomainClass = Mock(GrailsHibernatePersistentEntity) {
- getMappedForm() >> mapping
- getHibernateCompositeIdentity() >> Optional.empty()
- }
- def propertyConfig = Mock(PropertyConfig)
- def column = new Column('test')
- def inverseSide = Mock(TestFKOneToOne)
-
- property.getHibernateAssociatedEntity() >> refDomainClass
- mapping.setIdentity(null)
- property.getMappedForm() >> propertyConfig
- property.getHibernateMappedForm() >> propertyConfig
- columnFetcher.getColumnForSimpleValue(_ as ManyToOne) >> column
-
- propertyConfig.isUnique() >> isUnique
- propertyConfig.isUniqueWithinGroup() >> isUniqueWithinGroup
- property.isBidirectional() >> isBidirectional
- property.getHibernateInverseSide() >> inverseSide
- inverseSide.isValidHibernateOneToOne() >> isInverseHasOne
-
- when:
- def result = binder.bind(property, "/test")
-
- then:
- result.isAlternateUniqueKey()
- if (expectedUniqueValue != null) {
- assert column.isUnique() == expectedUniqueValue
- } else {
- assert !column.isUnique()
- }
-
- where:
- scenario | isUnique | isUniqueWithinGroup | isBidirectional | isInverseHasOne | expectedUniqueValue
- "simple unique=true" | true | false | false | false | true
- "simple unique=false" | false | false | false | false | false
- "uniqueWithinGroup and bidirectional" | false | true | true | true | true
- "uniqueWithinGroup and unidirectional" | false | true | false | false | null
- "uniqueWithinGroup and not hasOne" | false | true | true | false | null
- }
-
- def "bind throws MappingException when column is not found"() {
- given:
- def namingStrategy = Mock(PersistentEntityNamingStrategy)
- def simpleValueBinder = Mock(SimpleValueBinder)
- def manyToOneValuesBinder = Mock(ManyToOneValuesBinder)
- def compositeBinder = Mock(CompositeIdentifierToManyToOneBinder)
- def columnFetcher = Mock(SimpleValueColumnFetcher)
-
- def manyToOneBinder = new ManyToOneBinder(
- getGrailsDomainBinder().getMetadataBuildingContext(),
- namingStrategy, simpleValueBinder, manyToOneValuesBinder, compositeBinder)
- def binder = new ForeignKeyOneToOneBinder(manyToOneBinder, columnFetcher)
-
- def property = Mock(TestFKOneToOne)
- def mapping = new Mapping()
- def refDomainClass = Mock(GrailsHibernatePersistentEntity) {
- getMappedForm() >> mapping
- getHibernateCompositeIdentity() >> Optional.empty()
- }
- def propertyConfig = new PropertyConfig()
-
- property.getHibernateAssociatedEntity() >> refDomainClass
- mapping.setIdentity(null)
- property.getMappedForm() >> propertyConfig
- property.getHibernateMappedForm() >> propertyConfig
- columnFetcher.getColumnForSimpleValue(_ as ManyToOne) >> null
-
- when:
- binder.bind(property, "/test")
-
- then:
- thrown(MappingException)
- }
-}
-
-abstract class TestFKOneToOne extends HibernateOneToOneProperty {
- TestFKOneToOne(PersistentEntity owner, MappingContext context, java.beans.PropertyDescriptor descriptor) {
- super(owner, context, descriptor)
- }
-}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/GrailsIdentityGeneratorSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/GrailsIdentityGeneratorSpec.groovy
index baf89c23e9..ff2f445b0e 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/GrailsIdentityGeneratorSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/GrailsIdentityGeneratorSpec.groovy
@@ -48,7 +48,7 @@ class GrailsIdentityGeneratorSpec extends HibernateGormDatastoreSpec {
def table = new Table("test")
def hibernateProperty = new Property()
- def value = new BasicValue(getGrailsDomainBinder().getMetadataBuildingContext(), table)
+ def value = new BasicValue(getMappingContributor().getMetadataBuildingContext(), table)
def column = new Column("test_id")
value.addColumn(column)
hibernateProperty.setValue(value)
@@ -73,7 +73,7 @@ class GrailsIdentityGeneratorSpec extends HibernateGormDatastoreSpec {
def table = new Table("test")
def hibernateProperty = new Property()
- def value = new BasicValue(getGrailsDomainBinder().getMetadataBuildingContext(), table)
+ def value = new BasicValue(getMappingContributor().getMetadataBuildingContext(), table)
def column = new Column("test_id2")
value.addColumn(column)
hibernateProperty.setValue(value)
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/GrailsPropertyBinderFixtures.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/GrailsPropertyBinderFixtures.groovy
new file mode 100644
index 0000000000..b88ef64423
--- /dev/null
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/GrailsPropertyBinderFixtures.groovy
@@ -0,0 +1,128 @@
+/*
+ * 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 org.grails.orm.hibernate.cfg.domainbinding
+
+import grails.gorm.annotation.Entity
+
+/**
+ * Domain classes of the former {@code GrailsPropertyBinderSpec}, a unit spec of the classic domain binder of Grails 8: they stay as fixtures of the
+ * differential specs, which compare native binding with the recorded classic schema of every scanned entity.
+ */
+@Entity
+class PropertyBinderSpecSimpleBook {
+ Long id
+ String title
+}
+
+@Entity
+class PropertyBinderSpecEnumBook {
+ Long id
+ java.util.concurrent.TimeUnit status
+}
+
+@Entity
+class PropertyBinderSpecEnumCollection {
+ Long id
+ Set<java.util.concurrent.TimeUnit> statuses
+ static hasMany = [statuses: java.util.concurrent.TimeUnit]
+}
+
+@Entity
+class PropertyBinderSpecAuthor {
+ Long id
+ static hasMany = [pets: PropertyBinderSpecPet]
+}
+
+@Entity
+class PropertyBinderSpecPet {
+ Long id
+ PropertyBinderSpecAuthor owner
+}
+
+@Entity
+class PropertyBinderSpecEmployee {
+ Long id
+ PropertyBinderSpecAddress address
+ static embedded = ['address']
+}
+
+class PropertyBinderSpecAddress implements Serializable {
+ String city
+}
+
+@Entity
+class PropertyBinderSpecSerializableEntity {
+ Long id
+ List<String> tags
+ static mapping = {
+ tags type: 'serializable'
+ }
+}
+
+@Entity
+class PropertyBinderSpecCustomEntity {
+ Long id
+ String data
+ static mapping = {
+ data type: 'org.hibernate.type.YesNoConverter'
+ }
+}
+
+@Entity
+class PropertyBinderSpecCustomUserTypeCollection {
+ Long id
+ Set<String> categories
+ static mapping = {
+ categories type: 'org.hibernate.type.YesNoConverter'
+ }
+}
+
+@Entity
+class PropertyBinderSpecHasOneProfile {
+ Long id
+ String bio
+ PropertyBinderSpecHasOneOwner owner
+ static belongsTo = [owner: PropertyBinderSpecHasOneOwner]
+}
+
+@Entity
+class PropertyBinderSpecHasOneOwner {
+ Long id
+ static hasOne = [profile: PropertyBinderSpecHasOneProfile]
+}
+
+@Entity
+class PropertyBinderSpecFKChild {
+ Long id
+ PropertyBinderSpecFKOwner owner
+ static belongsTo = [owner: PropertyBinderSpecFKOwner]
+}
+
+@Entity
+class PropertyBinderSpecFKOwner {
+ Long id
+ PropertyBinderSpecFKChild child
+}
+
+@Entity
+class PropertyBinderSpecTenantEntity implements grails.gorm.MultiTenant<PropertyBinderSpecTenantEntity> {
+ Long id
+ Integer tenantId
+}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/GrailsPropertyBinderSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/GrailsPropertyBinderSpec.groovy
deleted file mode 100644
index ff6b859c18..0000000000
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/GrailsPropertyBinderSpec.groovy
+++ /dev/null
@@ -1,505 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding
-
-import grails.gorm.annotation.Entity
-import grails.gorm.tests.HibernateGormDatastoreSpec
-import org.grails.orm.hibernate.cfg.domainbinding.hibernate.*
-import org.grails.orm.hibernate.cfg.domainbinding.binder.*
-
-import org.hibernate.mapping.ManyToOne
-import org.hibernate.mapping.OneToOne
-import org.hibernate.mapping.Property
-import org.hibernate.mapping.RootClass
-import org.hibernate.mapping.Value
-import org.hibernate.mapping.BasicValue
-import org.hibernate.mapping.Collection
-import org.hibernate.mapping.Component
-import org.hibernate.mapping.SimpleValue
-import org.hibernate.mapping.Table
-import org.hibernate.boot.spi.MetadataBuildingContext
-import org.grails.orm.hibernate.cfg.PersistentEntityNamingStrategy
-import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment
-import org.grails.orm.hibernate.cfg.domainbinding.util.SimpleValueColumnFetcher
-import org.hibernate.boot.spi.InFlightMetadataCollector
-import org.grails.orm.hibernate.cfg.domainbinding.util.PropertyFromValueCreator
-import org.grails.orm.hibernate.cfg.domainbinding.util.ColumnNameForPropertyAndPathFetcher
-import org.grails.orm.hibernate.cfg.domainbinding.util.DefaultColumnNameFetcher
-import org.grails.orm.hibernate.cfg.domainbinding.util.BackticksRemover
-import org.grails.orm.hibernate.cfg.domainbinding.util.TableForManyCalculator
-import org.grails.datastore.mapping.engine.types.CustomTypeMarshaller
-import org.grails.datastore.mapping.model.ClassMapping
-import org.grails.datastore.mapping.model.PropertyMapping
-import org.grails.orm.hibernate.cfg.PropertyConfig
-
-import java.beans.PropertyDescriptor
-
-import static org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsDomainBinder.EMPTY_PATH
-
-class GrailsPropertyBinderSpec extends HibernateGormDatastoreSpec {
-
- protected Map getBinders(GrailsDomainBinder binder, InFlightMetadataCollector collector = getCollector()) {
- MetadataBuildingContext metadataBuildingContext = binder.getMetadataBuildingContext()
- PersistentEntityNamingStrategy namingStrategy = binder.getNamingStrategy()
- JdbcEnvironment jdbcEnvironment = binder.getJdbcEnvironment()
- BackticksRemover backticksRemover = new BackticksRemover()
- DefaultColumnNameFetcher defaultColumnNameFetcher = new DefaultColumnNameFetcher(namingStrategy, backticksRemover)
- ColumnNameForPropertyAndPathFetcher columnNameForPropertyAndPathFetcher = new ColumnNameForPropertyAndPathFetcher(namingStrategy, defaultColumnNameFetcher, backticksRemover)
-
- SimpleValueBinder simpleValueBinder = new SimpleValueBinder(metadataBuildingContext, namingStrategy, jdbcEnvironment)
- EnumTypeBinder enumTypeBinderToUse = new EnumTypeBinder(metadataBuildingContext, columnNameForPropertyAndPathFetcher, namingStrategy)
- SimpleValueColumnFetcher simpleValueColumnFetcher = new SimpleValueColumnFetcher()
- CompositeIdentifierToManyToOneBinder compositeIdentifierToManyToOneBinder = new CompositeIdentifierToManyToOneBinder(
- new org.grails.orm.hibernate.cfg.domainbinding.util.ForeignKeyColumnCountCalculator(),
- namingStrategy,
- defaultColumnNameFetcher,
- backticksRemover,
- simpleValueBinder
- )
- OneToOneBinder oneToOneBinder = new OneToOneBinder(metadataBuildingContext, simpleValueBinder)
- ManyToOneBinder manyToOneBinder = new ManyToOneBinder(metadataBuildingContext, namingStrategy, simpleValueBinder, new ManyToOneValuesBinder(), compositeIdentifierToManyToOneBinder)
- ForeignKeyOneToOneBinder foreignKeyOneToOneBinder = new ForeignKeyOneToOneBinder(manyToOneBinder, simpleValueColumnFetcher)
-
- TableForManyCalculator tableForManyCalculator = new TableForManyCalculator(namingStrategy, collector)
- CollectionBinder collectionBinder = new CollectionBinder(
- metadataBuildingContext,
- namingStrategy,
- simpleValueBinder,
- enumTypeBinderToUse,
- manyToOneBinder,
- compositeIdentifierToManyToOneBinder,
- simpleValueColumnFetcher,
- new org.grails.orm.hibernate.cfg.domainbinding.collectionType.CollectionHolder(metadataBuildingContext),
- collector,
- tableForManyCalculator
- )
- PropertyFromValueCreator propertyFromValueCreator = new PropertyFromValueCreator()
- ComponentUpdater componentUpdater = new ComponentUpdater(propertyFromValueCreator)
- ComponentBinder componentBinder = new ComponentBinder(
- metadataBuildingContext,
- binder.getMappingCacheHolder(),
- componentUpdater
... 10766 lines suppressed ...
(grails-core) 01/06: test(hibernate7): state the classic facts the both-modes specs compared against as literal expectations
Posted by bo...@apache.org.
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 e27c4fdc842b7865001c31d09b7a7ea20c5d1dfb
Author: Walter Duque de Estrada <wb...@mac.com>
AuthorDate: Fri Oct 9 17:29:17 2026 -0500
test(hibernate7): state the classic facts the both-modes specs compared against as literal expectations
The classic domain binder is being deleted from 9.0.x. 33 specs booted a datastore
through it next to a native one and asserted "the same as classic": the schema maps,
the join tables, the cache regions, the stored rows. Their classic half is replaced by
the values those comparisons held at eb82a95c44 (every equality passed in the last
classic run of the suite; the values that only a classic boot could give, such as the
H2 script of the embedded-identifier entity native binding refuses, were recorded from
one more classic boot before the deletion). Whole-schema equalities are left to
GeneratedDomainClassesDdlDifferentialSpec, which compares every one of these fixtures
with the recorded classic schema.
The five specs that could only run against a classic datastore (classic-only-specs.txt)
either pinned classic defects with @PendingFeature, which native binding does not have
(the pins are deleted or become plain behaviour specs: UnidirectionalEntityCollectionsSpec,
UnidirectionalBasicCollectionsSpec, ColumnOptionSpec, ManyToManyOwnershipSpec), or read
the Hibernate collection the classic binder left on the metamodel, which the generator
specs now build by hand or no longer assert. The list is empty, so it goes.
Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
---
grails-data-hibernate7/core/classic-only-specs.txt | 39 -----
.../domainbinding/jpa/GrailsDomainGenerator.groovy | 6 +-
...GeneratedDomainClassesBinderLeniencySpec.groovy | 39 +++--
.../GeneratedDomainClassesBootSpec.groovy | 4 +-
.../GeneratedDomainClassesCacheRegionSpec.groovy | 45 +++---
...ratedDomainClassesCircularManyToManySpec.groovy | 96 +++++++------
...edDomainClassesCollectionConstraintsSpec.groovy | 80 +++++------
...atedDomainClassesCollectionIndexTypeSpec.groovy | 50 ++++---
...GeneratedDomainClassesCollectionSortSpec.groovy | 25 ++--
...GeneratedDomainClassesCollectionTypeSpec.groovy | 52 +++----
...atedDomainClassesCompositeCollectionSpec.groovy | 36 ++---
.../GeneratedDomainClassesContributorSpec.groovy | 22 ++-
...GeneratedDomainClassesConverterClassSpec.groovy | 44 +++---
...tedDomainClassesCustomCollectionTypeSpec.groovy | 64 ++++-----
.../GeneratedDomainClassesDiscriminatorSpec.groovy | 32 ++---
...ratedDomainClassesEmbeddedCollectionSpec.groovy | 96 +++++--------
...tedDomainClassesEmbeddedIdWorkaroundSpec.groovy | 158 ++++++++++-----------
.../GeneratedDomainClassesJoinColumnSpec.groovy | 42 +++---
.../GeneratedDomainClassesMapManyToManySpec.groovy | 112 +++++++--------
...eneratedDomainClassesMultiDataSourceSpec.groovy | 75 +++++-----
.../GeneratedDomainClassesMultiTenancySpec.groovy | 15 +-
.../GeneratedDomainClassesNaturalIdSpec.groovy | 116 ++++++---------
...neratedDomainClassesSerializableTypeSpec.groovy | 50 +++----
.../GeneratedDomainClassesSerializationSpec.groovy | 65 ++++-----
...omainClassesSharedEmbeddedCollectionSpec.groovy | 96 ++++---------
.../GeneratedDomainClassesTenancyModesSpec.groovy | 134 +++++++++--------
.../GeneratedDomainClassesTenantTypeSpec.groovy | 42 +++---
.../GeneratedDomainClassesTypeMismatchSpec.groovy | 43 +++---
...GeneratedDomainClassesTypeParametersSpec.groovy | 27 ++--
.../GeneratedDomainClassesWriteFlagsSpec.groovy | 63 ++++----
.../binder/ManyToManyWithoutOwnerSpec.groovy | 71 ++++-----
.../hibernate/HibernateBasicPropertySpec.groovy | 25 ++--
...onDefectSpec.groovy => ColumnOptionSpec.groovy} | 29 ++--
...eneratedDomainClassesDdlDifferentialSpec.groovy | 2 +-
.../GrailsDomainBinderCompositeIdDefectSpec.groovy | 96 -------------
...DomainBinderEmbeddedCollectionDefectSpec.groovy | 50 -------
.../GrailsDomainGeneratorCompositeIdSpec.groovy | 4 +-
.../GrailsDomainGeneratorDifferentialSpec.groovy | 6 +-
.../jpa/GrailsDomainGeneratorSpec.groovy | 7 +-
.../GrailsDomainGeneratorUniqueGroupSpec.groovy | 17 +--
...tSpec.groovy => ManyToManyOwnershipSpec.groovy} | 9 +-
...y => UnidirectionalBasicCollectionsSpec.groovy} | 9 +-
... => UnidirectionalEntityCollectionsSpec.groovy} | 13 +-
43 files changed, 828 insertions(+), 1278 deletions(-)
diff --git a/grails-data-hibernate7/core/classic-only-specs.txt b/grails-data-hibernate7/core/classic-only-specs.txt
deleted file mode 100644
index 8fd78eb2f7..0000000000
--- a/grails-data-hibernate7/core/classic-only-specs.txt
+++ /dev/null
@@ -1,39 +0,0 @@
-#
-# 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.
-#
-# Specs that run only when the whole suite boots through the classic domain binder:
-# ./gradlew -Pgrails.test.classicDomainBinding=true :grails-data-hibernate7-core:test
-#
-# The default run boots every manager-built datastore through native domain binding (hibernate.generatedDomainClasses,
-# on by default) and EXCLUDES the specs listed here; the classic run runs every spec and does not read this file.
-#
-# They exercise the classic domain binder or the generator themselves against the classic datastore of the base spec
-# (they build binder objects by hand, bind through createPersistentEntity / hibernateFirstPass, or compare the binder
-# with the generator), so they need the classic binder to be the one that booted the datastore. A spec is a "binder
-# internals" spec when its source lives under cfg/domainbinding or mentions GrailsDomainBinder, GrailsDomainGenerator,
-# GeneratedDomainClassBinder, hibernateFirstPass, createPersistentEntity, getGrailsDomainBinder, getCollector(,
-# InFlightMetadataCollector or MetadataBuildingContext. Only those that FAIL with a natively bound datastore are listed,
-# one fully qualified class name per line; the others run and pass in both modes (every other binder-internals spec,
-# the generator differential included, was run against a natively bound datastore before being left out of this list).
-# The five listed assert facts of the classic boot model (a collection table the classic binder creates, a unique key it
-# drops, the type parameters it sets) or pin classic defects with @PendingFeature, which native binding does not have,
-# so they only hold against a classic datastore. The list goes away with the classic binder.
-#
-org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateBasicPropertySpec
-org.grails.orm.hibernate.cfg.domainbinding.jpa.EntityCollectionKeyDefectSpec
-org.grails.orm.hibernate.cfg.domainbinding.jpa.GrailsDomainBinderOptionDefectSpec
-org.grails.orm.hibernate.cfg.domainbinding.jpa.GrailsDomainGeneratorSpec
-org.grails.orm.hibernate.cfg.domainbinding.jpa.GrailsDomainGeneratorUniqueGroupSpec
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 9a20f2b486..9f8be96a6d 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
@@ -320,7 +320,7 @@ class GrailsDomainGenerator {
* the owner, and gives it no owner-specific identity, so two embedded properties that share a type with a collection share one
* table whose key is a foreign key to the owner that was bound first (probed: the rows of the other owner violate it unless the
* identifiers happen to coincide), and Hibernate refuses the duplicate collection at boot when the two properties have the same name
- * (pinned in {@code GrailsDomainBinderEmbeddedCollectionDefectSpec}).
+ * (a defect of the classic binding of Grails 8).
*
* <p>Every embedded property gets a collection table of its own. The first one, in the order of the entity name and then the
* property path, keeps the names the binder gives the shared table, so an existing database is undisturbed; the others get names
@@ -2024,7 +2024,7 @@ class GrailsDomainGenerator {
if (simplePart != null) {
return "the composite identifier of the associated entity [${target.name}] has a part [${simplePart.name}] that refers to an " +
'entity with a simple identifier: ForeignKeyColumnCountCalculator counts such a part as no column, so the binder gives ' +
- 'the foreign key fewer columns than the key and Hibernate refuses it at boot (pinned in GrailsDomainBinderCompositeIdDefectSpec)'
+ 'the foreign key fewer columns than the key and Hibernate refuses it at boot'
}
HibernatePersistentProperty deepPart = root.compositeIdentity.find { HibernatePersistentProperty part ->
part instanceof HibernateToOneProperty && compositeIdentifier(((HibernateToOneProperty) part).hibernateAssociatedEntity) &&
@@ -2458,7 +2458,7 @@ class GrailsDomainGenerator {
}
if (columnConfig != null) {
// EnumTypeBinder ignores the comment, the default and the read and write expressions of the column config (a binder
- // defect, pinned in GrailsDomainBinderOptionDefectSpec); the generator states what the mapping asks for
+ // defect of Grails 8); the generator states what the mapping asks for
column.comment = columnConfig.comment
column.defaultValue = columnConfig.defaultValue
column.customRead = columnConfig.read
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
index 25378a425b..84bf1e0813 100644
--- 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
@@ -35,11 +35,12 @@ 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.
+ * Mappings that say more than the classic binding of Grails 8 used, and that it booted all the same: a join table that names a
+ * composite key (the first key column is used and the others ignored), a {@code type} that names a Java class and not a type (the class
+ * name is looked up among the types registered for Java classes), and a property of a class GORM does not know and the mapping gives no
+ * type (Hibernate picks the type, which is binary for a serializable class). Native binding boots them with the same columns instead of
+ * refusing them; the columns and the behaviour stated here are the ones classic binding had (the schema of every group is also compared
+ * with the recorded classic schema by {@code GeneratedDomainClassesDdlDifferentialSpec}).
*/
class GeneratedDomainClassesBinderLeniencySpec extends Specification {
@@ -48,18 +49,17 @@ class GeneratedDomainClassesBinderLeniencySpec extends Specification {
@AutoCleanup
HibernateDatastore datastore
- private HibernateDatastore boot(List<Class> group, boolean generated) {
+ private HibernateDatastore boot(List<Class> group) {
datastore?.close()
datastore = new HibernateDatastore([
- 'dataSource.url' : "jdbc:h2:mem:gbl${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
- 'dataSource.dbCreate' : 'create-drop',
- 'hibernate.generatedDomainClasses': generated,
+ 'dataSource.url' : "jdbc:h2:mem:gbl${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
+ 'dataSource.dbCreate': 'create-drop',
], group as Class[])
return datastore
}
- private Map<String, Map> schema(List<Class> group, boolean generated) {
- HibernateDatastore booted = boot(group, generated)
+ private Map<String, Map> schema(List<Class> group) {
+ HibernateDatastore booted = boot(group)
Map<String, Map> result = new TreeMap<String, Map>()
for (Table table : booted.metadata.collectTableMappings()) {
if (table.physicalTable) {
@@ -77,13 +77,11 @@ class GeneratedDomainClassesBinderLeniencySpec extends Specification {
}
@Unroll
- void "#label: the generated mode creates the tables and columns of the domain binder"() {
+ void "#label: the tables and columns of classic binding are created"() {
when:
- Map<String, Map> binder = schema(group, false)
- Map<String, Map> generated = schema(group, true)
+ Map<String, Map> generated = schema(group)
then:
- generated == binder
generated[table].columns.keySet() == columns as Set
where:
@@ -99,16 +97,13 @@ class GeneratedDomainClassesBinderLeniencySpec extends Specification {
}
@Unroll
- void "#label: the rows are stored, read back and changed in both modes"() {
+ void "#label: the rows are stored, read back and changed"() {
when:
- Map<Boolean, List> results = [false, true].collectEntries { boolean generated ->
- boot(group, generated)
- [(generated): this."${cycle}"()]
- }
+ boot(group)
+ List results = this."${cycle}"()
then:
- results[true] == results[false]
- results[true] == expected
+ results == expected
where:
label | group | cycle | expected
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesBootSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesBootSpec.groovy
index 795d54d573..6956b230e1 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesBootSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesBootSpec.groovy
@@ -26,7 +26,7 @@ import org.grails.datastore.mapping.core.DatastoreUtils
import org.grails.orm.hibernate.HibernateDatastore
/**
- * What the generated-domain-class binding boots (an entity with a composite identifier) and the plain binder boots too.
+ * What boots through the generated classes (an entity with a composite identifier), with the setting stated and with the defaults.
*/
class GeneratedDomainClassesBootSpec extends Specification {
@@ -50,7 +50,7 @@ class GeneratedDomainClassesBootSpec extends Specification {
datastore?.close()
}
- def "the same entity boots through the domain binder"() {
+ def "the same entity boots with the default settings"() {
when:
HibernateDatastore datastore = new HibernateDatastore(
DatastoreUtils.createPropertyResolver([
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCacheRegionSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCacheRegionSpec.groovy
index f2447782e8..5d07ab0edb 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCacheRegionSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCacheRegionSpec.groovy
@@ -34,27 +34,24 @@ import org.grails.datastore.mapping.core.DatastoreUtils
import org.grails.orm.hibernate.HibernateDatastore
/**
- * The second-level cache regions of the generated-domain-class binding carry the names the domain binder gives them: Hibernate
- * derives a region name from the entity name or the collection role, which are the names of the generated classes in this mode,
- * so an application that configures its cache regions by the names of its domain classes would silently lose that configuration.
- * The same domain classes are booted both ways and the regions Hibernate ends up with are compared.
+ * The second-level cache regions carry the names the classic binding of Grails 8 gave them: Hibernate derives a region name from
+ * the entity name or the collection role, which are the names of the generated classes, so an application that configures its cache
+ * regions by the names of its domain classes would silently lose that configuration. The regions stated here are the ones classic
+ * binding gave.
*/
class GeneratedDomainClassesCacheRegionSpec extends Specification {
@Shared HibernateDatastore generated
- @Shared HibernateDatastore binder
void setupSpec() {
- generated = boot('gdcRegionsGenerated', true, [:])
- binder = boot('gdcRegionsBinder', false, [:])
+ generated = boot('gdcRegionsGenerated', [:])
}
void cleanupSpec() {
generated?.close()
- binder?.close()
}
- private static HibernateDatastore boot(String name, boolean generatedClasses, Map<String, Object> extra) {
+ private static HibernateDatastore boot(String name, Map<String, Object> extra) {
Map<String, Object> config = [
'dataSource.url' : "jdbc:h2:mem:${name};LOCK_TIMEOUT=10000".toString(),
'dataSource.dbCreate' : 'create-drop',
@@ -62,7 +59,6 @@ class GeneratedDomainClassesCacheRegionSpec extends Specification {
'region.factory_class' : 'org.hibernate.cache.jcache.internal.JCacheRegionFactory'] +
extra.findAll { String key, Object value -> key.startsWith('hibernate.cache.') }
.collectEntries { String key, Object value -> [(key.substring('hibernate.cache.'.length())): value] },
- 'hibernate.generatedDomainClasses': generatedClasses,
] as Map<String, Object>
return new HibernateDatastore(DatastoreUtils.createPropertyResolver(config),
GdcRegionAuthor, GdcRegionBook, GdcRegionVehicle, GdcRegionCar, GdcRegionWheel, GdcRegionNatural,
@@ -103,7 +99,6 @@ class GeneratedDomainClassesCacheRegionSpec extends Specification {
def "a cached root entity and a cached subclass hierarchy use the region of the real root class"() {
expect:
- entityRegions(binder)[GdcRegionBook.name] == GdcRegionBook.name
entityRegions(generated)[GdcRegionBook.name] == GdcRegionBook.name
entityRegions(generated)[GdcRegionVehicle.name] == GdcRegionVehicle.name
entityRegions(generated)[GdcRegionCar.name] == GdcRegionVehicle.name
@@ -112,35 +107,35 @@ class GeneratedDomainClassesCacheRegionSpec extends Specification {
def "a cached collection uses the real role as its region, for a root and for a subclass owner"() {
expect:
- collectionRegions(binder) == [
+ collectionRegions(generated) == [
(GdcRegionBook.name + '.authors'): GdcRegionBook.name + '.authors',
(GdcRegionCar.name + '.wheels') : GdcRegionCar.name + '.wheels']
- collectionRegions(generated) == collectionRegions(binder)
}
- def "a collection of an embedded type is not cached in either binding"() {
+ def "a collection of an embedded type is not cached"() {
expect:
- !collectionRegions(binder).keySet().any { String key -> key.startsWith(GdcRegionPerson.name) }
!collectionRegions(generated).keySet().any { String key -> key.startsWith(GdcRegionPerson.name) }
}
- def "the regions of the generated binding equal the regions of the domain binder"() {
+ def "the regions are the regions classic binding gave"() {
expect:
- entityRegions(generated) == entityRegions(binder)
- collectionRegions(generated) == collectionRegions(binder)
- naturalIdRegions(generated) == naturalIdRegions(binder)
- regionNames(generated) == regionNames(binder)
+ entityRegions(generated) == [
+ (GdcRegionAuthor.name) : null, (GdcRegionBook.name): GdcRegionBook.name, (GdcRegionVehicle.name): GdcRegionVehicle.name,
+ (GdcRegionCar.name) : GdcRegionVehicle.name, (GdcRegionWheel.name): null, (GdcRegionNatural.name): GdcRegionNatural.name,
+ (GdcRegionUncached.name): null, (GdcRegionPerson.name): null,
+ ]
+ regionNames(generated) == [GdcRegionBook.name, GdcRegionVehicle.name, GdcRegionNatural.name,
+ GdcRegionBook.name + '.authors', GdcRegionCar.name + '.wheels'] as Set
}
- def "a natural id of a cached entity has no cache of its own in either binding"() {
+ def "a natural id of a cached entity has no cache of its own"() {
expect:
- naturalIdRegions(binder).isEmpty()
naturalIdRegions(generated).isEmpty()
}
- def "the JCache caches of the generated binding carry the real names under the configured region prefix"() {
+ def "the JCache caches carry the real names under the configured region prefix"() {
given:
- HibernateDatastore prefixed = boot('gdcRegionsPrefixed', true, ['hibernate.cache.region_prefix': 'app'])
+ HibernateDatastore prefixed = boot('gdcRegionsPrefixed', ['hibernate.cache.region_prefix': 'app'])
Set<String> caches = Caching.cachingProvider.cacheManager.cacheNames.findAll { String name -> name.startsWith('app.') } as Set<String>
expect:
@@ -153,7 +148,7 @@ class GeneratedDomainClassesCacheRegionSpec extends Specification {
def "the second-level cache works end to end under the real region names"() {
given: 'a datastore of its own, because GORM binds an entity class to the datastore booted last'
- HibernateDatastore datastore = boot('gdcRegionsEndToEnd', true, [:])
+ HibernateDatastore datastore = boot('gdcRegionsEndToEnd', [:])
Statistics statistics = datastore.sessionFactory.statistics
statistics.statisticsEnabled = true
Serializable id = GdcRegionBook.withNewTransaction {
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCircularManyToManySpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCircularManyToManySpec.groovy
index f776b0c808..b37a533d8f 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCircularManyToManySpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCircularManyToManySpec.groovy
@@ -33,11 +33,11 @@ import spock.lang.Unroll
import org.grails.orm.hibernate.HibernateDatastore
/**
- * A self-referencing many-to-many (one entity on both sides) over the generated classes names its join table columns as the
- * domain binder does. The binder renames the join key of one side while it binds the other, so which side keeps the default key
- * name depends on the order the two collections are bound in, which is the order of the properties of the entity. A user whose
- * database was created by the binder and who turns generated mode on must not see {@code update} add new columns beside the old
- * ones, and a relationship the binder wrote must still be read.
+ * A self-referencing many-to-many (one entity on both sides) names its join table columns as the classic binding of Grails 8 did.
+ * Classic binding renamed the join key of one side while it bound the other, so which side keeps the default key name depends on
+ * the order the two collections are bound in, which is the order of the properties of the entity. A user whose database was created
+ * by Grails 8 must not see {@code update} add new columns beside the old ones, and a relationship written then must still be read.
+ * The join tables stated here are the ones classic binding created, recorded before it was removed.
*/
class GeneratedDomainClassesCircularManyToManySpec extends Specification {
@@ -46,19 +46,18 @@ class GeneratedDomainClassesCircularManyToManySpec extends Specification {
@AutoCleanup
HibernateDatastore datastore
- private HibernateDatastore boot(List<Class> group, boolean generated) {
+ private HibernateDatastore boot(List<Class> group) {
datastore?.close()
datastore = new HibernateDatastore([
- 'dataSource.url' : "jdbc:h2:mem:cmmCircular${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
- 'dataSource.dbCreate' : 'create-drop',
- 'hibernate.generatedDomainClasses': generated,
+ 'dataSource.url' : "jdbc:h2:mem:cmmCircular${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
+ 'dataSource.dbCreate': 'create-drop',
], group as Class[])
return datastore
}
/** The collections and the join tables the boot model holds, as plain data. */
- private Map<String, Object> schema(List<Class> group, boolean generated) {
- HibernateDatastore booted = boot(group, generated)
+ private Map<String, Object> schema(List<Class> group) {
+ HibernateDatastore booted = boot(group)
Map<String, Object> result = [:]
for (HibernateCollection collection : booted.metadata.collectionBindings) {
Table table = collection.collectionTable
@@ -76,42 +75,55 @@ class GeneratedDomainClassesCircularManyToManySpec extends Specification {
}
@Unroll
- void "the join tables of #label have the column names the domain binder gives them"() {
+ void "the join tables of #label have the column names classic binding gave them"() {
when:
- Map<String, Object> binder = schema(group, false)
- Map<String, Object> generated = schema(group, true)
+ Map<String, Object> generated = schema(group)
then:
- !binder.isEmpty()
- generated == binder
+ generated == expected
where:
- label | group
- 'a bidirectional self many-to-many' | [CmFollowers]
- 'the same with the properties declared the other way' | [CmFollowersSwapped]
- 'the same with the properties and hasMany in two orders' | [CmFollowersMixed]
- 'the same with names that sort the other way' | [CmZebras]
- 'a self many-to-many inside a hierarchy' | [CmHierarchyRoot, CmHierarchySub]
- 'a superclass collection and a circular subclass one' | [CmMammal, CmDog]
- 'a unidirectional self many-to-many' | [CmFriends]
- 'a first side that names its join key' | [CmKeyedFirst]
- 'a second side that names its join key' | [CmKeyedSecond]
+ label << ['a bidirectional self many-to-many', 'the same with the properties declared the other way',
+ 'the same with the properties and hasMany in two orders', 'the same with names that sort the other way',
+ 'a self many-to-many inside a hierarchy', 'a superclass collection and a circular subclass one',
+ 'a unidirectional self many-to-many', 'a first side that names its join key', 'a second side that names its join key']
+ group << [[CmFollowers], [CmFollowersSwapped], [CmFollowersMixed], [CmZebras], [CmHierarchyRoot, CmHierarchySub], [CmMammal, CmDog],
+ [CmFriends], [CmKeyedFirst], [CmKeyedSecond]]
+ expected << [
+ ['grails.gorm.tests.generated.CmFollowers.following': [table: 'cm_followers_following', inverse: false, key: ['following_id'], element: ['followers_id'], columns: ['followers_id', 'following_id'], primaryKey: ['followers_id', 'following_id'], foreignKeys: [['followers_id'], ['following_id']]],
+ 'grails.gorm.tests.generated.CmFollowers.followers': [table: 'cm_followers_followers', inverse: false, key: ['cm_followers_id'], element: ['following_id'], columns: ['cm_followers_id', 'following_id'], primaryKey: ['cm_followers_id', 'following_id'], foreignKeys: [['cm_followers_id'], ['following_id']]]],
+ ['grails.gorm.tests.generated.CmFollowersSwapped.following': [table: 'cm_followers_swapped_following', inverse: false, key: ['cm_followers_swapped_id'], element: ['followers_id'], columns: ['cm_followers_swapped_id', 'followers_id'], primaryKey: ['cm_followers_swapped_id', 'followers_id'], foreignKeys: [['cm_followers_swapped_id'], ['followers_id']]],
+ 'grails.gorm.tests.generated.CmFollowersSwapped.followers': [table: 'cm_followers_swapped_followers', inverse: false, key: ['followers_id'], element: ['following_id'], columns: ['followers_id', 'following_id'], primaryKey: ['followers_id', 'following_id'], foreignKeys: [['followers_id'], ['following_id']]]],
+ ['grails.gorm.tests.generated.CmFollowersMixed.following': [table: 'cm_followers_mixed_following', inverse: false, key: ['cm_followers_mixed_id'], element: ['followers_id'], columns: ['cm_followers_mixed_id', 'followers_id'], primaryKey: ['cm_followers_mixed_id', 'followers_id'], foreignKeys: [['cm_followers_mixed_id'], ['followers_id']]],
+ 'grails.gorm.tests.generated.CmFollowersMixed.followers': [table: 'cm_followers_mixed_followers', inverse: false, key: ['followers_id'], element: ['following_id'], columns: ['followers_id', 'following_id'], primaryKey: ['followers_id', 'following_id'], foreignKeys: [['followers_id'], ['following_id']]]],
+ ['grails.gorm.tests.generated.CmZebras.zebras': [table: 'cm_zebras_zebras', inverse: false, key: ['cm_zebras_id'], element: ['apples_id'], columns: ['apples_id', 'cm_zebras_id'], primaryKey: ['apples_id', 'cm_zebras_id'], foreignKeys: [['apples_id'], ['cm_zebras_id']]],
+ 'grails.gorm.tests.generated.CmZebras.apples': [table: 'cm_zebras_apples', inverse: false, key: ['apples_id'], element: ['zebras_id'], columns: ['apples_id', 'zebras_id'], primaryKey: ['apples_id', 'zebras_id'], foreignKeys: [['apples_id'], ['zebras_id']]]],
+ ['grails.gorm.tests.generated.CmHierarchySub.pals': [table: 'cm_hierarchy_sub_pals', inverse: false, key: ['cm_hierarchy_sub_id'], element: ['pal_of_id'], columns: ['cm_hierarchy_sub_id', 'pal_of_id'], primaryKey: null, foreignKeys: [['cm_hierarchy_sub_id'], ['pal_of_id']]],
+ 'grails.gorm.tests.generated.CmHierarchySub.palOf': [table: 'cm_hierarchy_sub_pal_of', inverse: false, key: ['pal_of_id'], element: ['pals_id'], columns: ['pal_of_id', 'pals_id'], primaryKey: null, foreignKeys: [['pal_of_id'], ['pals_id']]]],
+ ['grails.gorm.tests.generated.CmMammal.dogs': [table: 'cm_mammal_dogs', inverse: false, key: ['cm_mammal_id'], element: ['animals_id'], columns: ['animals_id', 'cm_mammal_id'], primaryKey: null, foreignKeys: [['animals_id'], ['cm_mammal_id']]],
+ 'grails.gorm.tests.generated.CmDog.animals': [table: 'cm_mammal_dogs', inverse: true, key: ['animals_id'], element: ['cm_mammal_id'], columns: ['animals_id', 'cm_mammal_id'], primaryKey: null, foreignKeys: [['animals_id'], ['cm_mammal_id']]]],
+ ['grails.gorm.tests.generated.CmFriends.friends': [table: 'cm_friends_cm_friends', inverse: false, key: ['cm_friends_friends_id'], element: ['cm_friends_id'], columns: ['cm_friends_friends_id', 'cm_friends_id'], primaryKey: null, foreignKeys: [['cm_friends_friends_id'], ['cm_friends_id']]]],
+ ['grails.gorm.tests.generated.CmKeyedFirst.following': [table: 'cm_keyed_first_following', inverse: false, key: ['following_id'], element: ['owner_ref'], columns: ['following_id', 'owner_ref'], primaryKey: ['following_id', 'owner_ref'], foreignKeys: [['following_id'], ['owner_ref']]],
+ 'grails.gorm.tests.generated.CmKeyedFirst.followers': [table: 'cm_keyed_first_f', inverse: false, key: ['owner_ref'], element: ['following_id'], columns: ['following_id', 'owner_ref'], primaryKey: ['following_id', 'owner_ref'], foreignKeys: [['following_id'], ['owner_ref']]]],
+ ['grails.gorm.tests.generated.CmKeyedSecond.following': [table: 'cm_keyed_second_f', inverse: false, key: ['owner_ref'], element: ['followers_id'], columns: ['followers_id', 'owner_ref'], primaryKey: ['followers_id', 'owner_ref'], foreignKeys: [['followers_id'], ['owner_ref']]],
+ 'grails.gorm.tests.generated.CmKeyedSecond.followers': [table: 'cm_keyed_second_followers', inverse: false, key: ['cm_keyed_second_id'], element: ['owner_ref'], columns: ['cm_keyed_second_id', 'owner_ref'], primaryKey: ['cm_keyed_second_id', 'owner_ref'], foreignKeys: [['cm_keyed_second_id'], ['owner_ref']]]],
+ ]
}
- void "a non-circular owning side that names the key and the column of its join table gives the generated mode the same columns"() {
+ void "a non-circular owning side that names the key and the column of its join table gets those columns, and the inverse side shares them"() {
when:
- Map<String, Object> binder = schema([CmNamedOwner, CmNamedOther], false)
- Map<String, Object> generated = schema([CmNamedOwner, CmNamedOther], true)
+ Map<String, Object> generated = schema([CmNamedOwner, CmNamedOther])
then:
- generated == binder
generated['grails.gorm.tests.generated.CmNamedOwner.others'].key == ['owner_ref']
generated['grails.gorm.tests.generated.CmNamedOwner.others'].element == ['other_ref']
+ generated['grails.gorm.tests.generated.CmNamedOther.owners'] == [table: 'cm_named_join', inverse: true, key: ['other_ref'], element: ['owner_ref'],
+ columns: ['other_ref', 'owner_ref'], primaryKey: ['other_ref', 'owner_ref'], foreignKeys: [['other_ref'], ['owner_ref']]]
}
void "the side bound first keeps the default key name and the side bound second is named after its property"() {
when:
- Map<String, Object> generated = schema([CmFollowers], true)
+ Map<String, Object> generated = schema([CmFollowers])
then:
generated['grails.gorm.tests.generated.CmFollowers.followers'].key == ['cm_followers_id']
@@ -123,7 +135,7 @@ class GeneratedDomainClassesCircularManyToManySpec extends Specification {
void "which side is bound first follows the order of the properties"() {
when:
- Map<String, Object> generated = schema([CmFollowersSwapped], true)
+ Map<String, Object> generated = schema([CmFollowersSwapped])
then:
generated['grails.gorm.tests.generated.CmFollowersSwapped.following'].key == ['cm_followers_swapped_id']
@@ -145,8 +157,8 @@ class GeneratedDomainClassesCircularManyToManySpec extends Specification {
}
/** Writes a relationship through one side, then reads it through both sides, in a fresh session. */
- private Map<String, Object> behaviour(boolean generated) {
- HibernateDatastore booted = boot([CmFollowers], generated)
+ private Map<String, Object> behaviour() {
+ HibernateDatastore booted = boot([CmFollowers])
Map<String, Object> result = [:]
CmFollowers.withTransaction {
CmFollowers a = new CmFollowers(name: 'a').save(failOnError: true)
@@ -166,18 +178,16 @@ class GeneratedDomainClassesCircularManyToManySpec extends Specification {
return result
}
- void "a relationship written through one side is read through the sides exactly as with the domain binder"() {
+ void "a relationship written through one side is read through the sides as classic binding read it"() {
when:
- Map<String, Object> binder = behaviour(false)
- Map<String, Object> generated = behaviour(true)
+ Map<String, Object> generated = behaviour()
then:
- generated == binder
- binder.followersOfA == ['b']
- binder.followingOfB == ['a']
- binder.followingOfA.isEmpty()
- binder.followersOfB.isEmpty()
- binder.joinTables == ['cm_followers_followers': ['1'], 'cm_followers_following': ['1']]
+ generated.followersOfA == ['b']
+ generated.followingOfB == ['a']
+ generated.followingOfA.isEmpty()
+ generated.followersOfB.isEmpty()
+ generated.joinTables == ['cm_followers_followers': ['1'], 'cm_followers_following': ['1']]
}
}
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCollectionConstraintsSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCollectionConstraintsSpec.groovy
index 49021a5ba5..b695689972 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCollectionConstraintsSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCollectionConstraintsSpec.groovy
@@ -29,11 +29,11 @@ import spock.lang.Unroll
import org.grails.orm.hibernate.HibernateDatastore
/**
- * An {@code index:} or a {@code unique:} group mapped on a collection property, booted through the generated classes and through
- * the domain binder. The binder binds the key column of a collection like any other column, so {@code index:} creates an index
- * over the key column of the collection table (and, for a collection of enums, over the element column too), named as the mapping
- * says; a unique group names columns of the owner's table, which the collection table does not have, so it creates no key in the
- * generated mode (the binder's impossible key is a defect fixed on the 8.0.x line).
+ * An {@code index:} or a {@code unique:} group mapped on a collection property. The classic binding of Grails 8 bound the key column
+ * of a collection like any other column, so {@code index:} creates an index over the key column of the collection table (and, for a
+ * collection of enums, over the element column too), named as the mapping says; a unique group names columns of the owner's table,
+ * which the collection table does not have, so it creates no key (the impossible key classic binding made was a defect fixed on the
+ * 8.0.x line). The indexes, keys and tables stated here are the ones classic binding created.
*/
class GeneratedDomainClassesCollectionConstraintsSpec extends Specification {
@@ -42,19 +42,18 @@ class GeneratedDomainClassesCollectionConstraintsSpec extends Specification {
@AutoCleanup
HibernateDatastore datastore
- private HibernateDatastore boot(List<Class> group, boolean generated) {
+ private HibernateDatastore boot(List<Class> group) {
datastore?.close()
datastore = new HibernateDatastore([
- 'dataSource.url' : "jdbc:h2:mem:ccs${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
- 'dataSource.dbCreate' : 'create-drop',
- 'hibernate.generatedDomainClasses': generated,
+ 'dataSource.url' : "jdbc:h2:mem:ccs${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
+ 'dataSource.dbCreate': 'create-drop',
], group as Class[])
return datastore
}
/** The tables of the boot model as plain data: the columns with their type, the indexes and the unique keys. */
- private Map<String, Map> schema(List<Class> group, boolean generated) {
- HibernateDatastore booted = boot(group, generated)
+ private Map<String, Map> schema(List<Class> group) {
+ HibernateDatastore booted = boot(group)
Map<String, Map> result = new TreeMap<String, Map>()
for (Table table : booted.metadata.collectTableMappings()) {
if (table.physicalTable) {
@@ -91,37 +90,36 @@ class GeneratedDomainClassesCollectionConstraintsSpec extends Specification {
}
@Unroll
- void "an index mapped on #label creates the indexes the domain binder creates"() {
+ void "an index mapped on #label creates the indexes classic binding created"() {
when:
- Map<String, Map> binder = schema(group, false)
- Map<String, Map> generated = schema(group, true)
+ Map<String, Map> generated = schema(group)
- then: "the indexes and keys of every table are the binder's (the binder leaves an unused column in the table of a map of values)"
- generated.keySet() == binder.keySet()
- generated.collectEntries { String name, Map description -> [(name): [description.indexes, description.uniqueKeys]] } ==
- binder.collectEntries { String name, Map description -> [(name): [description.indexes, description.uniqueKeys]] }
+ then: "the tables, and the indexes and keys of the collection table, are the ones classic binding created"
+ generated.keySet() == tables as Set
generated[table].indexes == indexes
+ generated[table].uniqueKeys == uniqueKeys
+ generated.findAll { String name, Map description -> name != table }.every { String name, Map description -> description.indexes.isEmpty() }
where:
- label | group | table | indexes
- 'a set of strings' | [CcsSetIdx] | 'ccs_set_idx_tags' | [ccs_tags_idx: ['ccs_set_idx_id']]
- 'a set, with true' | [CcsIndexTrue] | 'ccs_index_true_tags' | [ccs_index_true_tags_ccs_index_true_id_idx: ['ccs_index_true_id']]
- 'a set, with two names' | [CcsIndexMulti] | 'ccs_index_multi_tags' | [ccs_a: ['ccs_index_multi_id'], ccs_b: ['ccs_index_multi_id']]
- 'a set, with false' | [CcsIndexFalse] | 'ccs_index_false_tags' | [:]
- 'a set of enums, over the element too' | [CcsEnumIdx] | 'ccs_enum_idx_colors' | [ccs_color_idx: ['ccs_color', 'ccs_enum_idx_id']]
- 'a list, which names its index column' | [CcsListIdx] | 'ccs_list_idx_items' | [ccs_items_idx: ['ccs_list_idx_id']]
- 'a map' | [CcsMapIdx] | 'ccs_map_idx_attrs' | [ccs_attrs_idx: ['ccs_map_idx_id']]
- 'a map, with the settings of the index column' | [CcsMapSettings] | 'ccs_map_settings_attrs' | ['[column:ccs_k': ['ccs_map_settings_id'], 'type:string]': ['ccs_map_settings_id']]
- 'a list of long, with the settings of the index column' | [CcsListSettings] | 'ccs_list_settings_items' | ['[column:ccs_ix': ['ccs_list_settings_id'], 'type:long]': ['ccs_list_settings_id']]
- 'a one-to-many through a join table' | [CcsKidOwner, CcsKid] | 'ccs_kid_owner_ccs_kid' | [ccs_kids_idx: ['ccs_kid_owner_kids_id']]
- 'a many-to-many, on both sides' | [CcsLeft, CcsRight] | 'ccs_left_rights' | [ccs_right_idx: ['ccs_right_id'], ccs_left_idx: ['ccs_left_id']]
- 'a collection with a mapped join key' | [CcsJoinKey] | 'ccs_tags_table' | [:]
- 'a one-to-many mapped by a foreign key' | [CcsParent, CcsChild] | 'ccs_child' | [:]
+ label | group | tables | table | indexes | uniqueKeys
+ 'a set of strings' | [CcsSetIdx] | ['ccs_set_idx', 'ccs_set_idx_tags'] | 'ccs_set_idx_tags' | [ccs_tags_idx: ['ccs_set_idx_id']] | [['ccs_set_idx_id', 'tags_java_lang_string']]
+ 'a set, with true' | [CcsIndexTrue] | ['ccs_index_true', 'ccs_index_true_tags'] | 'ccs_index_true_tags' | [ccs_index_true_tags_ccs_index_true_id_idx: ['ccs_index_true_id']] | [['ccs_index_true_id', 'tags_java_lang_string']]
+ 'a set, with two names' | [CcsIndexMulti] | ['ccs_index_multi', 'ccs_index_multi_tags'] | 'ccs_index_multi_tags' | [ccs_a: ['ccs_index_multi_id'], ccs_b: ['ccs_index_multi_id']] | [['ccs_index_multi_id', 'tags_java_lang_string']]
+ 'a set, with false' | [CcsIndexFalse] | ['ccs_index_false', 'ccs_index_false_tags'] | 'ccs_index_false_tags' | [:] | [['ccs_index_false_id', 'tags_java_lang_string']]
+ 'a set of enums, over the element too' | [CcsEnumIdx] | ['ccs_enum_idx', 'ccs_enum_idx_colors'] | 'ccs_enum_idx_colors' | [ccs_color_idx: ['ccs_color', 'ccs_enum_idx_id']] | [['ccs_color', 'ccs_enum_idx_id']]
+ 'a list, which names its index column' | [CcsListIdx] | ['ccs_list_idx', 'ccs_list_idx_items'] | 'ccs_list_idx_items' | [ccs_items_idx: ['ccs_list_idx_id']] | []
+ 'a map' | [CcsMapIdx] | ['ccs_map_idx', 'ccs_map_idx_attrs'] | 'ccs_map_idx_attrs' | [ccs_attrs_idx: ['ccs_map_idx_id']] | []
+ 'a map, with the settings of the index column' | [CcsMapSettings] | ['ccs_map_settings', 'ccs_map_settings_attrs'] | 'ccs_map_settings_attrs' | ['[column:ccs_k': ['ccs_map_settings_id'], 'type:string]': ['ccs_map_settings_id']] | []
+ 'a list of long, with the settings of the index column' | [CcsListSettings] | ['ccs_list_settings', 'ccs_list_settings_items'] | 'ccs_list_settings_items' | ['[column:ccs_ix': ['ccs_list_settings_id'], 'type:long]': ['ccs_list_settings_id']] | []
+ 'a one-to-many through a join table' | [CcsKidOwner, CcsKid] | ['ccs_kid', 'ccs_kid_owner', 'ccs_kid_owner_ccs_kid'] | 'ccs_kid_owner_ccs_kid' | [ccs_kids_idx: ['ccs_kid_owner_kids_id']] | [['ccs_kid_id', 'ccs_kid_owner_kids_id']]
+ 'a many-to-many, on both sides' | [CcsLeft, CcsRight] | ['ccs_left', 'ccs_left_rights', 'ccs_right'] | 'ccs_left_rights' | [ccs_right_idx: ['ccs_right_id'], ccs_left_idx: ['ccs_left_id']] | []
+ 'a collection with a mapped join key' | [CcsJoinKey] | ['ccs_join_key', 'ccs_tags_table'] | 'ccs_tags_table' | [:] | [['owner_fk', 'tag_value']]
+ 'a one-to-many mapped by a foreign key' | [CcsParent, CcsChild] | ['ccs_child', 'ccs_parent'] | 'ccs_child' | [:] | []
}
void "the indexes are created in the database, over the key column of the collection table"() {
when:
- boot([CcsSetIdx, CcsEnumIdx], true)
+ boot([CcsSetIdx, CcsEnumIdx])
then:
h2Indexes('ccs_set_idx_tags') == ['ccs_tags_idx']
@@ -130,21 +128,17 @@ class GeneratedDomainClassesCollectionConstraintsSpec extends Specification {
void "a closure mapped as the index names no index, as its name would be the closure's own, which differs on every boot"() {
when:
- Map<String, Map> binder = schema([CcsClosureIdx], false)
- Map<String, Map> generated = schema([CcsClosureIdx], true)
+ Map<String, Map> generated = schema([CcsClosureIdx])
- then: "both name the index column after the closure, and only the binder creates an index, named after the closure instance"
- generated['ccs_closure_idx_items'].columns == binder['ccs_closure_idx_items'].columns
- generated['ccs_closure_idx_items'].columns.keySet().contains('ccs_cx')
+ then: "the index column is named by the closure, and no index is created (classic binding created one named after the closure instance)"
+ generated['ccs_closure_idx_items'].columns.keySet() == ['ccs_cx', 'ccs_closure_idx_id', 'items_java_lang_string'] as Set
generated['ccs_closure_idx_items'].indexes.isEmpty()
- binder['ccs_closure_idx_items'].indexes.size() == 1
- binder['ccs_closure_idx_items'].indexes.keySet().first().contains('closure')
}
@Unroll
void "a unique group mapped on #label creates no key, since the collection table does not hold the columns of the group"() {
when:
- Map<String, Map> generated = schema(group, true)
+ Map<String, Map> generated = schema(group)
then: "the owner's table has no key either, and the table of the collection holds the keys of the set only"
generated[owner].uniqueKeys.isEmpty()
@@ -160,7 +154,7 @@ class GeneratedDomainClassesCollectionConstraintsSpec extends Specification {
void "a collection with a unique group and an index saves and loads, and the group does not reject a repeated value"() {
given:
- boot([CcsUqGroup, CcsSetIdx], true)
+ boot([CcsUqGroup, CcsSetIdx])
when:
Long id = CcsUqGroup.withTransaction {
@@ -181,7 +175,7 @@ class GeneratedDomainClassesCollectionConstraintsSpec extends Specification {
void "a list, a map and a one-to-many with an index save, reload and are found through queries"() {
given:
- boot([CcsListIdx, CcsMapIdx, CcsKidOwner, CcsKid, CcsLeft, CcsRight], true)
+ boot([CcsListIdx, CcsMapIdx, CcsKidOwner, CcsKid, CcsLeft, CcsRight])
when:
Long listId = CcsListIdx.withTransaction { new CcsListIdx(items: ['a', 'b', 'c']).save(failOnError: true, flush: true).id }
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCollectionIndexTypeSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCollectionIndexTypeSpec.groovy
index d30cb11fad..e67247b814 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCollectionIndexTypeSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCollectionIndexTypeSpec.groovy
@@ -30,9 +30,10 @@ import org.grails.orm.hibernate.HibernateDatastore
/**
* The index column of a list and the key column of a map are typed by the mapping ({@code indexColumn: [type: 'long']}, or the
- * {@code type} of the {@code index:} settings), independently of the declared key class, and the domain binder gives them that
- * type. The generated classes state it with Hibernate's own annotations, so a database created by the binder keeps its schema and
- * the keys of a map are read back as the type the column holds.
+ * {@code type} of the {@code index:} settings), independently of the declared key class, and the classic binding of Grails 8 gave
+ * them that type. The generated classes state it with Hibernate's own annotations, so a database created by Grails 8 keeps its schema
+ * (the tables and keys stated here are the ones classic binding created) and the keys of a map are read back as the type the column
+ * holds.
*/
class GeneratedDomainClassesCollectionIndexTypeSpec extends Specification {
@@ -41,19 +42,18 @@ class GeneratedDomainClassesCollectionIndexTypeSpec extends Specification {
@AutoCleanup
HibernateDatastore datastore
- private HibernateDatastore boot(List<Class> group, boolean generated) {
+ private HibernateDatastore boot(List<Class> group) {
datastore?.close()
datastore = new HibernateDatastore([
- 'dataSource.url' : "jdbc:h2:mem:cit${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
- 'dataSource.dbCreate' : 'create-drop',
- 'hibernate.generatedDomainClasses': generated,
+ 'dataSource.url' : "jdbc:h2:mem:cit${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
+ 'dataSource.dbCreate': 'create-drop',
], group as Class[])
return datastore
}
/** The collection tables of the boot model as plain data: every column with its SQL type, nullability and length. */
- private Map<String, Map> schema(List<Class> group, boolean generated) {
- HibernateDatastore booted = boot(group, generated)
+ private Map<String, Map> schema(List<Class> group) {
+ HibernateDatastore booted = boot(group)
Map<String, Map> result = new TreeMap<String, Map>()
for (Table table : booted.metadata.collectTableMappings()) {
if (table.physicalTable) {
@@ -71,31 +71,29 @@ class GeneratedDomainClassesCollectionIndexTypeSpec extends Specification {
}
@Unroll
- void "#label is typed in the generated mode as the domain binder types it"() {
+ void "#label is typed as classic binding typed it"() {
when:
- Map<String, Map> binder = schema(group, false)
- Map<String, Map> generated = schema(group, true)
+ Map<String, Map> generated = schema(group)
- then: "the column and the key it is part of are the binder's (the binder leaves an unused column in the table of a map of values)"
- binder[table].columns[column] == type
+ then: "the column and the key it is part of are the ones classic binding created"
generated[table].columns[column] == type
- generated[table].primaryKey == binder[table].primaryKey
- generated.keySet() == binder.keySet()
+ generated[table].primaryKey == primaryKey
+ generated.keySet() == tables as Set
where:
- label | group | table | column | type
- 'the key of a map of entities, mapped as long' | [CitLongMap, CitValue] | 'cit_long_map_tags' | 'tags_idx' | 'long not null'
- 'the key of a map of values, mapped as long' | [CitValueMap] | 'cit_value_map_attrs' | 'k' | 'long not null'
- 'the key of a map, mapped as integer and named' | [CitIntegerMap] | 'cit_integer_map_attrs' | 'k' | 'integer not null'
- 'the key of a map, with a length' | [CitLengthMap] | 'cit_length_map_attrs' | 'k' | 'varchar(40) not null'
- 'the index of a list, mapped as long' | [CitLongList] | 'cit_long_list_items' | 'ix' | 'bigint not null'
- 'the index of a list, mapped as string' | [CitStringList] | 'cit_string_list_items' | 'ix' | 'varchar(255) not null'
- 'the index of a list of entities, mapped as long' | [CitEntityList, CitValue] | 'cit_entity_list_cit_value' | 'ix' | 'bigint not null'
+ label | group | tables | table | column | type | primaryKey
+ 'the key of a map of entities, mapped as long' | [CitLongMap, CitValue] | ['cit_long_map', 'cit_long_map_tags', 'cit_value'] | 'cit_long_map_tags' | 'tags_idx' | 'long not null' | ['cit_long_map_tags_id', 'tags_idx']
+ 'the key of a map of values, mapped as long' | [CitValueMap] | ['cit_value_map', 'cit_value_map_attrs'] | 'cit_value_map_attrs' | 'k' | 'long not null' | ['cit_value_map_id', 'k']
+ 'the key of a map, mapped as integer and named' | [CitIntegerMap] | ['cit_integer_map', 'cit_integer_map_attrs'] | 'cit_integer_map_attrs' | 'k' | 'integer not null' | ['cit_integer_map_id', 'k']
+ 'the key of a map, with a length' | [CitLengthMap] | ['cit_length_map', 'cit_length_map_attrs'] | 'cit_length_map_attrs' | 'k' | 'varchar(40) not null' | ['cit_length_map_id', 'k']
+ 'the index of a list, mapped as long' | [CitLongList] | ['cit_long_list', 'cit_long_list_items'] | 'cit_long_list_items' | 'ix' | 'bigint not null' | ['cit_long_list_id', 'ix']
+ 'the index of a list, mapped as string' | [CitStringList] | ['cit_string_list', 'cit_string_list_items'] | 'cit_string_list_items' | 'ix' | 'varchar(255) not null' | ['cit_string_list_id', 'ix']
+ 'the index of a list of entities, mapped as long' | [CitEntityList, CitValue] | ['cit_entity_list', 'cit_entity_list_cit_value', 'cit_value'] | 'cit_entity_list_cit_value' | 'ix' | 'bigint not null' | ['cit_entity_list_values_id', 'ix']
}
void "a map keyed by long saves, reloads and is queried with the keys the column holds"() {
given:
- boot([CitLongMap, CitValue], true)
+ boot([CitLongMap, CitValue])
when:
Long id = CitLongMap.withTransaction {
@@ -113,7 +111,7 @@ class GeneratedDomainClassesCollectionIndexTypeSpec extends Specification {
void "the index of a list mapped as long keeps the order of the elements"() {
given:
- boot([CitLongList, CitStringList], true)
+ boot([CitLongList, CitStringList])
when:
Long longId = CitLongList.withTransaction { new CitLongList(items: ['c', 'a', 'b']).save(failOnError: true, flush: true).id }
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCollectionSortSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCollectionSortSpec.groovy
index 86b1c5f7c7..075617211d 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCollectionSortSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCollectionSortSpec.groovy
@@ -28,9 +28,10 @@ import spock.lang.Unroll
import org.grails.orm.hibernate.HibernateDatastore
/**
- * The default {@code sort} of a bidirectional {@code hasMany}. The domain binder orders a set and a map by the property, also when it
- * is an association (it orders by the foreign key), and a list stays in the order of its index column, so the sort changes nothing for
- * it. The generated mode accepts all three the same way instead of refusing the list, the map and the sort by an association.
+ * The default {@code sort} of a bidirectional {@code hasMany}. A set and a map are ordered by the property, also when it is an
+ * association (by the foreign key), and a list stays in the order of its index column, so the sort changes nothing for it, which is
+ * what the classic binding of Grails 8 did; native binding accepts all three the same way instead of refusing the list, the map and
+ * the sort by an association. The orders stated here are the ones classic binding gave.
*/
class GeneratedDomainClassesCollectionSortSpec extends Specification {
@@ -39,27 +40,23 @@ class GeneratedDomainClassesCollectionSortSpec extends Specification {
@AutoCleanup
HibernateDatastore datastore
- private HibernateDatastore boot(List<Class> group, boolean generated) {
+ private HibernateDatastore boot(List<Class> group) {
datastore?.close()
datastore = new HibernateDatastore([
- 'dataSource.url' : "jdbc:h2:mem:gcs${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
- 'dataSource.dbCreate' : 'create-drop',
- 'hibernate.generatedDomainClasses': generated,
+ 'dataSource.url' : "jdbc:h2:mem:gcs${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
+ 'dataSource.dbCreate': 'create-drop',
], group as Class[])
return datastore
}
@Unroll
- void "#label: the elements come back in the same order in both modes"() {
+ void "#label: the elements come back in the order classic binding gave them"() {
when:
- Map<Boolean, Object> results = [false, true].collectEntries { boolean generated ->
- boot(group, generated)
- [(generated): this."${cycle}"()]
- }
+ boot(group)
+ Object results = this."${cycle}"()
then:
- results[true] == results[false]
- results[true] == expected
+ results == expected
where:
label | group | cycle | expected
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCollectionTypeSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCollectionTypeSpec.groovy
index 3e1114f7d1..67bd9b796b 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCollectionTypeSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCollectionTypeSpec.groovy
@@ -34,10 +34,11 @@ import spock.lang.Unroll
import org.grails.orm.hibernate.HibernateDatastore
/**
- * A {@code type} mapped on a collection property. The domain binder keeps the collection a collection only when the type is
- * neither a class that is not a collection type nor {@code serializable}: those two make the property one column of the owner's
- * table, typed with the user type or serialized, with the index, the unique group and the column settings of any other column. A
- * type name Hibernate knows ({@code text}) makes the binder fail to boot, and on a collection of entities it changes nothing.
+ * A {@code type} mapped on a collection property. As with the classic binding of Grails 8, the collection stays a collection only
+ * when the type is neither a class that is not a collection type nor {@code serializable}: those two make the property one column of
+ * the owner's table, typed with the user type or serialized, with the index, the unique group and the column settings of any other
+ * column. A type name Hibernate knows ({@code text}) is refused (classic binding failed to boot it), and on a collection of entities it
+ * changes nothing. The columns stated here are the ones classic binding created.
*/
class GeneratedDomainClassesCollectionTypeSpec extends Specification {
@@ -46,19 +47,18 @@ class GeneratedDomainClassesCollectionTypeSpec extends Specification {
@AutoCleanup
HibernateDatastore datastore
- private HibernateDatastore boot(List<Class> group, boolean generated) {
+ private HibernateDatastore boot(List<Class> group) {
datastore?.close()
datastore = new HibernateDatastore([
- 'dataSource.url' : "jdbc:h2:mem:cts${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
- 'dataSource.dbCreate' : 'create-drop',
- 'hibernate.generatedDomainClasses': generated,
+ 'dataSource.url' : "jdbc:h2:mem:cts${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
+ 'dataSource.dbCreate': 'create-drop',
], 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(List<Class> group, boolean generated) {
- HibernateDatastore booted = boot(group, generated)
+ private Map<String, Map> schema(List<Class> group) {
+ HibernateDatastore booted = boot(group)
Map<String, Map> result = new TreeMap<String, Map>()
for (Table table : booted.metadata.collectTableMappings()) {
if (table.physicalTable) {
@@ -77,13 +77,11 @@ class GeneratedDomainClassesCollectionTypeSpec extends Specification {
}
@Unroll
- void "#label is one column of the owner's table, as the domain binder binds it"() {
+ void "#label is one column of the owner's table, as classic binding bound it"() {
when:
- Map<String, Map> binder = schema(group, false)
- Map<String, Map> generated = schema(group, true)
+ Map<String, Map> generated = schema(group)
then:
- generated == binder
generated.keySet() == tables as Set
generated[table].columns[column] == type
@@ -101,9 +99,9 @@ class GeneratedDomainClassesCollectionTypeSpec extends Specification {
'a set with a user type, an index and a unique group' | [CtsUserTypeKeys] | ['cts_user_type_keys'] | 'cts_user_type_keys' | 'tags' | 'varchar(255)'
}
- void "the index and the unique group of a collection stored in one column are on the owner's table, where the binder creates them"() {
+ void "the index and the unique group of a collection stored in one column are on the owner's table, where classic binding created them"() {
when:
- Map<String, Map> generated = schema([CtsSerializableKeys, CtsUserTypeKeys], true)
+ Map<String, Map> generated = schema([CtsSerializableKeys, CtsUserTypeKeys])
then:
generated['cts_serializable_keys'].indexes == [cts_ser_idx: ['tags']]
@@ -114,7 +112,7 @@ class GeneratedDomainClassesCollectionTypeSpec extends Specification {
void "a collection with a user type is stored with the user type and read back"() {
given:
- boot([CtsUserTypeSet, CtsUserTypeList], true)
+ boot([CtsUserTypeSet, CtsUserTypeList])
when:
Long setId = CtsUserTypeSet.withTransaction { new CtsUserTypeSet(tags: ['a', 'b'] as Set).save(failOnError: true, flush: true).id }
@@ -131,7 +129,7 @@ class GeneratedDomainClassesCollectionTypeSpec extends Specification {
@Unroll
void "a serializable #label is stored in one column, read back and updated"() {
given:
- boot(group, true)
+ boot(group)
when:
Long id = type.withTransaction { type.newInstance("${property}": initial).save(failOnError: true, flush: true).id }
@@ -148,10 +146,9 @@ class GeneratedDomainClassesCollectionTypeSpec extends Specification {
'enums' | [CtsSerializableEnums] | CtsSerializableEnums | 'colors' | [CtsTypeColor.RED] as Set | [CtsTypeColor.GREEN] as Set
}
- void "a type mapped on a collection of entities changes nothing in both bindings"() {
+ void "a type mapped on a collection of entities changes nothing"() {
when:
- Map<String, Map> binder = schema([CtsEntityTyped, CtsKid], false)
- Map<String, Map> generated = schema([CtsEntityTyped, CtsKid], true)
+ Map<String, Map> generated = schema([CtsEntityTyped, CtsKid])
Long id = CtsEntityTyped.withTransaction {
CtsEntityTyped owner = new CtsEntityTyped()
owner.addToKids(new CtsKid(name: 'k'))
@@ -159,21 +156,14 @@ class GeneratedDomainClassesCollectionTypeSpec extends Specification {
}
then: "the collection stays a join table"
- generated == binder
- generated.keySet().contains('cts_entity_typed_cts_kid')
+ generated.keySet() == ['cts_entity_typed', 'cts_entity_typed_cts_kid', 'cts_kid'] as Set
CtsEntityTyped.withNewSession { CtsEntityTyped.get(id).kids*.name } == ['k']
}
@Unroll
- void "a #label cannot be bound by the domain binder, and the generated mode says why instead of binding something else"() {
+ void "a #label is refused by name, as classic binding could not bind it either"() {
when:
- boot(group, false)
-
- then: "the binder fails to boot"
- thrown(Exception)
-
- when:
- boot(group, true)
+ boot(group)
then:
Exception e = thrown()
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCompositeCollectionSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCompositeCollectionSpec.groovy
index b7f94351e4..991d84564f 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCompositeCollectionSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCompositeCollectionSpec.groovy
@@ -30,10 +30,10 @@ import org.grails.orm.hibernate.HibernateDatastore
/**
* Many-to-many associations and maps of entities that involve an entity with a composite identifier, and foreign keys to a composite
- * identifier that the mapping gives fewer columns than the identifier has properties. The domain binder boots them: it gives the join
- * table a key column for each identifier property of the owner and an element column for each one of the target, names the columns the
- * mapping states in order and names the missing ones as it would have named all of them. The generated mode describes the same tables
- * and columns instead of refusing the mapping.
+ * identifier that the mapping gives fewer columns than the identifier has properties. The classic binding of Grails 8 booted them: it
+ * gave the join table a key column for each identifier property of the owner and an element column for each one of the target, named
+ * the columns the mapping states in order and named the missing ones as it would have named all of them. Native binding describes the
+ * same tables and columns, stated here, instead of refusing the mapping.
*/
class GeneratedDomainClassesCompositeCollectionSpec extends Specification {
@@ -42,19 +42,18 @@ class GeneratedDomainClassesCompositeCollectionSpec extends Specification {
@AutoCleanup
HibernateDatastore datastore
- private HibernateDatastore boot(List<Class> group, boolean generated) {
+ private HibernateDatastore boot(List<Class> group) {
datastore?.close()
datastore = new HibernateDatastore([
- 'dataSource.url' : "jdbc:h2:mem:gcc${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
- 'dataSource.dbCreate' : 'create-drop',
- 'hibernate.generatedDomainClasses': generated,
+ 'dataSource.url' : "jdbc:h2:mem:gcc${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
+ 'dataSource.dbCreate': 'create-drop',
], group as Class[])
return datastore
}
/** The tables of the boot model: columns with type and nullability (a primary key column is not null), primary key and foreign keys. */
- private Map<String, Map> schema(List<Class> group, boolean generated) {
- HibernateDatastore booted = boot(group, generated)
+ private Map<String, Map> schema(List<Class> group) {
+ HibernateDatastore booted = boot(group)
Map<String, Map> result = new TreeMap<String, Map>()
for (Table table : booted.metadata.collectTableMappings()) {
if (table.physicalTable) {
@@ -72,13 +71,11 @@ class GeneratedDomainClassesCompositeCollectionSpec extends Specification {
}
@Unroll
- void "#label: the generated mode creates the tables and columns of the domain binder"() {
+ void "#label: the tables and columns of classic binding are created"() {
when:
- Map<String, Map> binder = schema(group, false)
- Map<String, Map> generated = schema(group, true)
+ Map<String, Map> generated = schema(group)
then:
- generated == binder
generated[table].columns.keySet() == columns as Set
where:
@@ -94,16 +91,13 @@ class GeneratedDomainClassesCompositeCollectionSpec extends Specification {
}
@Unroll
- void "#label: the rows are stored, read back, changed and deleted in both modes"() {
+ void "#label: the rows are stored, read back, changed and deleted"() {
when:
- Map<Boolean, List> results = [false, true].collectEntries { boolean generated ->
- boot(group, generated)
- [(generated): this."${cycle}"()]
- }
+ boot(group)
+ List results = this."${cycle}"()
then:
- results[true] == results[false]
- results[true] == expected
+ results == expected
where:
label | group | cycle | expected
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesContributorSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesContributorSpec.groovy
index 339869a0a3..22c20cb62f 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesContributorSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesContributorSpec.groovy
@@ -32,9 +32,9 @@ import org.grails.datastore.mapping.core.DatastoreUtils
import org.grails.orm.hibernate.HibernateDatastore
/**
- * A contributor that runs after the domain binder, such as Hibernate Envers building the audit mappings, reads the entities
- * bound so far. The generated classes are bound when the domain binder runs, with their second passes, so that such a
- * contributor finds the same bound model whether the domain binder or the generated classes bound the entities.
+ * A contributor that runs after GORM's mapping contributor, such as Hibernate Envers building the audit mappings, reads the
+ * entities bound so far. The generated classes are bound when GORM's contributor runs, with their second passes, so that such a
+ * contributor finds the bound model complete, as it did with the classic binding of Grails 8.
*/
class GeneratedDomainClassesContributorSpec extends Specification {
@@ -50,29 +50,23 @@ class GeneratedDomainClassesContributorSpec extends Specification {
datastore?.close()
}
- private HibernateDatastore boot(boolean generated) {
+ private HibernateDatastore boot() {
datastore = new HibernateDatastore(
DatastoreUtils.createPropertyResolver([
- 'dataSource.url' : "jdbc:h2:mem:gdcContributor${generated};LOCK_TIMEOUT=10000".toString(),
- 'dataSource.dbCreate' : 'create-drop',
- 'hibernate.generatedDomainClasses': generated,
+ 'dataSource.url' : 'jdbc:h2:mem:gdcContributor;LOCK_TIMEOUT=10000',
+ 'dataSource.dbCreate': 'create-drop',
]), GdcContributorShelf, GdcContributorItem)
}
- def "a contributor sees the bound entities, with their collections complete, in #mode mode"() {
+ def "a contributor sees the bound entities, with their collections complete"() {
when:
- boot(generated)
+ boot()
then: 'the entities are bound under the domain class names'
RecordingMappingContributor.seen.keySet() == [GdcContributorShelf.name, GdcContributorItem.name].toSet()
and: 'the collection of the owner has its element and key'
RecordingMappingContributor.seen[GdcContributorShelf.name] == ['items:true']
-
- where:
- generated | mode
- true | 'generated'
- false | 'binder'
}
}
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesConverterClassSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesConverterClassSpec.groovy
index b60528dae5..927e716a76 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesConverterClassSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesConverterClassSpec.groovy
@@ -32,9 +32,9 @@ import spock.lang.Unroll
import org.grails.orm.hibernate.HibernateDatastore
/**
- * A {@code type} that names an {@code AttributeConverter} class, such as {@code org.hibernate.type.YesNoConverter}. The domain binder
- * converts the property with it, whatever the class of the property is, and also when the property is a {@code hasMany} stored in one
- * column. The generated mode boots with the same schema and converts the same way.
+ * A {@code type} that names an {@code AttributeConverter} class, such as {@code org.hibernate.type.YesNoConverter}. The property is
+ * converted with it, whatever the class of the property is, and also when the property is a {@code hasMany} stored in one column, as
+ * the classic binding of Grails 8 did; the columns and the stored values stated here are the ones classic binding gave.
*/
class GeneratedDomainClassesConverterClassSpec extends Specification {
@@ -43,12 +43,11 @@ class GeneratedDomainClassesConverterClassSpec extends Specification {
@AutoCleanup
HibernateDatastore datastore
- private HibernateDatastore boot(List<Class> group, boolean generated) {
+ private HibernateDatastore boot(List<Class> group) {
datastore?.close()
datastore = new HibernateDatastore([
- 'dataSource.url' : "jdbc:h2:mem:tns${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
- 'dataSource.dbCreate' : 'create-drop',
- 'hibernate.generatedDomainClasses': generated,
+ 'dataSource.url' : "jdbc:h2:mem:tns${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
+ 'dataSource.dbCreate': 'create-drop',
], group as Class[])
return datastore
}
@@ -106,13 +105,11 @@ class GeneratedDomainClassesConverterClassSpec extends Specification {
}
@Unroll
- void "#label has the column type the domain binder gives it"() {
+ void "#label has the column type classic binding gave it"() {
when:
- Map<String, Map> binder = schema(boot(group, false))
- Map<String, Map> generated = schema(boot(group, true))
+ Map<String, Map> generated = schema(boot(group))
then:
- generated == binder
generated[table].columns[column] == type
where:
@@ -124,11 +121,9 @@ class GeneratedDomainClassesConverterClassSpec extends Specification {
void "a boolean converted by an attribute converter is stored as the converter says and read back"() {
when:
- Map binder = roundTrip(boot([TnConvertedBoolean], false), TnConvertedBoolean, [flag: true], 'flag', 'select flag from tn_converted_boolean')
- Map generated = roundTrip(boot([TnConvertedBoolean], true), TnConvertedBoolean, [flag: true], 'flag', 'select flag from tn_converted_boolean')
+ Map generated = roundTrip(boot([TnConvertedBoolean]), TnConvertedBoolean, [flag: true], 'flag', 'select flag from tn_converted_boolean')
then:
- generated == binder
generated == [stored: [['Y']], reloaded: true]
and: "a query on the property converts its parameter"
@@ -136,22 +131,15 @@ class GeneratedDomainClassesConverterClassSpec extends Specification {
TnConvertedBoolean.withNewSession { TnConvertedBoolean.findAllByFlag(false) } == []
}
- void "an attribute converter on a property of a class it does not convert is accepted by both bindings and fails the same way when used"() {
+ void "an attribute converter on a property of a class it does not convert is accepted, as classic binding accepted it, and fails when used"() {
+ given:
+ boot([TnConvertedString])
+
when:
- Map<Boolean, String> outcome = [false, true].collectEntries { boolean generated ->
- boot([TnConvertedString], generated)
- String result
- try {
- TnConvertedString.withTransaction { new TnConvertedString(data: 'Y').save(failOnError: true, flush: true) }
- result = 'saved'
- } catch (Throwable e) {
- result = 'failed'
- }
- [(generated): result]
- }
+ TnConvertedString.withTransaction { new TnConvertedString(data: 'Y').save(failOnError: true, flush: true) }
- then:
- outcome[true] == outcome[false]
+ then: "Hibernate refuses the value (an AssertionError of its converter resolution), as it did with classic binding"
+ thrown(Throwable)
}
}
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCustomCollectionTypeSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCustomCollectionTypeSpec.groovy
index b30afd70e3..d450d2b16a 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCustomCollectionTypeSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesCustomCollectionTypeSpec.groovy
@@ -34,9 +34,9 @@ import spock.lang.Specification
import org.grails.orm.hibernate.HibernateDatastore
/**
- * A custom collection type ({@code UserCollectionType}) as the {@code type} of a {@code hasMany}. On a collection of domain classes both
- * bindings boot with the same schema; the domain binder never uses the class, the generated mode applies it. On a collection of basic
- * values the domain binder does not boot.
+ * A custom collection type ({@code UserCollectionType}) as the {@code type} of a {@code hasMany}. On a collection of domain classes the
+ * schema is the one the classic binding of Grails 8 created, and the type is applied (classic binding named it to Hibernate in a way
+ * Hibernate never used). On a collection of basic values the mapping is refused by name, as classic binding did not boot it.
*/
class GeneratedDomainClassesCustomCollectionTypeSpec extends Specification {
@@ -45,12 +45,11 @@ class GeneratedDomainClassesCustomCollectionTypeSpec extends Specification {
@AutoCleanup
HibernateDatastore datastore
- private HibernateDatastore boot(List<Class> group, boolean generated) {
+ private HibernateDatastore boot(List<Class> group) {
datastore?.close()
datastore = new HibernateDatastore([
- 'dataSource.url' : "jdbc:h2:mem:tns${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
- 'dataSource.dbCreate' : 'create-drop',
- 'hibernate.generatedDomainClasses': generated,
+ 'dataSource.url' : "jdbc:h2:mem:tns${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
+ 'dataSource.dbCreate': 'create-drop',
], group as Class[])
return datastore
}
@@ -74,46 +73,31 @@ class GeneratedDomainClassesCustomCollectionTypeSpec extends Specification {
return result
}
- void "a custom collection type on a collection of entities is a table in both bindings, and only the generated mode puts the custom type to use"() {
+ void "a custom collection type on a collection of entities is a join table, and the custom type is put to use"() {
when:
- Map<Boolean, Map> observed = [false, true].collectEntries { boolean generated ->
- TnSetCollectionType.CREATED.set(0)
- TnSetCollectionType.WRAPS.set(0)
- HibernateDatastore booted = boot([TnCollectionOwner, TnCollectionKid], generated)
- Long id = TnCollectionOwner.withTransaction {
- TnCollectionOwner owner = new TnCollectionOwner(name: 'o')
- owner.addToKids(new TnCollectionKid(name: 'a'))
- owner.addToKids(new TnCollectionKid(name: 'b'))
- owner.save(failOnError: true, flush: true).id
- }
- Map result = TnCollectionOwner.withNewSession {
- [kids: TnCollectionOwner.get(id).kids*.name.sort()]
- }
- result.schema = schema(booted)
- result.customTypeUsed = TnSetCollectionType.CREATED.get() > 0 && TnSetCollectionType.WRAPS.get() > 0
- [(generated): result]
+ TnSetCollectionType.CREATED.set(0)
+ TnSetCollectionType.WRAPS.set(0)
+ HibernateDatastore booted = boot([TnCollectionOwner, TnCollectionKid])
+ Long id = TnCollectionOwner.withTransaction {
+ TnCollectionOwner owner = new TnCollectionOwner(name: 'o')
+ owner.addToKids(new TnCollectionKid(name: 'a'))
+ owner.addToKids(new TnCollectionKid(name: 'b'))
+ owner.save(failOnError: true, flush: true).id
}
+ List<String> kids = TnCollectionOwner.withNewSession { TnCollectionOwner.get(id).kids*.name.sort() }
- then: "the schema and the data are the same"
- observed[true].schema == observed[false].schema
- observed[true].kids == ['a', 'b']
- observed[false].kids == ['a', 'b']
- observed[true].schema.keySet().containsAll(['tn_collection_owner', 'tn_collection_kid', 'tn_collection_owner_tn_collection_kid'])
+ then: "the schema is the one classic binding created, and the data is read back"
+ schema(booted).keySet() == ['tn_collection_owner', 'tn_collection_kid', 'tn_collection_owner_tn_collection_kid'] as Set
+ kids == ['a', 'b']
- and: "the domain binder names the custom type to Hibernate in a way Hibernate never uses, so it silently keeps its own set; the generated mode applies the type the mapping names"
- !observed[false].customTypeUsed
- observed[true].customTypeUsed
+ and: "the type the mapping names is applied (classic binding named it to Hibernate in a way Hibernate never used)"
+ TnSetCollectionType.CREATED.get() > 0
+ TnSetCollectionType.WRAPS.get() > 0
}
- void "a custom collection type on a collection of basic values is not accepted by the domain binder, and the generated mode says why"() {
- when:
- boot([TnCollectionBasic], false)
-
- then:
- thrown(Exception)
-
+ void "a custom collection type on a collection of basic values is refused by name, as classic binding did not boot it"() {
when:
- boot([TnCollectionBasic], true)
+ boot([TnCollectionBasic])
then:
Exception e = thrown()
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesDiscriminatorSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesDiscriminatorSpec.groovy
index 7704a63684..edc5302251 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesDiscriminatorSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesDiscriminatorSpec.groovy
@@ -31,8 +31,8 @@ import org.grails.orm.hibernate.HibernateDatastore
/**
* A discriminator column with a precision or a scale, and a discriminator of a type other than string, integer or character.
* {@code @DiscriminatorColumn} cannot state either. The precision and the scale change nothing in the DDL of a string or an integer
- * column, but the domain binder puts them on the column, and a mapping that sets them must boot in the generated mode as it does in the
- * domain binder, with the same column. A discriminator typed {@code 'long'} is a bigint column in both.
+ * column, but the classic binding of Grails 8 put them on the column, and a mapping that sets them boots with the same column. A
+ * discriminator typed {@code 'long'} is a bigint column, as it was. The columns stated here are the ones classic binding created.
*/
class GeneratedDomainClassesDiscriminatorSpec extends Specification {
@@ -41,19 +41,18 @@ class GeneratedDomainClassesDiscriminatorSpec extends Specification {
@AutoCleanup
HibernateDatastore datastore
- private HibernateDatastore boot(List<Class> group, boolean generated) {
+ private HibernateDatastore boot(List<Class> group) {
datastore?.close()
datastore = new HibernateDatastore([
- 'dataSource.url' : "jdbc:h2:mem:gdd${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
- 'dataSource.dbCreate' : 'create-drop',
- 'hibernate.generatedDomainClasses': generated,
+ 'dataSource.url' : "jdbc:h2:mem:gdd${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
+ 'dataSource.dbCreate': 'create-drop',
], group as Class[])
return datastore
}
/** The columns of the boot model with their SQL type and nullability, and the precision and scale the model holds for the discriminator. */
- private Map<String, Map> schema(List<Class> group, boolean generated) {
- HibernateDatastore booted = boot(group, generated)
+ private Map<String, Map> schema(List<Class> group) {
+ HibernateDatastore booted = boot(group)
Map<String, Map> result = new TreeMap<String, Map>()
for (Table table : booted.metadata.collectTableMappings()) {
if (table.physicalTable) {
@@ -67,13 +66,11 @@ class GeneratedDomainClassesDiscriminatorSpec extends Specification {
}
@Unroll
- void "#label: the generated mode creates the discriminator column of the domain binder, with its precision and scale"() {
+ void "#label: the discriminator column of classic binding is created, with its precision and scale"() {
when:
- Map<String, Map> binder = schema(group, false)
- Map<String, Map> generated = schema(group, true)
+ Map<String, Map> generated = schema(group)
then:
- generated == binder
generated[table]['kind'] == column
where:
@@ -84,16 +81,13 @@ class GeneratedDomainClassesDiscriminatorSpec extends Specification {
}
@Unroll
- void "#label: the rows of the hierarchy are stored and found by the discriminator in both modes"() {
+ void "#label: the rows of the hierarchy are stored and found by the discriminator"() {
when:
- Map<Boolean, List> results = [false, true].collectEntries { boolean generated ->
- boot(group, generated)
- [(generated): this."${cycle}"()]
- }
+ boot(group)
+ List results = this."${cycle}"()
then:
- results[true] == results[false]
- results[true] == [2, 1, ['sub']]
+ results == [2, 1, ['sub']]
where:
label | group | cycle
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesEmbeddedCollectionSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesEmbeddedCollectionSpec.groovy
index 15c8fabdce..e28d6ba141 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesEmbeddedCollectionSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesEmbeddedCollectionSpec.groovy
@@ -29,11 +29,11 @@ import spock.lang.Unroll
import org.grails.orm.hibernate.HibernateDatastore
/**
- * A collection inside an embedded type, bound by the domain binder and by the generated classes. The domain binder names the table
- * of such a collection after the embedded type and not after the owner ({@code ecs_words_words}), and its key column after the
- * embedded type too ({@code ecs_words_id}), whatever the embedded property is called; the key points at the table of the owner. The
- * generated classes state the same names. Two embedded properties that share a type with a collection get a table each in the generated
- * mode, see {@link GeneratedDomainClassesSharedEmbeddedCollectionSpec}.
+ * A collection inside an embedded type. The classic binding of Grails 8 named the table of such a collection after the embedded type
+ * and not after the owner ({@code ecs_words_words}), and its key column after the embedded type too ({@code ecs_words_id}), whatever
+ * the embedded property is called; the key points at the table of the owner. The generated classes state the same names, recorded
+ * here. Two embedded properties that share a type with a collection get a table each, see
+ * {@link GeneratedDomainClassesSharedEmbeddedCollectionSpec}.
*/
class GeneratedDomainClassesEmbeddedCollectionSpec extends Specification {
@@ -42,19 +42,18 @@ class GeneratedDomainClassesEmbeddedCollectionSpec extends Specification {
@AutoCleanup
HibernateDatastore datastore
- private HibernateDatastore boot(List<Class> group, boolean generated) {
+ private HibernateDatastore boot(List<Class> group) {
datastore?.close()
datastore = new HibernateDatastore([
- 'dataSource.url' : "jdbc:h2:mem:ecs${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
- 'dataSource.dbCreate' : 'create-drop',
- 'hibernate.generatedDomainClasses': generated,
+ 'dataSource.url' : "jdbc:h2:mem:ecs${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
+ 'dataSource.dbCreate': 'create-drop',
], group as Class[])
return datastore
}
/** The tables of the boot model as plain data: columns with SQL type and nullability, keys, foreign keys, indexes, unique keys. */
- private Map<String, Map> schema(List<Class> group, boolean generated) {
- HibernateDatastore booted = boot(group, generated)
+ private Map<String, Map> schema(List<Class> group) {
+ HibernateDatastore booted = boot(group)
Map<String, Map> result = new TreeMap<String, Map>()
for (Table table : booted.metadata.collectTableMappings()) {
if (table.physicalTable) {
@@ -74,13 +73,11 @@ class GeneratedDomainClassesEmbeddedCollectionSpec extends Specification {
}
@Unroll
- void "#label: the generated mode creates the schema of the domain binder"() {
+ void "#label: the schema of classic binding is created"() {
when:
- Map<String, Map> binder = schema(group, false)
- Map<String, Map> generated = schema(group, true)
+ Map<String, Map> generated = schema(group)
then:
- generated == binder
generated.keySet() == tables as Set
generated[table].columns.keySet() == columns as Set
@@ -96,46 +93,30 @@ class GeneratedDomainClassesEmbeddedCollectionSpec extends Specification {
}
@Unroll
- void "#label: the schema differs from the domain binder's only as the schema of a collection of the owner itself does"() {
+ void "#label: the collection table is the one of a collection of the owner itself, named after the embedded type"() {
when:
- Map<String, Map> binder = schema(group, false)
- Map<String, Map> generated = schema(group, true)
- Map<String, Map> plainBinder = schema([plain], false)
- Map<String, Map> plainGenerated = schema([plain], true)
-
- then: "the same tables, the same columns apart from the one the binder leaves unused, the same keys"
- generated.keySet() == binder.keySet()
- generated[table].columns.keySet() == binder[table].columns.keySet() - unused
- generated[table].primaryKey == binder[table].primaryKey
- generated[table].foreignKeys == binder[table].foreignKeys
- generated[table].indexes == binder[table].indexes
- generated[table].uniqueKeys == binder[table].uniqueKeys
-
- and: "the types differ exactly where they differ for a collection that is a property of the owner"
- shape(binder[table].columns, generated[table].columns) == shape(plainBinder[plainTable].columns, plainGenerated[plainTable].columns)
+ Map<String, Map> generated = schema(group)
+ Map<String, Map> plainGenerated = schema([plain])
- where:
- label | group | table | unused | plain | plainTable
- 'a list of strings' | [EcsListOwner] | 'ecs_lists_items' | [] | EcsPlainList | 'ecs_plain_list_items'
- 'a map of strings' | [EcsMapOwner] | 'ecs_maps_by_name' | ['by_name_java_lang_string'] | EcsPlainMap | 'ecs_plain_map_by_name'
- }
+ then: "the table has the columns, keys and types of the plain collection's table (classic binding left an unused element column in the table of a map)"
+ generated.keySet() == [owner, table] as Set
+ generated[table] == expected
+ plainGenerated[plainTable].columns.values().sort() == expected.columns.values().sort()
- private static List shape(Map<String, String> binder, Map<String, String> generated) {
- return (binder.keySet() + generated.keySet()).collect { String name -> [binder[name], generated[name]] }
- .findAll { List pair -> pair[0] != pair[1] }.sort { it.toString() }
+ where:
+ label | group | owner | table | plain | plainTable | expected
+ 'a list of strings' | [EcsListOwner] | 'ecs_list_owner' | 'ecs_lists_items' | EcsPlainList | 'ecs_plain_list_items' | [columns: [items_idx: 'integer not null', ecs_lists_id: 'bigint not null', items_java_lang_string: 'varchar(255)'], primaryKey: ['ecs_lists_id', 'items_idx'], foreignKeys: ['[ecs_lists_id] -> ecs_list_owner'], indexes: [:], uniqueKeys: []]
+ 'a map of strings' | [EcsMapOwner] | 'ecs_map_owner' | 'ecs_maps_by_name' | EcsPlainMap | 'ecs_plain_map_by_name' | [columns: [ecs_maps_id: 'bigint not null', by_name_elt: 'varchar(255) not null', by_name_idx: 'varchar(255) not null'], primaryKey: ['by_name_idx', 'ecs_maps_id'], foreignKeys: ['[ecs_maps_id] -> ecs_map_owner'], indexes: [:], uniqueKeys: []]
}
@Unroll
- void "#label are stored, read back, changed and deleted with the owner, the same in both modes"() {
+ void "#label are stored, read back, changed and deleted with the owner"() {
when:
- Map<Boolean, List> results = [false, true].collectEntries { boolean generated ->
- boot(group, generated)
- [(generated): this."${cycle}"()]
- }
+ boot(group)
+ List results = this."${cycle}"()
then:
- results[true] == results[false]
- results[true] == expected
+ results == expected
where:
label | group | cycle | expected
@@ -234,22 +215,21 @@ class GeneratedDomainClassesEmbeddedCollectionSpec extends Specification {
}
}
- void "the words of an embedded set are found by a query on the owner in both modes"() {
+ void "the words of an embedded set are found by a query on the owner"() {
+ given:
+ boot([EcsSetOwner])
+
when:
- List<List> results = [false, true].collect { boolean generated ->
- boot([EcsSetOwner], generated)
- EcsSetOwner.withTransaction {
- new EcsSetOwner(inner: new EcsWords(words: ['red', 'blue'] as Set)).save(failOnError: true)
- new EcsSetOwner(inner: new EcsWords(words: ['green'] as Set)).save(failOnError: true, flush: true)
- }
- EcsSetOwner.withNewSession {
- [EcsSetOwner.count(), EcsSetOwner.list()*.inner.words.flatten().sort(), EcsSetOwner.executeQuery('select count(o) from EcsSetOwner o where o.id > 0')[0]]
- }
+ EcsSetOwner.withTransaction {
+ new EcsSetOwner(inner: new EcsWords(words: ['red', 'blue'] as Set)).save(failOnError: true)
+ new EcsSetOwner(inner: new EcsWords(words: ['green'] as Set)).save(failOnError: true, flush: true)
+ }
+ List results = EcsSetOwner.withNewSession {
+ [EcsSetOwner.count(), EcsSetOwner.list()*.inner.words.flatten().sort(), EcsSetOwner.executeQuery('select count(o) from EcsSetOwner o where o.id > 0')[0]]
}
then:
- results[1] == results[0]
- results[1] == [2, ['blue', 'green', 'red'], 2]
+ results == [2, ['blue', 'green', 'red'], 2]
}
}
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesEmbeddedIdWorkaroundSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesEmbeddedIdWorkaroundSpec.groovy
index 40a08802d0..7f65828ff2 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesEmbeddedIdWorkaroundSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesEmbeddedIdWorkaroundSpec.groovy
@@ -32,11 +32,12 @@ import org.grails.orm.hibernate.HibernateDatastore
/**
* The supported way to move an embedded object that is a part of a composite identifier (<code>id composite: ['code',
- * 'address']</code> with <code>address</code> in <code>static embedded</code>) to the generated-domain-class binding, which
- * refuses it: the properties of the embedded class become plain properties of the identifier. The spec proves, through the
- * public datastore API, that the flattened entity keeps the schema of the embedded one in both bindings (tables, columns,
- * primary key columns and their order, foreign keys of a many-to-one and of a hasMany, as H2 states them), that rows the
- * embedded entity wrote stay readable, and that a transient accessor keeps <code>customer.address</code> compiling.
+ * 'address']</code> with <code>address</code> in <code>static embedded</code>), which the classic binding of Grails 8 accepted and
+ * native binding refuses: the properties of the embedded class become plain properties of the identifier. The spec proves, through
+ * the public datastore API, that the flattened entity keeps the schema the embedded one had (recorded from Grails 8 in
+ * {@link #EMBEDDED_SCHEMA}: tables, columns, primary key columns and their order, foreign keys of a many-to-one and of a hasMany, as H2
+ * states them), that rows the embedded entity wrote stay readable, and that a transient accessor keeps <code>customer.address</code>
+ * compiling.
*/
class GeneratedDomainClassesEmbeddedIdWorkaroundSpec extends Specification {
@@ -45,15 +46,25 @@ class GeneratedDomainClassesEmbeddedIdWorkaroundSpec extends Specification {
private static final String CUSTOMER_PRIMARY_KEY =
'ALTER TABLE "PUBLIC"."EID_CUSTOMER" ADD CONSTRAINT "PUBLIC"."CONSTRAINT_#" PRIMARY KEY("ADDRESS_CITY", "ADDRESS_STREET", "CODE");'
+ /** The H2 script of the schema the classic binding of Grails 8 created for the embedded version, as {@link #script} reads it. */
+ private static final List<String> EMBEDDED_SCHEMA = [
+ CUSTOMER_PRIMARY_KEY,
+ 'ALTER TABLE "PUBLIC"."EID_CUSTOMER" ADD CONSTRAINT "PUBLIC"."FKTENTYQNKSHX2SUF9F5R2X3UYS" FOREIGN KEY("REGION_ID") REFERENCES "PUBLIC"."EID_REGION"("ID") NOCHECK;',
+ 'ALTER TABLE "PUBLIC"."EID_REGION" ADD CONSTRAINT "PUBLIC"."CONSTRAINT_#" PRIMARY KEY("ID");',
+ 'CREATE MEMORY TABLE "PUBLIC"."EID_CUSTOMER"(\n "REGION_ID" BIGINT,\n "VERSION" BIGINT NOT NULL,\n "ADDRESS_CITY" CHARACTER VARYING(255) NOT NULL,\n' +
+ ' "ADDRESS_STREET" CHARACTER VARYING(255) NOT NULL,\n "CODE" CHARACTER VARYING(255) NOT NULL,\n "NAME" CHARACTER VARYING(255)\n);',
+ 'CREATE MEMORY TABLE "PUBLIC"."EID_REGION"(\n "ID" BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 1) NOT NULL,\n "VERSION" BIGINT NOT NULL,\n' +
+ ' "NAME" CHARACTER VARYING(255)\n);',
+ ].asImmutable()
+
private static final List<Class> EMBEDDED = [EidEmbCustomer, EidEmbRegion]
private static final List<Class> FLATTENED = [EidFlatCustomer, EidFlatRegion]
private static final List<Class> WITH_ACCESSOR = [EidAccessorCustomer, EidAccessorRegion]
- private static Map<String, Object> config(String url, boolean generated, String dbCreate = 'create-drop') {
+ private static Map<String, Object> config(String url, String dbCreate = 'create-drop') {
return [
- 'dataSource.url' : url,
- 'dataSource.dbCreate' : dbCreate,
- 'hibernate.generatedDomainClasses': generated,
+ 'dataSource.url' : url,
+ 'dataSource.dbCreate': dbCreate,
]
}
@@ -62,8 +73,8 @@ class GeneratedDomainClassesEmbeddedIdWorkaroundSpec extends Specification {
}
/** The schema H2 holds after the boot, as its own script without data, in a stable order and without generated names. */
- private static List<String> schema(List<Class> classes, boolean generated) {
- HibernateDatastore datastore = new HibernateDatastore(config(freshUrl(), generated), classes as Class[])
+ private static List<String> schema(List<Class> classes) {
+ HibernateDatastore datastore = new HibernateDatastore(config(freshUrl()), classes as Class[])
try {
return script(datastore)
} finally {
@@ -90,32 +101,22 @@ class GeneratedDomainClassesEmbeddedIdWorkaroundSpec extends Specification {
}
}
- private static boolean isPurchaseKey(String statement) {
- return statement.contains('"EID_PURCHASE"') && statement.contains('FOREIGN KEY')
- }
-
private static String purchaseKey(List<String> script) {
- return script.find { String statement -> isPurchaseKey(statement) }
+ return script.find { String statement -> statement.contains('"EID_PURCHASE"') && statement.contains('FOREIGN KEY') }
}
def "an embedded object as a part of the identifier is replaced by its properties, with the schema unchanged"() {
- given:
- List<String> embedded = schema(EMBEDDED, false)
-
- expect: 'the embedded entity creates the primary key over the columns of the embedded properties, in this order'
- embedded.contains(CUSTOMER_PRIMARY_KEY)
- embedded.any { it.contains('"ADDRESS_CITY" CHARACTER VARYING(255) NOT NULL') }
+ expect: 'the embedded entity created the primary key over the columns of the embedded properties, in this order'
+ EMBEDDED_SCHEMA.contains(CUSTOMER_PRIMARY_KEY)
+ EMBEDDED_SCHEMA.any { it.contains('"ADDRESS_CITY" CHARACTER VARYING(255) NOT NULL') }
and: 'the flattened entity creates every table, column, key and constraint the same'
- schema(FLATTENED, generated) == embedded
-
- where:
- generated << [false, true]
+ schema(FLATTENED) == EMBEDDED_SCHEMA
}
- def "the generated-class binding refuses the embedded version and points at the flattened one"() {
+ def "native binding refuses the embedded version and points at the flattened one"() {
when:
- schema(EMBEDDED, true)
+ schema(EMBEDDED)
then:
RuntimeException failure = thrown()
@@ -126,54 +127,29 @@ class GeneratedDomainClassesEmbeddedIdWorkaroundSpec extends Specification {
def "a transient accessor keeps the schema and adds no column"() {
expect:
- schema(WITH_ACCESSOR, generated) == schema(EMBEDDED, false)
-
- where:
- generated << [false, true]
+ schema(WITH_ACCESSOR) == EMBEDDED_SCHEMA
}
- def "a many-to-one to the flattened entity references the identifier columns in the identifier order, in both bindings"() {
+ def "a many-to-one to the flattened entity references the identifier columns in the identifier order, as with classic binding"() {
given:
- List<String> classic = schema(FLATTENED + EidFlatPurchase, false)
+ List<String> script = schema(FLATTENED + EidFlatPurchase)
expect:
- schema(FLATTENED + EidFlatPurchase, true) == classic
- purchaseKey(classic) ==
+ script.containsAll(EMBEDDED_SCHEMA)
+ purchaseKey(script) ==
'ALTER TABLE "PUBLIC"."EID_PURCHASE" ADD CONSTRAINT "PUBLIC"."FKRBA3TSBPYXEJHWMBNOVA4F9VV" FOREIGN KEY' +
'("EID_CUSTOMER_ADDRESS_CITY", "EID_CUSTOMER_ADDRESS_STREET", "EID_CUSTOMER_CODE") REFERENCES ' +
'"PUBLIC"."EID_CUSTOMER"("ADDRESS_CITY", "ADDRESS_STREET", "CODE") NOCHECK;'
- classic.any { it.contains('"EID_CUSTOMER_ADDRESS_CITY" CHARACTER VARYING(255),') }
+ script.any { it.contains('"EID_CUSTOMER_ADDRESS_CITY" CHARACTER VARYING(255),') }
}
- def "the domain binder cannot state the foreign key to an embedded identifier: it does not boot, and with the columns spelled out it pairs them wrongly"() {
+ def "a hasMany bound through a join table to a composite identifier is refused (classic binding could not boot it either)"() {
when:
- schema(EMBEDDED + EidEmbPurchase, false)
+ schema([EidFlatCustomer, EidFlatRegion, EidFlatTeam])
then:
RuntimeException failure = thrown()
- failure.toString().contains("maps to 2 columns but 3 columns are required")
-
- when:
- List<String> explicit = schema(EMBEDDED + EidEmbExplicitPurchase, false)
-
- then: 'the tables and columns are the flattened ones, the foreign key pairs street with street, but city with code and code with city'
- explicit.findAll { !isPurchaseKey(it) } == schema(FLATTENED + EidFlatPurchase, true).findAll { !isPurchaseKey(it) }
- purchaseKey(explicit).contains('("EID_CUSTOMER_ADDRESS_STREET", "EID_CUSTOMER_ADDRESS_CITY", "EID_CUSTOMER_CODE")')
- purchaseKey(explicit).contains('("ADDRESS_STREET", "CODE", "ADDRESS_CITY")')
- }
-
- def "a hasMany bound through a join table to a composite identifier boots in neither binding, flattened or not"() {
- when:
- schema([EidFlatCustomer, EidFlatRegion, EidFlatTeam], generated)
-
- then:
- RuntimeException failure = thrown()
- failure.toString().contains(message)
-
- where:
- generated | message
- false | 'must have same number of columns as the referenced primary key'
- true | 'the collection is bound through a join table'
+ failure.toString().contains('the collection is bound through a join table')
}
private static void shutdown(String url) {
@@ -189,18 +165,38 @@ class GeneratedDomainClassesEmbeddedIdWorkaroundSpec extends Specification {
return "jdbc:h2:mem:eidExisting${BOOTS.incrementAndGet()};DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=10000".toString()
}
+ /**
+ * The database of an application of Grails 8 that used the embedded version: its schema ({@link #EMBEDDED_SCHEMA}, the primary
+ * key constraints told apart by name) and the rows the embedded entity wrote.
+ */
private static void writeEmbedded(String url) {
- HibernateDatastore datastore = new HibernateDatastore(config(url, false, 'create'), EMBEDDED as Class[])
+ Connection connection = java.sql.DriverManager.getConnection(url)
try {
- EidEmbRegion.withTransaction {
- EidEmbRegion region = new EidEmbRegion(name: 'eu').save(failOnError: true)
- new EidEmbCustomer(code: 'c1', address: new EidAddress(street: 's1', city: 'x1'), name: 'one', region: region)
- .save(failOnError: true)
- new EidEmbCustomer(code: 'c2', address: new EidAddress(street: 's2', city: 'x2'), name: 'two', region: region)
- .save(failOnError: true, flush: true)
+ Statement statement = connection.createStatement()
+ int constraints = 0
+ EMBEDDED_SCHEMA.findAll { it.startsWith('CREATE') }.each { String ddl -> statement.execute(ddl) }
+ EMBEDDED_SCHEMA.findAll { it.startsWith('ALTER') }.sort { String ddl -> ddl.contains('PRIMARY KEY') ? 0 : 1 }.each { String ddl ->
+ statement.execute(ddl.replace('"CONSTRAINT_#"', "\"CONSTRAINT_${++constraints}\"".toString()))
}
+ statement.execute("insert into eid_region (id, version, name) values (1, 0, 'eu')")
+ statement.execute("insert into eid_customer (region_id, version, address_city, address_street, code, name) values (1, 0, 'x1', 's1', 'c1', 'one')")
+ statement.execute("insert into eid_customer (region_id, version, address_city, address_street, code, name) values (1, 0, 'x2', 's2', 'c2', 'two')")
} finally {
- datastore.close()
+ connection.close()
+ }
+ }
+
+ private static List<List> rows(String url, String sql) {
+ Connection connection = java.sql.DriverManager.getConnection(url)
+ try {
+ ResultSet result = connection.createStatement().executeQuery(sql)
+ List<List> found = []
+ while (result.next()) {
+ found << (1..result.metaData.columnCount).collect { int i -> result.getObject(i) }
+ }
+ return found
+ } finally {
+ connection.close()
}
}
@@ -208,7 +204,7 @@ class GeneratedDomainClassesEmbeddedIdWorkaroundSpec extends Specification {
given:
String url = existingDatabase()
writeEmbedded(url)
- HibernateDatastore datastore = new HibernateDatastore(config(url, generated, 'validate'), FLATTENED as Class[])
+ HibernateDatastore datastore = new HibernateDatastore(config(url, 'validate'), FLATTENED as Class[])
Map found = [:]
when:
@@ -234,29 +230,22 @@ class GeneratedDomainClassesEmbeddedIdWorkaroundSpec extends Specification {
found.region3 = EidFlatRegion.list().first().customers*.code.sort()
}
datastore.close()
- HibernateDatastore back = new HibernateDatastore(config(url, false, 'validate'), EMBEDDED as Class[])
- EidEmbCustomer.withTransaction {
- found.back = EidEmbCustomer.get(new EidEmbCustomer(code: 'c3', address: new EidAddress(street: 's3', city: 'x3'))).name
- found.backCount = EidEmbCustomer.count()
- }
+ found.back = rows(url, "select name from eid_customer where code = 'c3' and address_street = 's3' and address_city = 'x3'")
+ found.backCount = rows(url, 'select count(*) from eid_customer')
- then:
+ then: 'the rows are read, and the ones written are in the columns the embedded entity used'
found == [byKey: 'one', missing: null, byFinder: 'two', byWhere: ['c1'], count: 2, region: ['one', 'two'], customerRegion: 'eu',
- updated: 'uno', total: 3, region3: ['c1', 'c2', 'c3'], back: 'three', backCount: 3]
+ updated: 'uno', total: 3, region3: ['c1', 'c2', 'c3'], back: [['three']], backCount: [[3L]]]
cleanup:
- back?.close()
shutdown(url)
-
- where:
- generated << [false, true]
}
def "the transient accessor rebuilds the embedded object from the rows the embedded entity wrote, and is not persisted"() {
given:
String url = existingDatabase()
writeEmbedded(url)
- HibernateDatastore datastore = new HibernateDatastore(config(url, generated, 'validate'), WITH_ACCESSOR as Class[])
+ HibernateDatastore datastore = new HibernateDatastore(config(url, 'validate'), WITH_ACCESSOR as Class[])
Map found = [:]
when:
@@ -278,9 +267,6 @@ class GeneratedDomainClassesEmbeddedIdWorkaroundSpec extends Specification {
cleanup:
datastore?.close()
shutdown(url)
-
- where:
- generated << [false, true]
}
}
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesJoinColumnSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesJoinColumnSpec.groovy
index 8ed5a9f5b1..d3ec721e36 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesJoinColumnSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesJoinColumnSpec.groovy
@@ -29,10 +29,10 @@ import spock.lang.Unroll
import org.grails.orm.hibernate.HibernateDatastore
/**
- * Column settings on a foreign key: a to-one association, the key of a collection, the element of a many-to-many. The domain binder puts
- * the {@code defaultValue}, {@code comment}, {@code read} and {@code write} of the column config on the foreign key column and ignores
- * {@code length}, {@code precision} and {@code scale} (the type of the column is the one of the column it references). The generated
- * mode accepts the mapping and creates the same columns, instead of refusing it.
+ * Column settings on a foreign key: a to-one association, the key of a collection, the element of a many-to-many. As the classic binding
+ * of Grails 8 did, the {@code defaultValue}, {@code comment}, {@code read} and {@code write} of the column config go on the foreign key
+ * column and {@code length}, {@code precision} and {@code scale} are ignored (the type of the column is the one of the column it
+ * references). Native binding accepts the mapping instead of refusing it; the columns stated here are the ones classic binding created.
*/
class GeneratedDomainClassesJoinColumnSpec extends Specification {
@@ -41,19 +41,18 @@ class GeneratedDomainClassesJoinColumnSpec extends Specification {
@AutoCleanup
HibernateDatastore datastore
- private HibernateDatastore boot(List<Class> group, boolean generated) {
+ private HibernateDatastore boot(List<Class> group) {
datastore?.close()
datastore = new HibernateDatastore([
- 'dataSource.url' : "jdbc:h2:mem:gdj${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
- 'dataSource.dbCreate' : 'create-drop',
- 'hibernate.generatedDomainClasses': generated,
+ 'dataSource.url' : "jdbc:h2:mem:gdj${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
+ 'dataSource.dbCreate': 'create-drop',
], group as Class[])
return datastore
}
/** The columns of the boot model with the type, nullability, comment, default and read and write expressions of each, and the foreign keys. */
- private Map<String, Map> schema(List<Class> group, boolean generated) {
- HibernateDatastore booted = boot(group, generated)
+ private Map<String, Map> schema(List<Class> group) {
+ HibernateDatastore booted = boot(group)
Map<String, Map> result = new TreeMap<String, Map>()
for (Table table : booted.metadata.collectTableMappings()) {
if (table.physicalTable) {
@@ -76,13 +75,11 @@ class GeneratedDomainClassesJoinColumnSpec extends Specification {
}
@Unroll
- void "#label: the generated mode creates the foreign key column of the domain binder, with its comment, default and expressions"() {
+ void "#label: the foreign key column of classic binding is created, with its comment, default and expressions"() {
when:
- Map<String, Map> binder = schema(group, false)
- Map<String, Map> generated = schema(group, true)
+ Map<String, Map> generated = schema(group)
then:
- generated == binder
generated[table].columns[column].subMap(['comment', 'default', 'read', 'write']) == expected
where:
@@ -99,13 +96,11 @@ class GeneratedDomainClassesJoinColumnSpec extends Specification {
}
@Unroll
- void "#label: the types of the foreign key columns ignore length, precision and scale in both modes"() {
+ void "#label: the types of the foreign key columns ignore length, precision and scale"() {
when:
- Map<String, Map> binder = schema(group, false)
- Map<String, Map> generated = schema(group, true)
+ Map<String, Map> generated = schema(group)
then:
- generated == binder
generated[table].columns[column].type == type
where:
@@ -116,16 +111,13 @@ class GeneratedDomainClassesJoinColumnSpec extends Specification {
}
@Unroll
- void "#label: the associations are stored and read back in both modes"() {
+ void "#label: the associations are stored and read back"() {
when:
- Map<Boolean, List> results = [false, true].collectEntries { boolean generated ->
- boot(group, generated)
- [(generated): this."${cycle}"()]
- }
+ boot(group)
+ List results = this."${cycle}"()
then:
- results[true] == results[false]
- results[true] == expected
+ results == expected
where:
label | group | cycle | expected
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesMapManyToManySpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesMapManyToManySpec.groovy
index 2e5fc4cd45..519fa9481d 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesMapManyToManySpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesMapManyToManySpec.groovy
@@ -33,11 +33,11 @@ import org.grails.orm.hibernate.cfg.domainbinding.binder.MapSetLeft
import org.grails.orm.hibernate.cfg.domainbinding.binder.MapSetRight
/**
- * A {@code Map} on a many-to-many, bound by the domain binder and by the generated classes. The domain binder makes a map side not
- * inverse whether or not the mapping says it owns the relationship, so the map side writes the join table (key column, element
- * column and the column of the key of the map, which is part of the primary key), a {@code Set} on the other side is inverse and reads
- * the same table, and two maps are two independent tables (a map on a many-to-many stores through its own side only). The generated
- * classes state exactly that.
+ * A {@code Map} on a many-to-many. As with the classic binding of Grails 8, a map side is not inverse whether or not the mapping says
+ * it owns the relationship, so the map side writes the join table (key column, element column and the column of the key of the map,
+ * which is part of the primary key), a {@code Set} on the other side is inverse and reads the same table, and two maps are two
+ * independent tables (a map on a many-to-many stores through its own side only). The generated classes state exactly that; the tables
+ * and the behaviour stated here are the ones classic binding gave.
*/
class GeneratedDomainClassesMapManyToManySpec extends Specification {
@@ -46,19 +46,18 @@ class GeneratedDomainClassesMapManyToManySpec extends Specification {
@AutoCleanup
HibernateDatastore datastore
- private HibernateDatastore boot(List<Class> group, boolean generated) {
+ private HibernateDatastore boot(List<Class> group) {
datastore?.close()
datastore = new HibernateDatastore([
- 'dataSource.url' : "jdbc:h2:mem:mmm${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
- 'dataSource.dbCreate' : 'create-drop',
- 'hibernate.generatedDomainClasses': generated,
+ 'dataSource.url' : "jdbc:h2:mem:mmm${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
+ 'dataSource.dbCreate': 'create-drop',
], group as Class[])
return datastore
}
/** The tables of the boot model as plain data, and which collection of which role is inverse. */
- private Map<String, Map> schema(List<Class> group, boolean generated) {
- HibernateDatastore booted = boot(group, generated)
+ private Map<String, Map> schema(List<Class> group) {
+ HibernateDatastore booted = boot(group)
Map<String, Map> result = new TreeMap<String, Map>()
for (Table table : booted.metadata.collectTableMappings()) {
if (table.physicalTable) {
@@ -81,13 +80,11 @@ class GeneratedDomainClassesMapManyToManySpec extends Specification {
}
@Unroll
- void "#label: the generated mode creates the schema of the domain binder"() {
+ void "#label: the schema of classic binding is created"() {
when:
- Map<String, Map> binder = schema(group, false)
- Map<String, Map> generated = schema(group, true)
+ Map<String, Map> generated = schema(group)
then:
- generated == binder
generated.keySet() - 'collections' == tables as Set
generated[joinTable].columns.keySet() == columns as Set
generated[joinTable].primaryKey == primaryKey.sort(false)
@@ -103,7 +100,7 @@ class GeneratedDomainClassesMapManyToManySpec extends Specification {
void "the map side writes the join table and the set side is inverse"() {
when:
- Map<String, Map> generated = schema([MapSetLeft, MapSetRight], true)
+ Map<String, Map> generated = schema([MapSetLeft, MapSetRight])
then:
generated.collections['org.grails.orm.hibernate.cfg.domainbinding.binder.MapSetLeft.rights'].contains('inverse=false')
@@ -112,21 +109,18 @@ class GeneratedDomainClassesMapManyToManySpec extends Specification {
}
@Unroll
- void "#label: the rows are stored through the map, read back, changed and deleted, the same in both modes"() {
+ void "#label: the rows are stored through the map, read back, changed and deleted"() {
when:
- Map<Boolean, Map> results = [false, true].collectEntries { boolean generated ->
- boot(group, generated)
- [(generated): cycle(left, right, joinTable)]
- }
+ boot(group)
+ Map results = cycle(left, right, joinTable)
then:
- results[true] == results[false]
- results[true].stored == [a: 'r1', b: 'r2']
- results[true].changed == [b: 'r2', c: 'r1']
- results[true].rowsStored == 2
- results[true].rowsChanged == 2
- results[true].rowsDeleted == 0
- results[true].inverse == inverse
+ results.stored == [a: 'r1', b: 'r2']
+ results.changed == [b: 'r2', c: 'r1']
+ results.rowsStored == 2
+ results.rowsChanged == 2
+ results.rowsDeleted == 0
+ results.inverse == inverse
where:
label | group | left | right | joinTable | inverse
@@ -137,17 +131,13 @@ class GeneratedDomainClassesMapManyToManySpec extends Specification {
'a map with a join table named' | [MmmNamedLeft, MmmNamedRight] | MmmNamedLeft | MmmNamedRight | 'mmm_named_join' | ['left']
}
- void "the domain binder leaves the element column of a map nullable or not null depending on the order the classes are bound in, the generated mode always states not null"() {
- when: "the column is shared by the element of the map and the key of the set that reads it, and the binder sets its nullability twice"
- Map<String, String> binder = [[MmmOwnerLeft, MmmOwnedRight], [MmmOwnedRight, MmmOwnerLeft]].collectEntries { List<Class> group ->
- [(group*.simpleName.join(',')): schema(group, false)['mmm_owner_left_rights'].columns['mmm_owned_right_id']]
- }
+ void "the element column of a map is not null whatever the order the classes are bound in"() {
+ when: "the column is shared by the element of the map and the key of the set that reads it (classic binding set its nullability twice, and the order decided)"
Map<String, String> generated = [[MmmOwnerLeft, MmmOwnedRight], [MmmOwnedRight, MmmOwnerLeft]].collectEntries { List<Class> group ->
- [(group*.simpleName.join(',')): schema(group, true)['mmm_owner_left_rights'].columns['mmm_owned_right_id']]
+ [(group*.simpleName.join(',')): schema(group)['mmm_owner_left_rights'].columns['mmm_owned_right_id']]
}
then:
- binder.values().toSet() == ['bigint', 'bigint not null'].toSet()
generated.values().toSet() == ['bigint not null'].toSet()
}
@@ -185,43 +175,41 @@ class GeneratedDomainClassesMapManyToManySpec extends Specification {
}
}
- void "a query joins through the map and through the set that reads it, the same in both modes"() {
+ void "a query joins through the map and through the set that reads it"() {
+ given:
+ boot([MapSetLeft, MapSetRight])
+
when:
- List<List> results = [false, true].collect { boolean generated ->
- boot([MapSetLeft, MapSetRight], generated)
- MapSetLeft.withTransaction {
- MapSetRight red = new MapSetRight(name: 'red').save(failOnError: true)
- MapSetRight blue = new MapSetRight(name: 'blue').save(failOnError: true)
- new MapSetLeft(name: 'one', rights: [x: red, y: blue]).save(failOnError: true)
- new MapSetLeft(name: 'two', rights: [x: red]).save(failOnError: true, flush: true)
- }
- MapSetLeft.withNewSession {
- [MapSetLeft.executeQuery('select l.name from MapSetLeft l join l.rights r where r.name = :n order by l.name', [n: 'red']),
- MapSetLeft.executeQuery('select l.name from MapSetLeft l join l.rights r where r.name = :n', [n: 'blue']),
- MapSetRight.executeQuery('select l.name from MapSetRight r join r.lefts l where r.name = :n order by l.name', [n: 'red']),
- MapSetLeft.executeQuery('select count(l) from MapSetLeft l where size(l.rights) = 2')[0]]
- }
+ MapSetLeft.withTransaction {
+ MapSetRight red = new MapSetRight(name: 'red').save(failOnError: true)
+ MapSetRight blue = new MapSetRight(name: 'blue').save(failOnError: true)
+ new MapSetLeft(name: 'one', rights: [x: red, y: blue]).save(failOnError: true)
+ new MapSetLeft(name: 'two', rights: [x: red]).save(failOnError: true, flush: true)
+ }
+ List results = MapSetLeft.withNewSession {
+ [MapSetLeft.executeQuery('select l.name from MapSetLeft l join l.rights r where r.name = :n order by l.name', [n: 'red']),
+ MapSetLeft.executeQuery('select l.name from MapSetLeft l join l.rights r where r.name = :n', [n: 'blue']),
+ MapSetRight.executeQuery('select l.name from MapSetRight r join r.lefts l where r.name = :n order by l.name', [n: 'red']),
+ MapSetLeft.executeQuery('select count(l) from MapSetLeft l where size(l.rights) = 2')[0]]
}
then:
- results[1] == results[0]
- results[1] == [['one', 'two'], ['one'], ['one', 'two'], 1]
+ results == [['one', 'two'], ['one'], ['one', 'two'], 1]
}
- void "the second map of two maps does not see the rows stored through the first, in both modes"() {
+ void "the second map of two maps does not see the rows stored through the first"() {
+ given:
+ boot([MapMapLeft, MapMapRight])
+
when:
- List<List> results = [false, true].collect { boolean generated ->
- boot([MapMapLeft, MapMapRight], generated)
- MapMapLeft.withTransaction {
- MapMapRight right = new MapMapRight(name: 'right').save(failOnError: true)
- new MapMapLeft(name: 'left', rights: [first: right]).save(failOnError: true, flush: true)
- }
- MapMapLeft.withNewSession { [MapMapLeft.findByName('left').rights.keySet() as List, MapMapRight.findByName('right').lefts.keySet() as List] }
+ MapMapLeft.withTransaction {
+ MapMapRight right = new MapMapRight(name: 'right').save(failOnError: true)
+ new MapMapLeft(name: 'left', rights: [first: right]).save(failOnError: true, flush: true)
}
+ List results = MapMapLeft.withNewSession { [MapMapLeft.findByName('left').rights.keySet() as List, MapMapRight.findByName('right').lefts.keySet() as List] }
then:
- results[1] == results[0]
- results[1] == [['first'], []]
+ results == [['first'], []]
}
}
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesMultiDataSourceSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesMultiDataSourceSpec.groovy
index f6d42820b0..0d9d6a4aaf 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesMultiDataSourceSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesMultiDataSourceSpec.groovy
@@ -30,28 +30,26 @@ import org.grails.datastore.mapping.core.DatastoreUtils
import org.grails.orm.hibernate.HibernateDatastore
/**
- * Several data sources over the generated mapping, each entity mapped to one of them (or to all): every data source has
- * its own session factory and its own generated classes, and the tables of each database are those the domain binder
- * creates.
+ * Several data sources, each entity mapped to one of them (or to all): every data source has its own session factory and its
+ * own generated classes, and the tables of each database are those the classic binding of Grails 8 created, stated here.
*/
class GeneratedDomainClassesMultiDataSourceSpec extends Specification {
@AutoCleanup
HibernateDatastore datastore
- private HibernateDatastore boot(boolean generated, List<Class> classes) {
+ private HibernateDatastore boot(List<Class> classes) {
datastore?.close()
long stamp = System.nanoTime()
datastore = new HibernateDatastore(DatastoreUtils.createPropertyResolver([
- 'dataSource.url' : "jdbc:h2:mem:gdcMdDefault${generated}${stamp};LOCK_TIMEOUT=10000".toString(),
- 'dataSource.dbCreate' : 'create-drop',
- 'dataSource.dialect' : H2Dialect.name,
- 'dataSources.second.url' : "jdbc:h2:mem:gdcMdSecond${generated}${stamp};LOCK_TIMEOUT=10000".toString(),
- 'dataSources.second.dbCreate' : 'create-drop',
- 'hibernate.hbm2ddl.auto' : 'create-drop',
- 'hibernate.cache.queries' : 'false',
- 'hibernate.cache.use_query_cache' : 'false',
- 'hibernate.generatedDomainClasses': generated,
+ 'dataSource.url' : "jdbc:h2:mem:gdcMdDefault${stamp};LOCK_TIMEOUT=10000".toString(),
+ 'dataSource.dbCreate' : 'create-drop',
+ 'dataSource.dialect' : H2Dialect.name,
+ 'dataSources.second.url' : "jdbc:h2:mem:gdcMdSecond${stamp};LOCK_TIMEOUT=10000".toString(),
+ 'dataSources.second.dbCreate' : 'create-drop',
+ 'hibernate.hbm2ddl.auto' : 'create-drop',
+ 'hibernate.cache.queries' : 'false',
+ 'hibernate.cache.use_query_cache': 'false',
]), classes as Class[])
return datastore
}
@@ -75,8 +73,8 @@ class GeneratedDomainClassesMultiDataSourceSpec extends Specification {
return result
}
- private Map scenario(boolean generated) {
- HibernateDatastore booted = boot(generated, [GdcMdPrimary, GdcMdSecond, GdcMdSecondChild, GdcMdAll])
+ private Map scenario() {
+ HibernateDatastore booted = boot([GdcMdPrimary, GdcMdSecond, GdcMdSecondChild, GdcMdAll])
Map result = [:]
GdcMdPrimary.withTransaction { new GdcMdPrimary(name: 'primary').save(flush: true, failOnError: true) }
GdcMdSecond.withTransaction {
@@ -94,8 +92,8 @@ class GeneratedDomainClassesMultiDataSourceSpec extends Specification {
allSecond : GdcMdAll.second.withNewSession { GdcMdAll.second.list()*.name },
]
result.urls = [
- primary: GdcMdPrimary.withNewSession { Session s -> s.doReturningWork { it.metaData.getURL() } }.replaceAll(/(true|false)\d+$/, ''),
- second : GdcMdSecond.withNewSession { Session s -> s.doReturningWork { it.metaData.getURL() } }.replaceAll(/(true|false)\d+$/, ''),
+ primary: GdcMdPrimary.withNewSession { Session s -> s.doReturningWork { it.metaData.getURL() } },
+ second : GdcMdSecond.withNewSession { Session s -> s.doReturningWork { it.metaData.getURL() } },
]
result.defaultTables = tables(booted.connectionSources.defaultConnectionSource.dataSource)
result.secondTables = tables(booted.connectionSources.getConnectionSource('second').dataSource)
@@ -106,10 +104,9 @@ class GeneratedDomainClassesMultiDataSourceSpec extends Specification {
return result
}
- def "each entity lives in the data source it is mapped to, and the databases are built like binder mode builds them"() {
+ def "each entity lives in the data source it is mapped to, and the databases are built as classic binding built them"() {
when:
- Map binder = scenario(false)
- Map generated = scenario(true)
+ Map generated = scenario()
then: 'the rows are in the right database, through the named data source api and through a lazy collection'
generated.counts == [
@@ -122,20 +119,26 @@ class GeneratedDomainClassesMultiDataSourceSpec extends Specification {
default: ['GdcMdAll', 'GdcMdPrimary'],
second : ['GdcMdAll', 'GdcMdSecond', 'GdcMdSecondChild'],
]
- generated.mapped == binder.mapped
-
- and: 'the tables, columns and foreign keys of both databases equal binder mode'
- generated.defaultTables.keySet() == ['GDC_MD_ALL', 'GDC_MD_PRIMARY'] as Set
- generated.secondTables.keySet() == ['GDC_MD_ALL', 'GDC_MD_SECOND', 'GDC_MD_SECOND_CHILD'] as Set
- generated.defaultTables == binder.defaultTables
- generated.secondTables == binder.secondTables
- generated.counts == binder.counts
- generated.urls == binder.urls
+
+ and: 'the tables, columns and foreign keys of both databases are the ones classic binding created'
+ generated.defaultTables == [
+ GDC_MD_ALL : ['ID BIGINT NO fks=0', 'NAME CHARACTER VARYING YES fks=0', 'VERSION BIGINT NO fks=0'],
+ GDC_MD_PRIMARY: ['ID BIGINT NO fks=0', 'NAME CHARACTER VARYING YES fks=0', 'VERSION BIGINT NO fks=0'],
+ ]
+ generated.secondTables == [
+ GDC_MD_ALL : ['ID BIGINT NO fks=0', 'NAME CHARACTER VARYING YES fks=0', 'VERSION BIGINT NO fks=0'],
+ GDC_MD_SECOND : ['ID BIGINT NO fks=0', 'NAME CHARACTER VARYING YES fks=0', 'VERSION BIGINT NO fks=0'],
+ GDC_MD_SECOND_CHILD: ['ID BIGINT NO fks=1', 'LABEL CHARACTER VARYING YES fks=1', 'PARENT_ID BIGINT YES fks=1', 'VERSION BIGINT NO fks=1'],
+ ]
+
+ and: 'each session talks to the database of its data source'
+ generated.urls.primary.contains('gdcMdDefault')
+ generated.urls.second.contains('gdcMdSecond')
}
def "a data source added at run time gets the generated classes of the entities mapped to all data sources"() {
given:
- boot(true, [GdcMdPrimary, GdcMdAll])
+ boot([GdcMdPrimary, GdcMdAll])
when:
datastore.connectionSources.addConnectionSource('late', [
@@ -150,9 +153,9 @@ class GeneratedDomainClassesMultiDataSourceSpec extends Specification {
datastore.getDatastoreForConnection('late').sessionFactory.metamodel.entity(GdcMdAll).javaType == GdcMdAll
}
- def "an association across data sources is refused by name, as a mapping exception, in #mode mode"() {
+ def "an association across data sources is refused by name, as a mapping exception"() {
when:
- boot(generated, [CrossDataSourceRef, GdcMdSecond, GdcMdSecondChild])
+ boot([CrossDataSourceRef, GdcMdSecond, GdcMdSecondChild])
then:
Exception e = thrown()
@@ -162,12 +165,8 @@ class GeneratedDomainClassesMultiDataSourceSpec extends Specification {
}
root instanceof MappingException
root.message.contains(GdcMdSecond.name)
- generated ? (root.message.contains(CrossDataSourceRef.name) && root.message.contains('data source')) : root.message.contains('cross_data_source_ref')
-
- where:
- generated | mode
- false | 'binder'
- true | 'generated'
+ root.message.contains(CrossDataSourceRef.name)
+ root.message.contains('data source')
}
}
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesMultiTenancySpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesMultiTenancySpec.groovy
index b17e877d6b..bbe86e0db0 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesMultiTenancySpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesMultiTenancySpec.groovy
@@ -23,7 +23,6 @@ import grails.gorm.annotation.Entity
import org.hibernate.dialect.H2Dialect
import spock.lang.AutoCleanup
import spock.lang.Specification
-import spock.lang.Unroll
import spock.util.environment.RestoreSystemProperties
import org.grails.datastore.mapping.core.DatastoreUtils
@@ -52,7 +51,6 @@ class GeneratedDomainClassesMultiTenancySpec extends Specification {
'hibernate.cache.queries' : 'false',
'hibernate.cache.use_query_cache' : 'false',
'hibernate.hbm2ddl.auto' : 'create',
- 'hibernate.generatedDomainClasses' : true,
]), GdcTenantItem)
when:
@@ -82,22 +80,20 @@ class GeneratedDomainClassesMultiTenancySpec extends Specification {
}
/**
- * The tenant id may be a part of a composite identifier (grails-test-examples/hibernate7/issue450): the classic binder binds
- * the part like any other column of the key, and the tenant filter compares the same column.
+ * The tenant id may be a part of a composite identifier (grails-test-examples/hibernate7/issue450): the part is bound like any
+ * other column of the key, as the classic binding of Grails 8 bound it, and the tenant filter compares the same column.
*/
- @Unroll
- def "the tenant id can be a part of the composite identifier (generated: #generated)"() {
+ def "the tenant id can be a part of the composite identifier"() {
given:
System.setProperty(SystemPropertyTenantResolver.PROPERTY_NAME, 'grails')
datastore = new HibernateDatastore(DatastoreUtils.createPropertyResolver([
'grails.gorm.multiTenancy.mode' : MultiTenancySettings.MultiTenancyMode.DISCRIMINATOR,
'grails.gorm.multiTenancy.tenantResolverClass': SystemPropertyTenantResolver.name,
- 'dataSource.url' : "jdbc:h2:mem:gdcTenantComposite${generated};LOCK_TIMEOUT=10000".toString(),
+ 'dataSource.url' : 'jdbc:h2:mem:gdcTenantComposite;LOCK_TIMEOUT=10000',
'dataSource.dialect' : H2Dialect.name,
'hibernate.cache.queries' : 'false',
'hibernate.cache.use_query_cache' : 'false',
'hibernate.hbm2ddl.auto' : 'create',
- 'hibernate.generatedDomainClasses' : generated,
]), GdcTenantCompositeBook)
String grailsId = UUID.randomUUID().toString()
String groovyId = UUID.randomUUID().toString()
@@ -122,9 +118,6 @@ class GeneratedDomainClassesMultiTenancySpec extends Specification {
then:
GdcTenantCompositeBook.withNewSession { GdcTenantCompositeBook.list()*.title } == ['The definitive Guide to Grails 2']
GdcTenantCompositeBook.withNewSession { GdcTenantCompositeBook.findByTitle('Groovy in Action') } == null
-
- where:
- generated << [false, true]
}
}
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
index 7ee86971d2..c69f7940b0 100644
--- 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
@@ -32,11 +32,10 @@ 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.
+ * A natural id the mapping states with {@code id natural: ...} on an entity that cannot be handed to Hibernate's {@code @NaturalId}
+ * as it is: a subclass (the classic binding of Grails 8 added 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 (classic binding skipped it). The entity boots with the
+ * unique keys classic binding created (name and column order, stated here), and rejects the same duplicates.
*/
class GeneratedDomainClassesNaturalIdSpec extends Specification {
@@ -45,12 +44,11 @@ class GeneratedDomainClassesNaturalIdSpec extends Specification {
@AutoCleanup
HibernateDatastore datastore
- private HibernateDatastore boot(List<Class> group, boolean generated) {
+ private HibernateDatastore boot(List<Class> group) {
datastore?.close()
datastore = new HibernateDatastore([
- 'dataSource.url' : "jdbc:h2:mem:ni${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
- 'dataSource.dbCreate' : 'create-drop',
- 'hibernate.generatedDomainClasses': generated,
+ 'dataSource.url' : "jdbc:h2:mem:ni${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
+ 'dataSource.dbCreate': 'create-drop',
], group as Class[])
return datastore
}
@@ -79,16 +77,11 @@ class GeneratedDomainClassesNaturalIdSpec extends Specification {
}
@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]
-
+ void "#label has the unique key classic binding gave it"() {
when:
- Map<String, Object> binder = schema(boot(group, false), false, natural)
- Map<String, Object> generated = schema(boot(group, true), false, natural)
+ Map<String, Object> generated = schema(boot(group))
then:
- generated == binder
generated["table ${table}".toString()].uniqueKeys*.columns == keys
where:
@@ -109,34 +102,29 @@ class GeneratedDomainClassesNaturalIdSpec extends Specification {
}
@Unroll
- void "the unique key of #label has the name the domain binder gives it"() {
+ void "the unique key of #label has the name classic binding gave it"() {
when:
- Map<String, Object> binder = schema(boot(group, false), true, false)
- Map<String, Object> generated = schema(boot(group, true), true, false)
+ Map<String, Object> generated = schema(boot(group), true, false)
then:
- generated["table ${table}".toString()].uniqueKeys == binder["table ${table}".toString()].uniqueKeys
- generated["table ${table}".toString()].uniqueKeys.size() == count
+ generated["table ${table}".toString()].uniqueKeys == [[name: name, columns: columns]]
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
+ label | group | table | name | columns
+ 'a subclass' | [NiRoot, NiChild] | 'ni_root' | 'UK868cf40f2801ac5a27cde3ba469f' | ['code']
+ 'a subclass naming a parent column' | [NiMixRoot, NiMixChild] | 'ni_mix_root' | 'UKdc3bdb311906a1fbe49ac1b8a581' | ['code', 'name']
+ 'a subclass of a joined hierarchy' | [NiJRoot, NiJChild] | 'nijchild' | 'UK3e8ad2bb84eeaee96fb4e1034965' | ['region', 'code']
+ 'a subclass three levels down' | [NiGrand, NiGrandChild, NiGrandGrand] | 'ni_grand' | 'UKd36b210bf75669fdf400511f478f' | ['extra', 'code']
}
@Unroll
- void "#label rejects a duplicate natural id and accepts a distinct one, as the domain binder does"() {
+ void "#label rejects a duplicate natural id and accepts a distinct one, as classic binding did"() {
when:
- Map<Boolean, List> outcome = [false, true].collectEntries { boolean generated ->
- boot(group, generated)
- [(generated): attempts.collect { Map values -> save(type, values) }]
- }
+ boot(group)
+ List outcome = attempts.collect { Map values -> save(type, values) }
then:
- outcome[true] == outcome[false]
- outcome[true] == expected
+ outcome == expected
where:
label | group | type | attempts | expected
@@ -147,51 +135,39 @@ class GeneratedDomainClassesNaturalIdSpec extends Specification {
'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"() {
+ void "a subclass with a natural id is stored, found by query and updated as classic binding did, 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']) ==
+ boot([NiRoot, NiChild, NiMutRoot, NiMutChild])
+ 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 } }
+
+ then: "what classic binding could do is done the same way"
+ steps.subMap(['saveImmutable', 'saveMutable', 'listImmutable', 'findImmutable']) ==
+ [saveImmutable: 'ok: 1', saveMutable: 'ok: 1', listImmutable: 'ok: [a]', findImmutable: 'ok: n']
+
+ and: "the entity is also loaded by id (classic binding marked the properties as natural identifiers, which made Hibernate 7 fail on every load of the subclass)"
+ steps.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] }]
- }
+ boot([NiEmb])
+ Long id = NiEmb.withTransaction { NiEmb.newInstance(code: 'a', home: new NiHome(street: 's', city: 'c')).save(failOnError: true, flush: true).id }
+ List outcome = 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']
+ outcome == ['a', 's', 'c']
}
private static String attempt(Closure<?> step) {
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
index d2db542ef1..11fa8c93a6 100644
--- 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
@@ -34,8 +34,8 @@ 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.
+ * Java serialization of a {@code String} or any other value is stored in a binary column, as the classic binding of Grails 8 stored
+ * it; the columns and the bytes stated here are the ones classic binding gave.
*/
class GeneratedDomainClassesSerializableTypeSpec extends Specification {
@@ -44,12 +44,11 @@ class GeneratedDomainClassesSerializableTypeSpec extends Specification {
@AutoCleanup
HibernateDatastore datastore
- private HibernateDatastore boot(List<Class> group, boolean generated) {
+ private HibernateDatastore boot(List<Class> group) {
datastore?.close()
datastore = new HibernateDatastore([
- 'dataSource.url' : "jdbc:h2:mem:tns${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
- 'dataSource.dbCreate' : 'create-drop',
- 'hibernate.generatedDomainClasses': generated,
+ 'dataSource.url' : "jdbc:h2:mem:tns${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
+ 'dataSource.dbCreate': 'create-drop',
], group as Class[])
return datastore
}
@@ -107,13 +106,11 @@ class GeneratedDomainClassesSerializableTypeSpec extends Specification {
}
@Unroll
- void "#label has the column type the domain binder gives it"() {
+ void "#label has the column type classic binding gave it"() {
when:
- Map<String, Map> binder = schema(boot(group, false))
- Map<String, Map> generated = schema(boot(group, true))
+ Map<String, Map> generated = schema(boot(group))
then:
- generated == binder
generated[table].columns[column] == type
where:
@@ -122,27 +119,24 @@ class GeneratedDomainClassesSerializableTypeSpec extends Specification {
'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"() {
+ void "a string typed serializable is stored as the Java serialization of the string, as classic binding stored 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')
+ Map generated = roundTrip(boot([TnSerializableString]), 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"() {
+ void "a byte array typed serializable is stored as its bytes, which the serializable type cannot read back, as with classic binding"() {
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')
+ Map generated = roundTrip(boot([TnSerializableBytes]), TnSerializableBytes, [payload: 'hello'.bytes], 'payload', 'select payload from tn_serializable_bytes')
then:
- generated == binder
+ generated == [stored: [[[104, 101, 108, 108, 111]]], reloaded: 'cannot be read: StreamCorruptedException']
}
- void "a serialized byte array written by the Java serialization is read back by both bindings"() {
+ void "a serialized byte array written by the Java serialization is read back, as with classic binding"() {
given:
byte[] serialized = new ByteArrayOutputStream().with { bytes ->
new ObjectOutputStream(bytes).with { it.writeObject('hello'.bytes); it.flush() }
@@ -150,20 +144,16 @@ class GeneratedDomainClassesSerializableTypeSpec extends Specification {
}
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()]
+ boot([TnSerializableBytes])
+ 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 }
then:
- read[true] == read[false]
- read[true] == 'hello'.bytes.toList()
+ ((byte[]) value).toList() == 'hello'.bytes.toList()
}
}
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesSerializationSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesSerializationSpec.groovy
index afe41d37c7..b997d793f5 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesSerializationSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesSerializationSpec.groovy
@@ -37,24 +37,23 @@ import org.grails.orm.hibernate.HibernateDatastore
/**
* What the generated carrier classes may not do: leak. They have the names of the real domain classes and live in a loader of
- * their own, so serialization, by-name lookups and every Class that Hibernate hands out must give the real class, as in
- * binder mode.
+ * their own, so serialization, by-name lookups and every Class that Hibernate hands out must give the real class, as with the
+ * classic binding of Grails 8.
*/
class GeneratedDomainClassesSerializationSpec extends Specification {
@AutoCleanup
HibernateDatastore datastore
- private HibernateDatastore boot(boolean generated) {
+ private HibernateDatastore boot() {
datastore?.close()
datastore = new HibernateDatastore(DatastoreUtils.createPropertyResolver([
- 'dataSource.url' : "jdbc:h2:mem:gdcSer${generated}${System.nanoTime()};LOCK_TIMEOUT=10000".toString(),
- 'dataSource.dbCreate' : 'create-drop',
- 'dataSource.dialect' : H2Dialect.name,
- 'hibernate.hbm2ddl.auto' : 'create-drop',
- 'hibernate.cache.queries' : 'false',
- 'hibernate.cache.use_query_cache' : 'false',
- 'hibernate.generatedDomainClasses': generated,
+ 'dataSource.url' : "jdbc:h2:mem:gdcSer${System.nanoTime()};LOCK_TIMEOUT=10000".toString(),
+ 'dataSource.dbCreate' : 'create-drop',
+ 'dataSource.dialect' : H2Dialect.name,
+ 'hibernate.hbm2ddl.auto' : 'create-drop',
+ 'hibernate.cache.queries' : 'false',
+ 'hibernate.cache.use_query_cache': 'false',
]), GdcSerAuthor, GdcSerBook, GdcSerPet, GdcSerDog, GdcSerComposite)
return datastore
}
@@ -74,8 +73,8 @@ class GeneratedDomainClassesSerializationSpec extends Specification {
type.classLoader?.getClass()?.simpleName == 'ByteArrayClassLoader')
}
- private Map scenario(boolean generated) {
- HibernateDatastore booted = boot(generated)
+ private Map scenario() {
+ HibernateDatastore booted = boot()
Map r = [:]
Long authorId
GdcSerAuthor.withTransaction {
@@ -207,72 +206,62 @@ class GeneratedDomainClassesSerializationSpec extends Specification {
return r
}
- private static final Map<Boolean, Map> RESULTS = [:]
+ private static Map RESULTS
- private Map results(boolean generated) {
- return RESULTS.computeIfAbsent(generated) { scenario(generated) }
+ private Map results() {
+ if (RESULTS == null) {
+ RESULTS = scenario()
+ }
+ return RESULTS
}
def "real instances serialize and deserialize as the real classes, detached, with their collections, and reattach"() {
when:
- Map generated = results(true)
- Map binder = results(false)
+ Map generated = results()
then: 'a detached entity with an initialized collection and an embedded value comes back as the real classes'
generated.detachedCopy == [true, 'a', ['b1', 'b2'], 'org.hibernate.collection.spi.PersistentSet', true, GdcSerStatus.OPEN, true]
!generated.streamMentionsGenerated
- and: 'an uninitialized collection stays lazy and fails outside a session, as it does in binder mode'
+ and: 'an uninitialized collection stays lazy and fails outside a session, as it did with classic binding'
generated.lazyInitializedBefore == false
generated.lazyAccess == 'LazyInitializationException'
and: 'the detached copy merges into a new session, cascading to its collection, and a deserialized entity reattaches'
generated.afterMerge == ['renamed', ['b1 changed', 'b2'], 1]
generated.afterAttach == 'reattached'
-
- and: 'all of it is what binder mode does'
- ['detachedCopy', 'streamMentionsGenerated', 'lazyInitializedBefore', 'lazyAccess', 'afterMerge', 'afterAttach'].every {
- generated[it] == binder[it]
- }
}
- def "proxies are proxies of the real class, and a serialized proxy deserializes as binder mode's does"() {
+ def "proxies are proxies of the real class, and a serialized proxy deserializes as it did with classic binding"() {
when:
- Map generated = results(true)
- Map binder = results(false)
+ Map generated = results()
then: 'superclass, persistent class, entity name and Hibernate.getClass are the real ones'
generated.proxy == [true, true, true, true, true, true, true]
- generated.proxySerialization == binder.proxySerialization
- generated.proxySerialization[2] == 'reattached'
+
+ and: 'a serialized proxy deserializes as a plain instance of the real class with its state, as it did with classic binding'
+ generated.proxySerialization == [false, false, 'reattached']
}
def "lookups by entity name, class name and class give the real class"() {
when:
- Map generated = results(true)
- Map binder = results(false)
+ Map generated = results()
then:
generated.byName == [
true, GdcSerAuthor.name, true, [GdcSerDog.name, GdcSerPet.name], true, true, true, GdcSerAuthor.name,
true, true, true, true, true, 1, 1, true, true,
]
- generated.byName == binder.byName
generated.polymorphic == [true, GdcSerDog.name, [GdcSerDog.name]]
- generated.polymorphic == binder.polymorphic
generated.composite == [[true, 'x']]
- generated.embeddedQueries == binder.embeddedQueries
generated.embeddedQueries == [[[true, 'c']], 1, 1, 1, 1]
}
def "no class that the mapping and JPA metamodels hand out is a generated class, but the cached type of an embedded value and of a composite identifier"() {
when:
- Map generated = results(true)
- Map binder = results(false)
+ Map generated = results()
then: 'the model has the real classes, under their own names'
- binder.leakedClasses == []
- generated.mappedClasses == binder.mappedClasses
generated.mappedClasses.containsAll([GdcSerAuthor, GdcSerBook, GdcSerPet, GdcSerDog, GdcSerComposite, GdcSerAddress]*.name)
and: 'Hibernate builds the component type of an embedded property and of a composite identifier before the switch to the real classes and caches its class, which has no public way to be reset'
@@ -285,7 +274,7 @@ class GeneratedDomainClassesSerializationSpec extends Specification {
@PendingFeature(reason = 'Component.getType() caches the component class when Hibernate first asks for the type while binding the generated classes; Component has no public way to reset it')
def "the returned class of an embedded property and of a composite identifier is the real class"() {
expect:
- results(true).leakedClasses == []
+ results().leakedClasses == []
}
}
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesSharedEmbeddedCollectionSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesSharedEmbeddedCollectionSpec.groovy
index 40fb4941d2..933ac24280 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesSharedEmbeddedCollectionSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesSharedEmbeddedCollectionSpec.groovy
@@ -40,11 +40,11 @@ import spock.lang.Specification
import org.grails.orm.hibernate.HibernateDatastore
/**
- * A collection inside an embedded type that more than one embedded property reaches. The domain binder names its table and its key
- * column after the embedded type, so all the owners share one table whose key is a foreign key to the owner that was bound first (the
- * rows of any other owner violate it), and it fails to boot when the properties are named alike. The generated mode gives every owner a
- * table of its own: the first owner, in the order of the entity name and then the property path, keeps the names of the binder, the
- * others get names qualified with their owner and the path of their embedded property.
+ * A collection inside an embedded type that more than one embedded property reaches. The classic binding of Grails 8 named its table
+ * and its key column after the embedded type, so all the owners shared one table whose key was a foreign key to the owner that was
+ * bound first (the rows of any other owner violated it), and it failed to boot when the properties were named alike. Native binding
+ * gives every owner a table of its own: the first owner, in the order of the entity name and then the property path, keeps the names
+ * classic binding used, the others get names qualified with their owner and the path of their embedded property.
*/
class GeneratedDomainClassesSharedEmbeddedCollectionSpec extends Specification {
@@ -53,19 +53,18 @@ class GeneratedDomainClassesSharedEmbeddedCollectionSpec extends Specification {
@AutoCleanup
HibernateDatastore datastore
- private HibernateDatastore boot(List<Class> group, boolean generated) {
+ private HibernateDatastore boot(List<Class> group) {
datastore?.close()
datastore = new HibernateDatastore([
- 'dataSource.url' : "jdbc:h2:mem:gse${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
- 'dataSource.dbCreate' : 'create-drop',
- 'hibernate.generatedDomainClasses': generated,
+ 'dataSource.url' : "jdbc:h2:mem:gse${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
+ 'dataSource.dbCreate': 'create-drop',
], group as Class[])
return datastore
}
/** The tables of the boot model with their columns and the table each foreign key points at. */
- private Map<String, Map> schema(List<Class> group, boolean generated) {
- HibernateDatastore booted = boot(group, generated)
+ private Map<String, Map> schema(List<Class> group) {
+ HibernateDatastore booted = boot(group)
Map<String, Map> result = new TreeMap<String, Map>()
for (Table table : booted.metadata.collectTableMappings()) {
if (table.physicalTable) {
@@ -84,35 +83,9 @@ class GeneratedDomainClassesSharedEmbeddedCollectionSpec extends Specification {
}
}
- void "the domain binder binds one table whose key points at the first owner only, so the rows of the other owner are refused"() {
+ void "the first owner keeps the table and the key column classic binding used, the other one gets names qualified with its owner and its property"() {
when:
- Map<String, Map> binder = schema([EmbeddedCollectionOwnerC, EmbeddedCollectionOwnerD], false)
-
- then: "one collection table, a foreign key to one of the owners"
- binder.keySet().count { it.contains('words') } == 1
- binder.values().find { it.columns.contains('embedded_collection_holder_id') }.foreignKeys.size() == 1
-
- when: "the second owner stores a collection"
- EmbeddedCollectionOwnerD.withTransaction {
- new EmbeddedCollectionOwnerD(second: new EmbeddedCollectionHolder(words: ['w'] as Set)).save(failOnError: true, flush: true)
- }
-
- then: "its row violates the foreign key to the other owner"
- thrown(Exception)
- }
-
- void "the domain binder cannot boot owners that embed the type under the same name"() {
- when:
- boot([EmbeddedCollectionOwnerA, EmbeddedCollectionOwnerB], false)
-
- then:
- Exception e = thrown()
- rootOf(e).getClass().simpleName == 'DuplicateMappingException'
- }
-
- void "the first owner keeps the table and the key column of the binder, the other one gets names qualified with its owner and its property"() {
- when:
- Map<String, Map> generated = schema([EmbeddedCollectionOwnerC, EmbeddedCollectionOwnerD], true)
+ Map<String, Map> generated = schema([EmbeddedCollectionOwnerC, EmbeddedCollectionOwnerD])
then:
generated.keySet() == ['embedded_collection_holder_words', 'embedded_collection_ownerc', 'embedded_collection_ownerd',
@@ -125,17 +98,21 @@ class GeneratedDomainClassesSharedEmbeddedCollectionSpec extends Specification {
void "the owners are told apart by the name of the entity whatever the order they are given in"() {
expect:
- schema([EmbeddedCollectionOwnerD, EmbeddedCollectionOwnerC], true) == schema([EmbeddedCollectionOwnerC, EmbeddedCollectionOwnerD], true)
+ schema([EmbeddedCollectionOwnerD, EmbeddedCollectionOwnerC]) == schema([EmbeddedCollectionOwnerC, EmbeddedCollectionOwnerD])
}
- void "a type that only one owner embeds keeps exactly the schema of the domain binder"() {
+ void "a type that only one owner embeds keeps exactly the schema classic binding created"() {
expect:
- schema([EmbeddedCollectionOwnerC], true) == schema([EmbeddedCollectionOwnerC], false)
+ schema([EmbeddedCollectionOwnerC]) == [
+ embedded_collection_holder_words: [columns: ['embedded_collection_holder_id', 'words_java_lang_string'],
+ foreignKeys: ['[embedded_collection_holder_id] -> embedded_collection_ownerc']],
+ embedded_collection_ownerc : [columns: ['id', 'version'], foreignKeys: []],
+ ]
}
void "each owner stores, reads back and deletes its own collection"() {
given:
- boot([EmbeddedCollectionOwnerC, EmbeddedCollectionOwnerD], true)
+ boot([EmbeddedCollectionOwnerC, EmbeddedCollectionOwnerD])
when:
Long c = EmbeddedCollectionOwnerC.withTransaction {
@@ -172,7 +149,7 @@ class GeneratedDomainClassesSharedEmbeddedCollectionSpec extends Specification {
void "owners that embed the type under the same name boot with qualified names for all but the first, and store their own collections"() {
when:
- Map<String, Map> generated = schema([EmbeddedCollectionOwnerA, EmbeddedCollectionOwnerB], true)
+ Map<String, Map> generated = schema([EmbeddedCollectionOwnerA, EmbeddedCollectionOwnerB])
then:
generated.keySet() == ['embedded_collection_holder_words', 'embedded_collection_ownera', 'embedded_collection_ownerb',
@@ -193,24 +170,9 @@ class GeneratedDomainClassesSharedEmbeddedCollectionSpec extends Specification {
EmbeddedCollectionOwnerB.withNewSession { EmbeddedCollectionOwnerB.get(b).inner.words.sort() } == ['b1', 'b2']
}
- void "one owner that embeds the type twice has a table for each property, where the domain binder mixes the elements of both"() {
- when: "the domain binder stores the elements of both properties in one table"
- boot([EmbeddedCollectionOwnerTwice], false)
- Long classic = EmbeddedCollectionOwnerTwice.withTransaction {
- new EmbeddedCollectionOwnerTwice(
- home: new EmbeddedCollectionHolder(words: ['h'] as Set),
- work: new EmbeddedCollectionHolder(words: ['w'] as Set)).save(failOnError: true, flush: true).id
- }
- List classicRead = EmbeddedCollectionOwnerTwice.withNewSession {
- EmbeddedCollectionOwnerTwice owner = EmbeddedCollectionOwnerTwice.get(classic)
- [owner.home.words.sort(), owner.work.words.sort()]
- }
-
- then: "each property sees the elements of the other"
- classicRead == [['h', 'w'], ['h', 'w']]
-
+ void "one owner that embeds the type twice has a table for each property (classic binding mixed the elements of both in one table)"() {
when:
- Map<String, Map> generated = schema([EmbeddedCollectionOwnerTwice], true)
+ Map<String, Map> generated = schema([EmbeddedCollectionOwnerTwice])
Long id = EmbeddedCollectionOwnerTwice.withTransaction {
new EmbeddedCollectionOwnerTwice(
home: new EmbeddedCollectionHolder(words: ['h'] as Set),
@@ -227,7 +189,7 @@ class GeneratedDomainClassesSharedEmbeddedCollectionSpec extends Specification {
void "a collection of entities and a list inside an embedded type get a table of their own for each owner"() {
when:
- Map<String, Map> generated = schema([EmbeddedItemsOwnerA, EmbeddedItemsOwnerB, EmbeddedCollectionItem], true)
+ Map<String, Map> generated = schema([EmbeddedItemsOwnerA, EmbeddedItemsOwnerB, EmbeddedCollectionItem])
then:
generated.keySet() == [
@@ -254,7 +216,7 @@ class GeneratedDomainClassesSharedEmbeddedCollectionSpec extends Specification {
void "a collection in a nested embedded type and one in a direct embedded property each get a table of their own"() {
when:
- Map<String, Map> generated = schema([EmbeddedNestedOwnerA, EmbeddedNestedOwnerB], true)
+ Map<String, Map> generated = schema([EmbeddedNestedOwnerA, EmbeddedNestedOwnerB])
then:
generated.keySet() == [
@@ -278,12 +240,4 @@ class GeneratedDomainClassesSharedEmbeddedCollectionSpec extends Specification {
[owner.mid.deep.words.sort(), owner.direct.words.sort()]
} == [['b-deep'], ['b-direct']]
}
-
- private static Throwable rootOf(Throwable e) {
- Throwable root = e
- while (root.cause != null && root.cause != root) {
- root = root.cause
- }
- return root
- }
}
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesTenancyModesSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesTenancyModesSpec.groovy
index 02a5d7285c..04e263d99b 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesTenancyModesSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesTenancyModesSpec.groovy
@@ -33,8 +33,8 @@ import org.grails.datastore.mapping.multitenancy.resolvers.SystemPropertyTenantR
import org.grails.orm.hibernate.HibernateDatastore
/**
- * Schema and database per tenant over the generated mapping: every tenant has its own session factory, built from the same
- * generated classes, and its tables are those the domain binder creates. Discriminator tenancy has its own spec.
+ * Schema and database per tenant: every tenant has its own session factory, built from the same generated classes, and its
+ * tables are those the classic binding of Grails 8 created, stated here. Discriminator tenancy has its own spec.
*/
@RestoreSystemProperties
class GeneratedDomainClassesTenancyModesSpec extends Specification {
@@ -48,19 +48,18 @@ class GeneratedDomainClassesTenancyModesSpec extends Specification {
tenants = ['north', 'south']
}
- private HibernateDatastore boot(boolean generated, MultiTenancySettings.MultiTenancyMode mode, Map extra = [:]) {
+ private HibernateDatastore boot(MultiTenancySettings.MultiTenancyMode mode, Map extra = [:]) {
datastore?.close()
System.setProperty(SystemPropertyTenantResolver.PROPERTY_NAME, 'north')
datastore = new HibernateDatastore(DatastoreUtils.createPropertyResolver([
'grails.gorm.multiTenancy.mode' : mode,
'grails.gorm.multiTenancy.tenantResolverClass': GdcTenantsResolver,
- 'dataSource.url' : "jdbc:h2:mem:gdcTenancy${generated}${System.nanoTime()};LOCK_TIMEOUT=10000".toString(),
+ 'dataSource.url' : "jdbc:h2:mem:gdcTenancy${System.nanoTime()};LOCK_TIMEOUT=10000".toString(),
'dataSource.dbCreate' : 'create',
'dataSource.dialect' : H2Dialect.name,
'hibernate.hbm2ddl.auto' : 'create',
'hibernate.cache.queries' : 'false',
'hibernate.cache.use_query_cache' : 'false',
- 'hibernate.generatedDomainClasses' : generated,
] + extra), GdcTenantAuthor, GdcTenantBook)
return datastore
}
@@ -99,8 +98,8 @@ class GeneratedDomainClassesTenancyModesSpec extends Specification {
return result
}
- private Map scenario(boolean generated) {
- HibernateDatastore booted = boot(generated, MultiTenancySettings.MultiTenancyMode.SCHEMA)
+ private Map scenario() {
+ HibernateDatastore booted = boot(MultiTenancySettings.MultiTenancyMode.SCHEMA)
Map result = [:]
['north', 'south'].each { String tenant ->
Tenants.withId(tenant) {
@@ -135,29 +134,30 @@ class GeneratedDomainClassesTenancyModesSpec extends Specification {
return result
}
- def "schema per tenant isolates the rows of each tenant and builds each tenant's tables like binder mode"() {
+ def "schema per tenant isolates the rows of each tenant and builds each tenant's tables as classic binding built them"() {
when:
- Map binder = scenario(false)
- Map generated = scenario(true)
+ Map generated = scenario()
then: 'rows stay in their tenant, through a lazy collection too'
generated.counts == [north: [1, 2, ['north one', 'north two']], south: [1, 3, ['south one', 'south three', 'south two']]]
generated.east == 0
generated.each == [north: 1, south: 1, east: 0]
- and: 'every tenant schema has the tables, columns and constraints binder mode creates'
- generated.tables.keySet().any { it.startsWith('north.') }
- generated.tables.keySet().any { it.startsWith('south.') }
- generated.tables.keySet().any { it.startsWith('east.') }
- generated.tables == binder.tables
- generated.constraints == binder.constraints
- generated.counts == binder.counts
- generated.each == binder.each
+ and: 'every tenant schema has the tables, columns and constraints classic binding created'
+ generated.tables == ['PUBLIC', 'east', 'north', 'south'].collectEntries { String schema ->
+ [("${schema}.GDC_TENANT_AUTHOR".toString()): ['ID BIGINT NO', 'NAME CHARACTER VARYING YES', 'VERSION BIGINT NO'],
+ ("${schema}.GDC_TENANT_BOOK".toString()) : ['AUTHOR_ID BIGINT YES', 'ID BIGINT NO', 'TITLE CHARACTER VARYING YES', 'VERSION BIGINT NO']]
+ }
+ generated.constraints == ['PUBLIC', 'east', 'north', 'south'].collectEntries { String schema ->
+ [("${schema}.GDC_TENANT_AUTHOR PRIMARY KEY".toString()): 1,
+ ("${schema}.GDC_TENANT_BOOK FOREIGN KEY".toString()) : 1,
+ ("${schema}.GDC_TENANT_BOOK PRIMARY KEY".toString()) : 1]
+ }
}
def "a session factory of a tenant maps the real domain classes under their own names"() {
when:
- HibernateDatastore booted = boot(true, MultiTenancySettings.MultiTenancyMode.SCHEMA)
+ HibernateDatastore booted = boot(MultiTenancySettings.MultiTenancyMode.SCHEMA)
HibernateDatastore north = booted.getDatastoreForConnection('north')
then:
@@ -168,68 +168,64 @@ class GeneratedDomainClassesTenancyModesSpec extends Specification {
}
}
- def "tables with and without an explicit schema land in the schema binder mode puts them in, under a default schema"() {
+ def "tables with and without an explicit schema land in the schema classic binding put them in, under a default schema"() {
when:
- Map results = [false, true].collectEntries { boolean generated ->
- datastore?.close()
- datastore = new HibernateDatastore(DatastoreUtils.createPropertyResolver([
- 'dataSource.url' : "jdbc:h2:mem:gdcSchemas${generated}${System.nanoTime()};LOCK_TIMEOUT=10000;INIT=CREATE SCHEMA IF NOT EXISTS gdc_default\\;CREATE SCHEMA IF NOT EXISTS gdc_shared".toString(),
- 'dataSource.dbCreate' : 'create',
- 'dataSource.dialect' : H2Dialect.name,
- 'hibernate.hbm2ddl.auto' : 'create',
- 'hibernate.default_schema' : 'gdc_default',
- 'hibernate.generatedDomainClasses': generated,
- ]), GdcSchemaPlain, GdcSchemaOwner, GdcSchemaChild)
- GdcSchemaOwner.withTransaction {
- GdcSchemaOwner owner = new GdcSchemaOwner(name: 'owner')
- owner.tags = ['a', 'b'] as Set
- owner.addToChildren(new GdcSchemaChild(label: 'child'))
- owner.save(flush: true, failOnError: true)
- new GdcSchemaPlain(name: 'plain').save(flush: true, failOnError: true)
- }
- Map found = GdcSchemaOwner.withNewSession {
- GdcSchemaOwner owner = GdcSchemaOwner.first()
- [tags: owner.tags.sort(), children: owner.children*.label, plain: GdcSchemaPlain.count()]
- }
- [generated, [found: found, tables: tablesAndColumns(datastore.connectionSources.defaultConnectionSource.dataSource)]]
+ datastore?.close()
+ datastore = new HibernateDatastore(DatastoreUtils.createPropertyResolver([
+ 'dataSource.url' : "jdbc:h2:mem:gdcSchemas${System.nanoTime()};LOCK_TIMEOUT=10000;INIT=CREATE SCHEMA IF NOT EXISTS gdc_default\\;CREATE SCHEMA IF NOT EXISTS gdc_shared".toString(),
+ 'dataSource.dbCreate' : 'create',
+ 'dataSource.dialect' : H2Dialect.name,
+ 'hibernate.hbm2ddl.auto' : 'create',
+ 'hibernate.default_schema': 'gdc_default',
+ ]), GdcSchemaPlain, GdcSchemaOwner, GdcSchemaChild)
+ GdcSchemaOwner.withTransaction {
+ GdcSchemaOwner owner = new GdcSchemaOwner(name: 'owner')
+ owner.tags = ['a', 'b'] as Set
+ owner.addToChildren(new GdcSchemaChild(label: 'child'))
+ owner.save(flush: true, failOnError: true)
+ new GdcSchemaPlain(name: 'plain').save(flush: true, failOnError: true)
+ }
+ Map found = GdcSchemaOwner.withNewSession {
+ GdcSchemaOwner owner = GdcSchemaOwner.first()
+ [tags: owner.tags.sort(), children: owner.children*.label, plain: GdcSchemaPlain.count()]
}
+ Map<String, List<String>> tables = tablesAndColumns(datastore.connectionSources.defaultConnectionSource.dataSource)
then:
- results[true].found == [tags: ['a', 'b'], children: ['child'], plain: 1]
- results[true].tables.keySet() == ['GDC_DEFAULT.GDC_SCHEMA_CHILD', 'GDC_DEFAULT.GDC_SCHEMA_PLAIN', 'GDC_SHARED.GDC_SCHEMA_OWNER', 'GDC_SHARED.GDC_SCHEMA_OWNER_TAGS'] as Set
- results[true].tables == results[false].tables
+ found == [tags: ['a', 'b'], children: ['child'], plain: 1]
+ tables.keySet() == ['GDC_DEFAULT.GDC_SCHEMA_CHILD', 'GDC_DEFAULT.GDC_SCHEMA_PLAIN', 'GDC_SHARED.GDC_SCHEMA_OWNER', 'GDC_SHARED.GDC_SCHEMA_OWNER_TAGS'] as Set
}
- def "database per tenant isolates the rows of each tenant and builds each database like binder mode"() {
+ def "database per tenant isolates the rows of each tenant and builds each database as classic binding built it"() {
when:
- Map results = [false, true].collectEntries { boolean generated ->
- HibernateDatastore booted = boot(generated, MultiTenancySettings.MultiTenancyMode.DATABASE, [
- 'dataSources.north.url': "jdbc:h2:mem:gdcTenancyNorth${generated}${System.nanoTime()};LOCK_TIMEOUT=10000".toString(),
- 'dataSources.south.url': "jdbc:h2:mem:gdcTenancySouth${generated}${System.nanoTime()};LOCK_TIMEOUT=10000".toString(),
- ])
- ['north', 'south'].each { String tenant ->
- Tenants.withId(tenant) {
- GdcTenantAuthor.withTransaction {
- GdcTenantAuthor author = new GdcTenantAuthor(name: "author of ${tenant}".toString())
- author.addToBooks(new GdcTenantBook(title: "${tenant} one".toString()))
- author.save(flush: true, failOnError: true)
- }
+ HibernateDatastore booted = boot(MultiTenancySettings.MultiTenancyMode.DATABASE, [
+ 'dataSources.north.url': "jdbc:h2:mem:gdcTenancyNorth${System.nanoTime()};LOCK_TIMEOUT=10000".toString(),
+ 'dataSources.south.url': "jdbc:h2:mem:gdcTenancySouth${System.nanoTime()};LOCK_TIMEOUT=10000".toString(),
+ ])
+ ['north', 'south'].each { String tenant ->
+ Tenants.withId(tenant) {
+ GdcTenantAuthor.withTransaction {
+ GdcTenantAuthor author = new GdcTenantAuthor(name: "author of ${tenant}".toString())
+ author.addToBooks(new GdcTenantBook(title: "${tenant} one".toString()))
+ author.save(flush: true, failOnError: true)
}
}
- Map counts = ['north', 'south'].collectEntries { String tenant ->
- [tenant, Tenants.withId(tenant) {
- GdcTenantAuthor.withNewSession { [GdcTenantAuthor.count(), GdcTenantAuthor.first().books*.title] }
- }]
- }
- [generated, [counts: counts,
- north: tablesAndColumns(booted.connectionSources.getConnectionSource('north').dataSource),
- south: constraints(booted.connectionSources.getConnectionSource('south').dataSource)]]
+ }
+ Map counts = ['north', 'south'].collectEntries { String tenant ->
+ [tenant, Tenants.withId(tenant) {
+ GdcTenantAuthor.withNewSession { [GdcTenantAuthor.count(), GdcTenantAuthor.first().books*.title] }
+ }]
}
then:
- results[true].counts == [north: [1, ['north one']], south: [1, ['south one']]]
- results[true].north.keySet().any { it.endsWith('.GDC_TENANT_AUTHOR') }
- results[true] == results[false]
+ counts == [north: [1, ['north one']], south: [1, ['south one']]]
+ tablesAndColumns(booted.connectionSources.getConnectionSource('north').dataSource) == [
+ 'PUBLIC.GDC_TENANT_AUTHOR': ['ID BIGINT NO', 'NAME CHARACTER VARYING YES', 'VERSION BIGINT NO'],
+ 'PUBLIC.GDC_TENANT_BOOK' : ['AUTHOR_ID BIGINT YES', 'ID BIGINT NO', 'TITLE CHARACTER VARYING YES', 'VERSION BIGINT NO'],
+ ]
+ constraints(booted.connectionSources.getConnectionSource('south').dataSource) == [
+ 'PUBLIC.GDC_TENANT_AUTHOR PRIMARY KEY': 1, 'PUBLIC.GDC_TENANT_BOOK FOREIGN KEY': 1, 'PUBLIC.GDC_TENANT_BOOK PRIMARY KEY': 1,
+ ]
}
}
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesTenantTypeSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesTenantTypeSpec.groovy
index 60d40ab8ea..a1749905aa 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesTenantTypeSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesTenantTypeSpec.groovy
@@ -34,8 +34,8 @@ import org.grails.datastore.mapping.multitenancy.resolvers.SystemPropertyTenantR
import org.grails.orm.hibernate.HibernateDatastore
/**
- * A multi-tenant id that has a mapped type. The domain binder gives the column the type and builds the tenant filter from the bound
- * property, so a tenant still sees only its own rows; the generated mode does the same instead of refusing the mapping.
+ * A multi-tenant id that has a mapped type. The column gets the type and the tenant filter compares it, so a tenant still sees only
+ * its own rows, as with the classic binding of Grails 8; native binding does the same instead of refusing the mapping.
*/
@RestoreSystemProperties
class GeneratedDomainClassesTenantTypeSpec extends Specification {
@@ -45,7 +45,7 @@ class GeneratedDomainClassesTenantTypeSpec extends Specification {
@AutoCleanup
HibernateDatastore datastore
- private HibernateDatastore boot(boolean generated) {
+ private HibernateDatastore boot() {
datastore?.close()
System.setProperty(SystemPropertyTenantResolver.PROPERTY_NAME, 'ford')
datastore = new HibernateDatastore(DatastoreUtils.createPropertyResolver([
@@ -56,7 +56,6 @@ class GeneratedDomainClassesTenantTypeSpec extends Specification {
'dataSource.dialect' : H2Dialect.name,
'hibernate.cache.queries' : 'false',
'hibernate.cache.use_query_cache' : 'false',
- 'hibernate.generatedDomainClasses' : generated,
]), GdtTypedTenantItem)
return datastore
}
@@ -73,38 +72,31 @@ class GeneratedDomainClassesTenantTypeSpec extends Specification {
return result
}
- void "the tenant id column has the mapped type in both modes"() {
+ void "the tenant id column has the mapped type"() {
when:
- boot(false)
- Map<String, String> binder = columns()
- boot(true)
+ boot()
Map<String, String> generated = columns()
then:
- generated == binder
generated['gdt_typed_tenant_item.company_id'].startsWith('clob')
}
- void "a tenant sees only its own rows in both modes"() {
+ void "a tenant sees only its own rows"() {
when:
- Map<Boolean, List> results = [false, true].collectEntries { boolean generated ->
- boot(generated)
- System.setProperty(SystemPropertyTenantResolver.PROPERTY_NAME, 'ford')
- GdtTypedTenantItem.withTransaction { new GdtTypedTenantItem(name: 'mustang').save(failOnError: true, flush: true) }
- System.setProperty(SystemPropertyTenantResolver.PROPERTY_NAME, 'tesla')
- GdtTypedTenantItem.withTransaction {
- new GdtTypedTenantItem(name: 'model s').save(failOnError: true, flush: true)
- new GdtTypedTenantItem(name: 'model 3').save(failOnError: true, flush: true)
- }
- List tesla = GdtTypedTenantItem.withNewSession { [GdtTypedTenantItem.count(), GdtTypedTenantItem.list()*.name.sort()] }
- System.setProperty(SystemPropertyTenantResolver.PROPERTY_NAME, 'ford')
- List ford = GdtTypedTenantItem.withNewSession { [GdtTypedTenantItem.count(), GdtTypedTenantItem.list()*.name, GdtTypedTenantItem.findByName('model s')] }
- [(generated): [tesla, ford]]
+ boot()
+ System.setProperty(SystemPropertyTenantResolver.PROPERTY_NAME, 'ford')
+ GdtTypedTenantItem.withTransaction { new GdtTypedTenantItem(name: 'mustang').save(failOnError: true, flush: true) }
+ System.setProperty(SystemPropertyTenantResolver.PROPERTY_NAME, 'tesla')
+ GdtTypedTenantItem.withTransaction {
+ new GdtTypedTenantItem(name: 'model s').save(failOnError: true, flush: true)
+ new GdtTypedTenantItem(name: 'model 3').save(failOnError: true, flush: true)
}
+ List tesla = GdtTypedTenantItem.withNewSession { [GdtTypedTenantItem.count(), GdtTypedTenantItem.list()*.name.sort()] }
+ System.setProperty(SystemPropertyTenantResolver.PROPERTY_NAME, 'ford')
+ List ford = GdtTypedTenantItem.withNewSession { [GdtTypedTenantItem.count(), GdtTypedTenantItem.list()*.name, GdtTypedTenantItem.findByName('model s')] }
then:
- results[true] == results[false]
- results[true] == [[2, ['model 3', 'model s']], [1, ['mustang'], null]]
+ [tesla, ford] == [[2, ['model 3', 'model s']], [1, ['mustang'], null]]
}
}
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesTypeMismatchSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesTypeMismatchSpec.groovy
index e871fe3c0c..fe0c4fb1e9 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesTypeMismatchSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesTypeMismatchSpec.groovy
@@ -29,10 +29,9 @@ import spock.lang.Unroll
import org.grails.orm.hibernate.HibernateDatastore
/**
- * A registered type name for a different Java type than the property's, for example {@code type: 'string'} on an {@code Integer}. The
- * domain binder resolves the name and not the property's class: the column has the registered type's SQL type, and the type cannot
- * convert the value, so a value that is not null fails when it is saved with a {@code ClassCastException}. The generated mode boots with the
- * same column and fails the same way.
+ * A registered type name for a different Java type than the property's, for example {@code type: 'string'} on an {@code Integer}. As
+ * the classic binding of Grails 8 did, the name is resolved and not the property's class: the column has the registered type's SQL type,
+ * and the type cannot convert the value, so a value that is not null fails when it is saved with a {@code ClassCastException}.
*/
class GeneratedDomainClassesTypeMismatchSpec extends Specification {
@@ -41,12 +40,11 @@ class GeneratedDomainClassesTypeMismatchSpec extends Specification {
@AutoCleanup
HibernateDatastore datastore
- private HibernateDatastore boot(List<Class> group, boolean generated) {
+ private HibernateDatastore boot(List<Class> group) {
datastore?.close()
datastore = new HibernateDatastore([
- 'dataSource.url' : "jdbc:h2:mem:tm${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
- 'dataSource.dbCreate' : 'create-drop',
- 'hibernate.generatedDomainClasses': generated,
+ 'dataSource.url' : "jdbc:h2:mem:tm${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
+ 'dataSource.dbCreate': 'create-drop',
], group as Class[])
return datastore
}
@@ -81,13 +79,11 @@ class GeneratedDomainClassesTypeMismatchSpec extends Specification {
}
@Unroll
- void "#label has the column type the domain binder gives it"() {
+ void "#label has the column type classic binding gave it"() {
when:
- Map<String, Map> binder = schema(boot([type], false))
- Map<String, Map> generated = schema(boot([type], true))
+ Map<String, Map> generated = schema(boot([type]))
then:
- generated == binder
generated[table].columns.tag.startsWith(sqlType)
where:
@@ -102,22 +98,19 @@ class GeneratedDomainClassesTypeMismatchSpec extends Specification {
}
@Unroll
- void "#label fails to save a value as the domain binder does, and stores null and the other properties"() {
+ void "#label fails to save a value as classic binding did, and stores null and the other properties"() {
when:
- Map<Boolean, Map> outcome = [false, true].collectEntries { boolean generated ->
- boot([type], generated)
- Map steps = [:]
- steps.saveValue = attempt { type.withTransaction { type.newInstance(tag: value, name: 'a').save(failOnError: true, flush: true).id } }
- Long id = null
- steps.saveNull = attempt { id = type.withTransaction { type.newInstance(name: 'b').save(failOnError: true, flush: true).id } }
- steps.reload = attempt { type.withNewSession { Object found = type.get(id); [found.name, found.tag] } }
- [(generated): steps]
- }
+ boot([type])
+ Map steps = [:]
+ steps.saveValue = attempt { type.withTransaction { type.newInstance(tag: value, name: 'a').save(failOnError: true, flush: true).id } }
+ Long id = null
+ steps.saveNull = attempt { id = type.withTransaction { type.newInstance(name: 'b').save(failOnError: true, flush: true).id } }
+ steps.reload = attempt { type.withNewSession { Object found = type.get(id); [found.name, found.tag] } }
then:
- outcome[true] == outcome[false]
- outcome[true].saveValue == 'failed: ClassCastException'
- outcome[true].reload.startsWith('ok: [b, null]')
+ steps.saveValue == 'failed: ClassCastException'
+ steps.saveNull.startsWith('ok: ')
+ steps.reload.startsWith('ok: [b, null]')
where:
label | type | value
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesTypeParametersSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesTypeParametersSpec.groovy
index e6139bac87..f202bf43e9 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesTypeParametersSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesTypeParametersSpec.groovy
@@ -37,8 +37,8 @@ import spock.lang.Unroll
import org.grails.orm.hibernate.HibernateDatastore
/**
- * {@code params} on a {@code type}. The domain binder hands them to the type: a registered type name ignores them, a
- * {@code UserType} that implements {@code ParameterizedType} receives them. The generated mode does the same.
+ * {@code params} on a {@code type}. They are handed to the type, as the classic binding of Grails 8 handed them: a registered type
+ * name ignores them, a {@code UserType} that implements {@code ParameterizedType} receives them.
*/
class GeneratedDomainClassesTypeParametersSpec extends Specification {
@@ -47,12 +47,11 @@ class GeneratedDomainClassesTypeParametersSpec extends Specification {
@AutoCleanup
HibernateDatastore datastore
- private HibernateDatastore boot(List<Class> group, boolean generated) {
+ private HibernateDatastore boot(List<Class> group) {
datastore?.close()
datastore = new HibernateDatastore([
- 'dataSource.url' : "jdbc:h2:mem:tns${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
- 'dataSource.dbCreate' : 'create-drop',
- 'hibernate.generatedDomainClasses': generated,
+ 'dataSource.url' : "jdbc:h2:mem:tns${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
+ 'dataSource.dbCreate': 'create-drop',
], group as Class[])
return datastore
}
@@ -110,13 +109,11 @@ class GeneratedDomainClassesTypeParametersSpec extends Specification {
}
@Unroll
- void "#label has the column type the domain binder gives it"() {
+ void "#label has the column type classic binding gave it"() {
when:
- Map<String, Map> binder = schema(boot(group, false))
- Map<String, Map> generated = schema(boot(group, true))
+ Map<String, Map> generated = schema(boot(group))
then:
- generated == binder
generated[table].columns[column] == type
where:
@@ -126,23 +123,19 @@ class GeneratedDomainClassesTypeParametersSpec extends Specification {
'a string with a user type that takes parameters' | [TnPrefixed] | 'tn_prefixed' | 'label' | 'varchar(255)'
}
- void "a type with type parameters is saved and read back as the domain binder does, which hands the parameters to a registered type that ignores them"() {
+ void "a type with type parameters is saved and read back as with classic binding, which handed the parameters to a registered type that ignores them"() {
when:
- Map binder = roundTrip(boot([TnStringParams], false), TnStringParams, [myProperty: 'hello'], 'myProperty', 'select my_property from tn_string_params')
- Map generated = roundTrip(boot([TnStringParams], true), TnStringParams, [myProperty: 'hello'], 'myProperty', 'select my_property from tn_string_params')
+ Map generated = roundTrip(boot([TnStringParams]), TnStringParams, [myProperty: 'hello'], 'myProperty', 'select my_property from tn_string_params')
then:
- generated == binder
generated == [stored: [['hello']], reloaded: 'hello']
}
void "the parameters of a user type reach the user type"() {
when:
- Map binder = roundTrip(boot([TnPrefixed], false), TnPrefixed, [label: 'hello'], 'label', 'select label from tn_prefixed')
- Map generated = roundTrip(boot([TnPrefixed], true), TnPrefixed, [label: 'hello'], 'label', 'select label from tn_prefixed')
+ Map generated = roundTrip(boot([TnPrefixed]), TnPrefixed, [label: 'hello'], 'label', 'select label from tn_prefixed')
then:
- generated == binder
generated == [stored: [['p:hello']], reloaded: 'hello']
}
}
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesWriteFlagsSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesWriteFlagsSpec.groovy
index 35472e6cfa..0f948dd984 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesWriteFlagsSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/generated/GeneratedDomainClassesWriteFlagsSpec.groovy
@@ -30,10 +30,10 @@ import org.grails.orm.hibernate.HibernateDatastore
/**
* {@code insertable: false} and {@code updatable: false} on a property that has no column of its own. A collection and the
- * inverse side of a one-to-one are written through their own tables or by the other side, so the domain binder writes them
- * whatever the flags say, and the generated classes ignore the flags there the same way, instead of refusing the mapping. An
- * embedded object is written through the columns of its properties, which the binder keeps out of the insert or the update, and so
- * do the generated classes.
+ * inverse side of a one-to-one are written through their own tables or by the other side, so the classic binding of Grails 8 wrote
+ * them whatever the flags said, and the generated classes ignore the flags there the same way, instead of refusing the mapping. An
+ * embedded object is written through the columns of its properties, which are kept out of the insert or the update, as classic
+ * binding kept them. The schema and the behaviour stated here are the ones classic binding gave.
*/
class GeneratedDomainClassesWriteFlagsSpec extends Specification {
@@ -42,18 +42,17 @@ class GeneratedDomainClassesWriteFlagsSpec extends Specification {
@AutoCleanup
HibernateDatastore datastore
- private HibernateDatastore boot(List<Class> group, boolean generated) {
+ private HibernateDatastore boot(List<Class> group) {
datastore?.close()
datastore = new HibernateDatastore([
- 'dataSource.url' : "jdbc:h2:mem:gdw${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
- 'dataSource.dbCreate' : 'create-drop',
- 'hibernate.generatedDomainClasses': generated,
+ 'dataSource.url' : "jdbc:h2:mem:gdw${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
+ 'dataSource.dbCreate': 'create-drop',
], group as Class[])
return datastore
}
- private Map<String, Map> schema(List<Class> group, boolean generated) {
- HibernateDatastore booted = boot(group, generated)
+ private Map<String, Map> schema(List<Class> group) {
+ HibernateDatastore booted = boot(group)
Map<String, Map> result = new TreeMap<String, Map>()
for (Table table : booted.metadata.collectTableMappings()) {
if (table.physicalTable) {
@@ -70,32 +69,42 @@ class GeneratedDomainClassesWriteFlagsSpec extends Specification {
}
@Unroll
- void "#label: the generated mode creates the schema of the domain binder"() {
+ void "#label: the schema of classic binding is created"() {
expect:
- schema(group, true) == schema(group, false)
+ schema(group) == expected
where:
- label | group
- 'insertable false on a basic collection' | [GdwTagsOwner]
- 'updatable false on a basic collection' | [GdwUpdTagsOwner]
- 'insertable false on a collection of entities' | [GdwItemsOwner, GdwItem]
- 'insertable false on an embedded object' | [GdwEmbeddedOwner]
- 'updatable false on an embedded object' | [GdwUpdEmbeddedOwner]
- 'insertable false on a many-to-many' | [GdwManyA, GdwManyB]
- 'insertable false on the hasOne side' | [GdwHasOneOwner, GdwHasOneDetail]
+ label << ['insertable false on a basic collection', 'updatable false on a basic collection', 'insertable false on a collection of entities',
+ 'insertable false on an embedded object', 'updatable false on an embedded object', 'insertable false on a many-to-many',
+ 'insertable false on the hasOne side']
+ group << [[GdwTagsOwner], [GdwUpdTagsOwner], [GdwItemsOwner, GdwItem], [GdwEmbeddedOwner], [GdwUpdEmbeddedOwner], [GdwManyA, GdwManyB],
+ [GdwHasOneOwner, GdwHasOneDetail]]
+ expected << [
+ [gdw_tags_owner: [columns: [id: 'bigint not null', version: 'bigint not null'], primaryKey: ['id'], foreignKeys: []],
+ gdw_tags_owner_tags: [columns: [gdw_tags_owner_id: 'bigint', tags_java_lang_string: 'varchar(255)'], primaryKey: null, foreignKeys: ['[gdw_tags_owner_id] -> gdw_tags_owner']]],
+ [gdw_upd_tags_owner: [columns: [id: 'bigint not null', version: 'bigint not null'], primaryKey: ['id'], foreignKeys: []],
+ gdw_upd_tags_owner_tags: [columns: [gdw_upd_tags_owner_id: 'bigint', tags_java_lang_string: 'varchar(255)'], primaryKey: null, foreignKeys: ['[gdw_upd_tags_owner_id] -> gdw_upd_tags_owner']]],
+ [gdw_item: [columns: [id: 'bigint not null', version: 'bigint not null', name: 'varchar(255)'], primaryKey: ['id'], foreignKeys: []],
+ gdw_items_owner: [columns: [id: 'bigint not null', version: 'bigint not null'], primaryKey: ['id'], foreignKeys: []],
+ gdw_items_owner_gdw_item: [columns: [gdw_item_id: 'bigint', gdw_items_owner_items_id: 'bigint'], primaryKey: null, foreignKeys: ['[gdw_item_id] -> gdw_item', '[gdw_items_owner_items_id] -> gdw_items_owner']]],
+ [gdw_embedded_owner: [columns: [id: 'bigint not null', version: 'bigint not null', home_street: 'varchar(255)'], primaryKey: ['id'], foreignKeys: []]],
+ [gdw_upd_embedded_owner: [columns: [id: 'bigint not null', version: 'bigint not null', home_street: 'varchar(255)'], primaryKey: ['id'], foreignKeys: []]],
+ [gdw_manya: [columns: [id: 'bigint not null', version: 'bigint not null'], primaryKey: ['id'], foreignKeys: []],
+ gdw_manya_bs: [columns: [gdw_manya_id: 'bigint not null', gdw_manyb_id: 'bigint not null'], primaryKey: ['gdw_manya_id', 'gdw_manyb_id'], foreignKeys: ['[gdw_manya_id] -> gdw_manya', '[gdw_manyb_id] -> gdw_manyb']],
+ gdw_manyb: [columns: [id: 'bigint not null', version: 'bigint not null', name: 'varchar(255)'], primaryKey: ['id'], foreignKeys: []]],
+ [gdw_has_one_detail: [columns: [id: 'bigint not null', owner_id: 'bigint not null', version: 'bigint not null', label: 'varchar(255)'], primaryKey: ['id'], foreignKeys: ['[owner_id] -> gdw_has_one_owner']],
+ gdw_has_one_owner: [columns: [id: 'bigint not null', version: 'bigint not null'], primaryKey: ['id'], foreignKeys: []]],
+ ]
}
@Unroll
- void "#label: the property is written and updated in both modes, whatever the flag says"() {
+ void "#label: the property is written and updated whatever the flag says"() {
when:
- Map<Boolean, List> results = [false, true].collectEntries { boolean generated ->
- boot(group, generated)
- [(generated): this."${cycle}"()]
- }
+ boot(group)
+ List results = this."${cycle}"()
then:
- results[true] == results[false]
- results[true] == expected
+ results == expected
where:
label | group | cycle | expected
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ManyToManyWithoutOwnerSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ManyToManyWithoutOwnerSpec.groovy
index 1301ce7c9c..f109b4556d 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ManyToManyWithoutOwnerSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ManyToManyWithoutOwnerSpec.groovy
@@ -33,22 +33,21 @@ import spock.lang.Unroll
/**
* A bidirectional many-to-many is written by the side that {@code belongsTo} designates as the owner. When neither side
* declares it, both collections are inverse and the relationship is never stored, so the application refuses to start
- * instead of silently losing the data, in both the domain binder and the generated mapping.
+ * instead of silently losing the data.
*/
class ManyToManyWithoutOwnerSpec extends Specification {
@AutoCleanup
HibernateDatastore datastore
- private HibernateDatastore boot(boolean generated, Class... classes) {
+ private HibernateDatastore boot(Class... classes) {
datastore = new HibernateDatastore(DatastoreUtils.createPropertyResolver([
- 'dataSource.url' : "jdbc:h2:mem:m2mNoOwner${generated}${System.nanoTime()};LOCK_TIMEOUT=10000".toString(),
- 'dataSource.dbCreate' : 'create-drop',
- 'dataSource.dialect' : H2Dialect.name,
- 'hibernate.hbm2ddl.auto' : 'create-drop',
- 'hibernate.cache.queries' : 'false',
- 'hibernate.cache.use_query_cache' : 'false',
- 'hibernate.generatedDomainClasses': generated,
+ 'dataSource.url' : "jdbc:h2:mem:m2mNoOwner${System.nanoTime()};LOCK_TIMEOUT=10000".toString(),
+ 'dataSource.dbCreate' : 'create-drop',
+ 'dataSource.dialect' : H2Dialect.name,
+ 'hibernate.hbm2ddl.auto' : 'create-drop',
+ 'hibernate.cache.queries' : 'false',
+ 'hibernate.cache.use_query_cache': 'false',
]), classes)
return datastore
}
@@ -67,39 +66,30 @@ class ManyToManyWithoutOwnerSpec extends Specification {
return null
}
- @Unroll
- def "the application does not start when neither side of a many-to-many declares belongsTo (generated mapping: #generated)"() {
+ def "the application does not start when neither side of a many-to-many declares belongsTo"() {
when:
- MappingException failure = mappingFailure { boot(generated, NoOwnerLeft, NoOwnerRight) }
+ MappingException failure = mappingFailure { boot(NoOwnerLeft, NoOwnerRight) }
then: 'the message names both sides and says where to declare belongsTo'
failure != null
failure.message == 'Neither side of the many-to-many between [grails.unbootable.NoOwnerLeft.rights] and ' +
'[grails.unbootable.NoOwnerRight.lefts] declares belongsTo, so the relationship would never be stored. ' +
'Declare belongsTo on the owned side, for example in NoOwnerRight: static belongsTo = NoOwnerLeft'
-
- where:
- generated << [false, true]
}
- @Unroll
- def "the application does not start when a self-referencing many-to-many has no belongsTo (generated mapping: #generated)"() {
+ def "the application does not start when a self-referencing many-to-many has no belongsTo"() {
when:
- MappingException failure = mappingFailure { boot(generated, NoOwnerSelf) }
+ MappingException failure = mappingFailure { boot(NoOwnerSelf) }
then:
failure != null
failure.message.contains('[grails.unbootable.NoOwnerSelf.followers] and [grails.unbootable.NoOwnerSelf.following]')
failure.message.contains('static belongsTo = NoOwnerSelf')
-
- where:
- generated << [false, true]
}
- @Unroll
- def "a many-to-many with belongsTo on one side starts and stores its rows (generated mapping: #generated)"() {
+ def "a many-to-many with belongsTo on one side starts and stores its rows"() {
when:
- boot(generated, OwnedLeft, OwnerRight)
+ boot(OwnedLeft, OwnerRight)
OwnerRight.withTransaction {
OwnerRight owner = new OwnerRight(name: 'owner')
owner.addToLefts(new OwnedLeft(name: 'left'))
@@ -109,27 +99,19 @@ class ManyToManyWithoutOwnerSpec extends Specification {
then:
OwnerRight.withNewSession { OwnerRight.first().lefts*.name } == ['left']
OwnedLeft.withNewSession { OwnedLeft.first().owners*.name } == ['owner']
-
- where:
- generated << [false, true]
}
- @Unroll
- def "a unidirectional many-to-many starts (generated mapping: #generated)"() {
+ def "a unidirectional many-to-many starts"() {
when:
- boot(generated, UnidirectionalLeft, UnidirectionalRight)
+ boot(UnidirectionalLeft, UnidirectionalRight)
then:
noExceptionThrown()
-
- where:
- generated << [false, true]
}
- @Unroll
- def "a self-referencing many-to-many with belongsTo starts and stores its rows (generated mapping: #generated)"() {
+ def "a self-referencing many-to-many with belongsTo starts and stores its rows"() {
when:
- boot(generated, OwnedSelf)
+ boot(OwnedSelf)
OwnedSelf.withTransaction {
OwnedSelf first = new OwnedSelf(name: 'first')
first.addToFollowers(new OwnedSelf(name: 'second'))
@@ -138,15 +120,12 @@ class ManyToManyWithoutOwnerSpec extends Specification {
then:
OwnedSelf.withNewSession { OwnedSelf.findByName('first').followers*.name } == ['second']
-
- where:
- generated << [false, true]
}
@Unroll
- def "a many-to-many with a Map on #shape starts without belongsTo and stores its rows through the Map side (generated mapping: #generated)"() {
+ def "a many-to-many with a Map on #shape starts without belongsTo and stores its rows through the Map side"() {
when:
- boot(generated, left, right)
+ boot(left, right)
left.withTransaction {
def rightRow = right.newInstance(name: 'right').save(failOnError: true)
left.newInstance(name: 'left', (leftProperty): [first: rightRow]).save(flush: true, failOnError: true)
@@ -157,16 +136,14 @@ class ManyToManyWithoutOwnerSpec extends Specification {
!readsBack || right.withNewSession { right.findByName('right')."$rightProperty"*.name } == ['left']
where:
- shape | left | right | leftProperty | rightProperty | readsBack | generated
- 'one side' | MapSetLeft | MapSetRight | 'rights' | 'lefts' | true | false
- 'both sides' | MapMapLeft | MapMapRight | 'rights' | 'lefts' | false | false
- 'one side' | MapSetLeft | MapSetRight | 'rights' | 'lefts' | true | true
- 'both sides' | MapMapLeft | MapMapRight | 'rights' | 'lefts' | false | true
+ shape | left | right | leftProperty | rightProperty | readsBack
+ 'one side' | MapSetLeft | MapSetRight | 'rights' | 'lefts' | true
+ 'both sides' | MapMapLeft | MapMapRight | 'rights' | 'lefts' | false
}
def "a Set on both sides without belongsTo still does not start"() {
when:
- MappingException failure = mappingFailure { boot(false, NoOwnerLeft, NoOwnerRight) }
+ MappingException failure = mappingFailure { boot(NoOwnerLeft, NoOwnerRight) }
then:
failure != null
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateBasicPropertySpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateBasicPropertySpec.groovy
index 73c2d852a7..c6501a2005 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateBasicPropertySpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernateBasicPropertySpec.groovy
@@ -72,24 +72,29 @@ class HibernateBasicPropertySpec extends HibernateGormDatastoreSpec {
mockCollection.getBatchSize() == property.getBatchSize()
}
- def "getTable on an enum collection element switches from owner table to collection table"() {
+ def "getTable on an enum collection element switches from the owner's table to the collection's once a collection is set"() {
given:
def entity = (HibernatePersistentEntity) getMappingContext().getPersistentEntity(HBPStatusPerson.name)
def property = (HibernateBasicEnumProperty) entity.getPropertyByName("statuses")
- def original = property.getHibernateCollection()
+ def mbc = getGrailsDomainBinder().metadataBuildingContext
+ def rootClass = new org.hibernate.mapping.RootClass(mbc)
+ rootClass.setEntityName(HBPStatusPerson.name)
+ def collection = new org.hibernate.mapping.Set(mbc, rootClass)
+ collection.setCollectionTable(new org.hibernate.mapping.Table('orm', 'hbp_status_person_statuses'))
- expect: "after binding, the property's table is the collection's join table, not the owner's"
- property.getTable() == original.getCollectionTable()
- property.getTable() != property.getPersistentClass().getTable()
+ expect: "with no collection, the property's table is the owning entity's"
+ property.getHibernateCollection() == null
+ property.getTable() == property.getPersistentClass().getTable()
- when: "the collection has not been assigned yet"
- property.setHibernateCollection(null)
+ when:
+ property.setHibernateCollection(collection)
- then: "getTable falls back to the owning entity's table"
- property.getTable() == property.getPersistentClass().getTable()
+ then: "the property's table is the collection's table, not the owner's"
+ property.getTable() == collection.getCollectionTable()
+ property.getTable() != property.getPersistentClass().getTable()
cleanup:
- property.setHibernateCollection(original)
+ property.setHibernateCollection(null)
}
def "getTable on a non-enum basic collection element stays the owning entity's table"() {
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainBinderOptionDefectSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ColumnOptionSpec.groovy
similarity index 75%
rename from grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainBinderOptionDefectSpec.groovy
rename to grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ColumnOptionSpec.groovy
index 73f55d1855..4988cc3b9d 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainBinderOptionDefectSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ColumnOptionSpec.groovy
@@ -20,17 +20,14 @@ package org.grails.orm.hibernate.cfg.domainbinding.jpa
import grails.gorm.annotation.Entity
import grails.gorm.tests.HibernateGormDatastoreSpec
-import org.hibernate.mapping.Collection as HibernateCollection
import org.hibernate.mapping.Column
-import org.hibernate.mapping.Table
-import spock.lang.PendingFeature
/**
- * Pins defects of the domain binder found while auditing which mapping options {@link GrailsDomainGenerator} drops. The
- * binder silently ignores the options below; the generator either states what the mapping asks for (and the differential spec
- * lists the difference) or rejects the mapping by name. Each feature reports as fixed when the binder is.
+ * Column options of a simple property and of an enum property that reach the bound column and the rows: the write flags
+ * ({@code insertable}, {@code updatable}) and the comment, default and read and write expressions of an enum column, which
+ * {@link GrailsDomainGenerator} states as the mapping asks for.
*/
-class GrailsDomainBinderOptionDefectSpec extends HibernateGormDatastoreSpec {
+class ColumnOptionSpec extends HibernateGormDatastoreSpec {
void setupSpec() {
manager.registerDomainClasses(DefectWritable, DefectReadOnlyColumns, DefectEnumGroup, DefectCollectionGroup, DefectEnumColumn)
@@ -72,8 +69,7 @@ class GrailsDomainBinderOptionDefectSpec extends HibernateGormDatastoreSpec {
DefectReadOnlyColumns.get(row.id).updated == 'b'
}
- @PendingFeature(reason = 'EnumTypeBinder never calls CreateKeyForProps, so a unique group on an enum property makes no unique key')
- void "a unique group on an enum property is unique in the database"() {
+ void "a unique group on an enum property is unique in the database (classic binding never created the key)"() {
given:
new DefectEnumGroup(state: DefectState.ON, other: 'a').save(flush: true, failOnError: true)
session.clear()
@@ -96,14 +92,17 @@ class GrailsDomainBinderOptionDefectSpec extends HibernateGormDatastoreSpec {
column.customWrite == 'upper(?)'
}
- @PendingFeature(reason = 'CollectionKeyBinder runs ColumnBinder on the collection property, so a unique group becomes a unique key of the collection table that names a column of the owner\'s table')
- void "the unique key of a collection table names only columns of that table"() {
+ void "a unique group on a collection property creates no key, since the collection table does not hold the columns of the group"() {
given:
- Table table = ((HibernateCollection) getPersistentEntity(DefectCollectionGroup).persistentClass.getProperty('tags').value).collectionTable
- Set<String> columns = table.columns*.name.toSet()
+ new DefectCollectionGroup(x: 'a', tags: ['one', 'two'] as Set).save(flush: true, failOnError: true)
+ session.clear()
- expect:
- table.uniqueKeys.values().every { it.columns*.name.every { String name -> columns.contains(name) } }
+ when: 'another owner repeats the value the group names'
+ new DefectCollectionGroup(x: 'a', tags: ['one'] as Set).save(flush: true, failOnError: true)
+ session.clear()
+
+ then:
+ DefectCollectionGroup.count() == 2
}
}
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 1f50ec12e2..5bb9d68b8b 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
@@ -74,7 +74,7 @@ class GeneratedDomainClassesDdlDifferentialSpec extends Specification {
[id: 'MAP_ELEMENT_NULLABLE', reason: 'The mapping of a map of values states nullable: false on the element column and the binder leaves the column nullable (it ignores the option, like the enum column extras); the generated mode honours the mapping, so a database created by the binder has a nullable column where the generated mode creates NOT NULL. Matching the binder would drop a constraint the mapping states.'],
[id: 'MAP_UNUSED_COLUMN', reason: 'The binder leaves an unused nullable column in the table of a map of values (the element it bound before the map replaced it, attributes_java_lang_string); the generated mode creates no such column. Nothing reads the extra column; an existing database keeps it (update does not drop columns).'],
[id: 'UNIQUE_GROUP_ON_COLLECTION', reason: 'A binder defect (fixed on the 8.0.x line by PR 16533, so the class disappears with the next up-merge): a unique group mapped on a collection property makes the binder create a unique key on the collection table over the key column and the other properties of the group, which are columns of the owner\'s table and not of the collection table, so the key cannot be created (Hibernate logs the failed statement and boots; the key is not i [...]
- [id: 'UNIQUE_GROUP_ON_ENUM', reason: 'A binder defect (pinned in GrailsDomainBinderOptionDefectSpec): a unique group that includes an enum property is dropped by the binder. The generated mode creates the constraint the mapping states, so a database created by the binder lacks it and `update` would add it. 2 groups in the scanned domains.']
+ [id: 'UNIQUE_GROUP_ON_ENUM', reason: 'A classic binder defect (the native constraint is proven by ColumnOptionSpec): a unique group that includes an enum property is dropped by the binder. The generated mode creates the constraint the mapping states, so a database created by the binder lacks it and `update` would add it. 2 groups in the scanned domains.']
]
private static final AtomicInteger BOOTS = new AtomicInteger()
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainBinderCompositeIdDefectSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainBinderCompositeIdDefectSpec.groovy
deleted file mode 100644
index d391992d3f..0000000000
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainBinderCompositeIdDefectSpec.groovy
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.jpa
-
-import grails.gorm.tests.HibernateGormDatastoreSpec
-import grails.unbootable.UnbootableComposite
-import grails.unbootable.UnbootableJoinToComposite
-import grails.unbootable.UnbootableJoinedChild
-import grails.unbootable.UnbootableJoinedParent
-import grails.unbootable.UnbootableParts
-import grails.unbootable.UnbootableRefToParts
-import grails.unbootable.UnbootableRefToTop
-import grails.unbootable.UnbootableTarget
-import grails.unbootable.UnbootableTop
-import grails.unbootable.UnbootableMiddle
-import grails.unbootable.UnbootableFlat
-import org.grails.orm.hibernate.HibernateDatastore
-import spock.lang.PendingFeature
-
-/**
- * Pins a defect of the domain binder found while describing composite identifiers: a unidirectional collection of entities that
- * have a composite identifier is bound through a join table, and the binder gives the element its columns from the column configs
- * of the collection property (one for each identifier property of the target) and then reads the same configs again for the key,
- * which should point at the owner. The key gets the element's columns and Hibernate refuses the foreign key ("must have same number
- * of columns as the referenced primary key"), so the mapping cannot boot. The generator rejects such a collection by name. This
- * feature reports as fixed when the binder is.
- */
-class GrailsDomainBinderCompositeIdDefectSpec extends HibernateGormDatastoreSpec {
-
- /** The defects are the classic binder's, so the datastores select it whatever the default is. */
- private static final Map<String, Object> CLASSIC = ['hibernate.generatedDomainClasses': false]
-
- @PendingFeature(reason = 'the key of a join table to a composite identifier gets the columns of the element, so Hibernate refuses the foreign key')
- void "a unidirectional collection of entities with a composite identifier can be bound"() {
- when:
- HibernateDatastore datastore = new HibernateDatastore(CLASSIC, UnbootableJoinToComposite, UnbootableComposite)
-
- then:
- notThrown(Exception)
-
- cleanup:
- datastore?.close()
- }
-
- @PendingFeature(reason = 'ForeignKeyColumnCountCalculator counts a composite identifier part that refers to an entity with a simple identifier as no column, so the foreign key has fewer columns than the key and Hibernate refuses it')
- void "a foreign key to a composite identifier with a part that refers to an entity can be bound"() {
- when:
- HibernateDatastore datastore = new HibernateDatastore(CLASSIC, UnbootableRefToParts, UnbootableParts, UnbootableTarget)
-
- then:
- notThrown(Exception)
-
- cleanup:
- datastore?.close()
- }
-
- @PendingFeature(reason = 'CompositeIdentifierToManyToOneBinder expands a nested composite identifier one level only, so a foreign key to a composite identifier three levels deep has fewer columns than the key')
- void "a foreign key to a composite identifier three levels deep can be bound"() {
- when:
- HibernateDatastore datastore = new HibernateDatastore(CLASSIC, UnbootableRefToTop, UnbootableTop, UnbootableMiddle, UnbootableFlat)
-
- then:
- notThrown(Exception)
-
- cleanup:
- datastore?.close()
- }
-
- @PendingFeature(reason = 'the key of a joined subclass is bound with one column, so a joined subclass of an entity with a composite identifier cannot be bound')
- void "a joined subclass of an entity with a composite identifier can be bound"() {
- when:
- HibernateDatastore datastore = new HibernateDatastore(CLASSIC, UnbootableJoinedParent, UnbootableJoinedChild)
-
- then:
- notThrown(Exception)
-
- cleanup:
- datastore?.close()
- }
-}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainBinderEmbeddedCollectionDefectSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainBinderEmbeddedCollectionDefectSpec.groovy
deleted file mode 100644
index b8be64ee3d..0000000000
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainBinderEmbeddedCollectionDefectSpec.groovy
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * 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 org.grails.orm.hibernate.cfg.domainbinding.jpa
-
-import grails.gorm.tests.HibernateGormDatastoreSpec
-import grails.unbootable.EmbeddedCollectionOwnerA
-import grails.unbootable.EmbeddedCollectionOwnerB
-import org.grails.orm.hibernate.HibernateDatastore
-import spock.lang.PendingFeature
-
-/**
- * Pins a defect of the domain binder found while auditing what {@link GrailsDomainGenerator} rejects: a collection inside an
- * embedded type is registered under a role built from the embedded type and the embedded property ({@code
- * EmbeddedCollectionHolder.inner.words}), and given a table and a key column named after the type, not the owner, so two
- * owners that embed the same type collide and Hibernate refuses the duplicate collection definition at boot. The generator
- * rejects such a type by name instead of copying that. This feature reports as fixed when the binder is.
- */
-class GrailsDomainBinderEmbeddedCollectionDefectSpec extends HibernateGormDatastoreSpec {
-
- /** The defects are the classic binder's, so the datastores select it whatever the default is. */
- private static final Map<String, Object> CLASSIC = ['hibernate.generatedDomainClasses': false]
-
- @PendingFeature(reason = 'the role, the table and the key column of a collection inside an embedded type come from the type, so two owners of the type collide')
- void "two entities can embed a type that has a collection"() {
- when:
- HibernateDatastore datastore = new HibernateDatastore(CLASSIC, EmbeddedCollectionOwnerA, EmbeddedCollectionOwnerB)
-
- then:
- notThrown(Exception)
-
- cleanup:
- datastore?.close()
- }
-}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorCompositeIdSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorCompositeIdSpec.groovy
index 9b402987ea..bbe9d3f039 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorCompositeIdSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorCompositeIdSpec.groovy
@@ -221,7 +221,7 @@ class GrailsDomainGeneratorCompositeIdSpec extends GrailsDomainGeneratorSupport
when:
newGenerator().generateAll(unbound(domain, composite), getClass().classLoader)
- then: "the binder cannot boot a join table to a composite identifier either (see GrailsDomainBinderCompositeIdDefectSpec)"
+ then: "classic binding could not boot a join table to a composite identifier either (the key got the columns of the element)"
UnsupportedOperationException e = thrown()
e.message.contains(domain.simpleName)
e.message.contains(property)
@@ -332,7 +332,7 @@ class GrailsDomainGeneratorCompositeIdSpec extends GrailsDomainGeneratorSupport
when:
newGenerator().generateAll(unbound(UnbootableJoinedParent, UnbootableJoinedChild), getClass().classLoader)
- then: "the binder binds the key of a joined subclass with one column (see GrailsDomainBinderCompositeIdDefectSpec)"
+ then: "classic binding bound the key of a joined subclass with one column, so it could not boot this either"
UnsupportedOperationException e = thrown()
e.message.contains('UnbootableJoinedParent')
e.message.contains('joined subclass')
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 dabc6f22b1..06a89e85f0 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
@@ -519,8 +519,8 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec {
/**
* The column facets the generator decided against the bound column and property. A mapping that says {@code insertable: false}
* or {@code updatable: false} is a known divergence, not a mismatch: {@code PropertyBinder} overwrites those flags with the
- * ones of the columns, which are always set, so the binder ignores the option (pinned in
- * {@link GrailsDomainBinderOptionDefectSpec}) and the generator states what the mapping asks for.
+ * ones of the columns, which are always set, so the classic binder ignored the option and the generator states what the
+ * mapping asks for ({@code ColumnOptionSpec} proves the flags reach the rows).
*/
private List<String> compare(
String where, ColumnFacets facets, Map bound, Map<String, Integer> known, Collection<String> ignore = [],
@@ -549,7 +549,7 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec {
ignore.each { pairs.remove(it) }
if (enumeration) {
// EnumTypeBinder ignores the comment, default and read and write expressions of the column config (a binder defect,
- // pinned in GrailsDomainBinderOptionDefectSpec); the generator states them
+ // of Grails 8); the generator states them
['default', 'read', 'write', 'comment'].each { String facet ->
if (pairs[facet][0] != null && pairs[facet][1] == null) {
known["the binder ignores the comment, default and read and write expressions of an enum column; the generator states them".toString()]++
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 08968c05fc..1ccd65e41c 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
@@ -273,14 +273,13 @@ class GrailsDomainGeneratorSpec extends HibernateGormDatastoreSpec {
entityClass << [GenCar, GenVehicle]
}
- void "type parameters mapped with no type are not stated, because the built-in type the binder hands them to ignores them"() {
+ void "type parameters mapped with no type are not stated, because the built-in type they would go to ignores them"() {
when:
Class<?> generated = generate(GenParamsOnly)
then:
generated.getDeclaredField('quantity').getAnnotations().every { !(it instanceof Type) && !(it instanceof JdbcTypeCode) }
generated.getDeclaredField('quantity').getAnnotation(Column).name() == 'quantity'
- getPersistentEntity(GenParamsOnly).persistentClass.getProperty('quantity').value.typeParameters.getProperty('sequence_name') == 'seq'
}
void "the version is marked as the optimistic lock"() {
@@ -422,7 +421,7 @@ class GrailsDomainGeneratorSpec extends HibernateGormDatastoreSpec {
classes[entity(GenCustomCollectionOwner)].getDeclaredField('kids').getAnnotation(CollectionType).type() == GenSetCollectionType
}
- void "Hibernate's own annotation binder resolves a converted type like the domain binder"() {
+ void "Hibernate's own annotation binder resolves a converted type as the bound model holds it"() {
given:
Map<GrailsHibernatePersistentEntity, Class<?>> classes = generateGroup(GenConverted)
PersistentClass bound = entity(GenConverted).persistentClass
@@ -436,7 +435,7 @@ class GrailsDomainGeneratorSpec extends HibernateGormDatastoreSpec {
expected.jdbcType.defaultSqlTypeCode == actual.jdbcType.defaultSqlTypeCode &&
expected.domainJavaType.javaTypeClass == actual.domainJavaType.javaTypeClass
}
- ((BasicValue) bound.getProperty('yesNo').value).resolve().valueConverter instanceof YesNoConverter
+ converterClass(((BasicValue) bound.getProperty('yesNo').value).resolve()) == YesNoConverter
}
private static Class<?> converterClass(BasicValue.Resolution<?> resolution) {
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorUniqueGroupSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorUniqueGroupSpec.groovy
index bd5c144561..ab5527c33b 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorUniqueGroupSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorUniqueGroupSpec.groovy
@@ -31,8 +31,8 @@ import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateBasicProper
/**
* Describes how {@link GrailsDomainGenerator} states the unique constraints a mapping asks for with {@code unique: 'group'}
* or {@code unique: ['a', 'b']} on a column: one multi-column unique key per property that names a group, with the
- * binder's column order (the property's own column last) and the binder's name ({@code UK} and a hash of the table and
- * the columns). The differential spec compares them on every domain class.
+ * column order of Grails 8's classic binding (the property's own column last) and its name ({@code UK} and a hash of the
+ * table and the columns). The differential spec compares them with the recorded classic keys on every domain class.
*/
class GrailsDomainGeneratorUniqueGroupSpec extends GrailsDomainGeneratorSupport {
@@ -92,15 +92,15 @@ class GrailsDomainGeneratorUniqueGroupSpec extends GrailsDomainGeneratorSupport
readConstraints(metadata.getEntityBinding(classes[entity(GenUqJoinedChild)].name)) == boundConstraints(GenUqJoinedChild)
}
- void "a unique group on an enum property is stated, although the binder never creates the key"() {
+ void "a unique group on an enum property is stated, although classic binding never created the key"() {
when:
Map<GrailsHibernatePersistentEntity, Class<?>> classes = generateGroup(GenUqEnum)
ConstraintFacets facets = newGenerator().constraintFacets(entity(GenUqEnum))
- then: "EnumTypeBinder never calls CreateKeyForProps, which the mapping does not mean: the generator states the key and says the binder does not"
+ then: "classic binding never created the key of an enum property, which the mapping does not mean: the generator states the key and says so"
generatedConstraints(classes[entity(GenUqEnum)]).values().toList() == [['other', 'state']]
facets.uniqueKeys()*.bound() == [false]
- entity(GenUqEnum).persistentClass.table.uniqueKeys.values().every { it.columns.size() < 2 }
+ entity(GenUqEnum).persistentClass.table.uniqueKeys.values().any { it.columns*.name == ['other', 'state'] }
}
void "a unique group over the columns of a composite identifier states the order of its primary key, as the binder gives it"() {
@@ -118,15 +118,12 @@ class GrailsDomainGeneratorUniqueGroupSpec extends GrailsDomainGeneratorSupport
newGenerator().constraintFacets(entity(GenUqTarget)).primaryKeyOrder() == null
}
- void "a unique group on a collection property states no key, since the key the binder makes names columns the collection table does not have"() {
+ void "a unique group on a collection property states no key, since the key classic binding made named columns the collection table does not have"() {
when:
Map<GrailsHibernatePersistentEntity, Class<?>> classes = generateGroup(GenUqCollection)
CollectionTable table = classes[entity(GenUqCollection)].getDeclaredField('tags').getAnnotation(CollectionTable)
- then: "the binder's key names a column of the owner's table, so it cannot be created; the generated collection has none"
- entity(GenUqCollection).persistentClass.getProperty('tags').value.collectionTable.uniqueKeys.values().any {
- it.columns*.name.contains('x')
- }
+ then: "the key classic binding made named a column of the owner's table, so it could not be created; the generated collection has none"
table.uniqueConstraints().length == 0
newGenerator().collectionFacets((HibernateBasicProperty) entity(GenUqCollection).getPropertyByName('tags')).indexes().isEmpty()
newGenerator().constraintFacets(entity(GenUqCollection)).uniqueKeys().isEmpty()
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ManyToManyOwnershipDefectSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ManyToManyOwnershipSpec.groovy
similarity index 80%
rename from grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ManyToManyOwnershipDefectSpec.groovy
rename to grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ManyToManyOwnershipSpec.groovy
index 779b749d76..debc13ec39 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ManyToManyOwnershipDefectSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ManyToManyOwnershipSpec.groovy
@@ -22,12 +22,11 @@ import grails.gorm.annotation.Entity
import grails.gorm.tests.HibernateGormDatastoreSpec
/**
- * Pins a defect of the domain binder in the many-to-many ownership rules, found by comparing it with the annotations
- * {@link GrailsDomainGenerator} generates. The generator does not copy it: it follows the owning side. The feature reports
- * as fixed when the binder is. A many-to-many that neither side owns, the other defect found that way, no longer boots: see
- * {@code ManyToManyWithoutOwnerSpec}.
+ * The ownership rules of a many-to-many: the annotations {@link GrailsDomainGenerator} generates follow the owning side, so the
+ * inverse side reads the join table the owner writes, also when only the owner names the table (the classic binding of Grails 8
+ * lost the rows then). A many-to-many that neither side owns does not boot: see {@code ManyToManyWithoutOwnerSpec}.
*/
-class ManyToManyOwnershipDefectSpec extends HibernateGormDatastoreSpec {
+class ManyToManyOwnershipSpec extends HibernateGormDatastoreSpec {
void setupSpec() {
manager.registerDomainClasses(DefectNamedOwner, DefectNamedInverse)
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/BasicCollectionKeyDefectSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/UnidirectionalBasicCollectionsSpec.groovy
similarity index 81%
rename from grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/BasicCollectionKeyDefectSpec.groovy
rename to grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/UnidirectionalBasicCollectionsSpec.groovy
index 8678dad15e..9ef479cc4d 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/BasicCollectionKeyDefectSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/UnidirectionalBasicCollectionsSpec.groovy
@@ -22,12 +22,11 @@ import grails.gorm.annotation.Entity
import grails.gorm.tests.HibernateGormDatastoreSpec
/**
- * Regression test for a defect of the domain binder: {@code CollectionKeyColumnUpdater} made the key of a collection
- * not updatable when its owner had more than one unidirectional to-many property. Hibernate's collection persister then
- * disables inserting and deleting the rows of the collection, so the elements of a collection of basic values were never
- * written. The key of a collection of basic values must stay updatable.
+ * The elements of a collection of basic values are written whether or not the owner has another unidirectional to-many
+ * property: the key of the collection stays updatable (a defect of Grails 8's classic binding once made it not updatable when
+ * the owner had more than one such property, so Hibernate's collection persister never wrote the rows).
*/
-class BasicCollectionKeyDefectSpec extends HibernateGormDatastoreSpec {
+class UnidirectionalBasicCollectionsSpec extends HibernateGormDatastoreSpec {
void setupSpec() {
manager.registerDomainClasses(DefectOneCollection, DefectTwoCollections)
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/EntityCollectionKeyDefectSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/UnidirectionalEntityCollectionsSpec.groovy
similarity index 74%
rename from grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/EntityCollectionKeyDefectSpec.groovy
rename to grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/UnidirectionalEntityCollectionsSpec.groovy
index fbdd455564..e4a7b68823 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/EntityCollectionKeyDefectSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/UnidirectionalEntityCollectionsSpec.groovy
@@ -20,16 +20,14 @@ package org.grails.orm.hibernate.cfg.domainbinding.jpa
import grails.gorm.annotation.Entity
import grails.gorm.tests.HibernateGormDatastoreSpec
-import spock.lang.PendingFeature
/**
- * Pins a defect of the domain binder that {@link BasicCollectionKeyDefectSpec} fixed for collections of basic values:
- * {@code CollectionKeyColumnUpdater} makes the key of a collection of entities not updatable when its owner has more than
- * one unidirectional to-many property. Hibernate's collection persister then disables inserting and deleting the rows of the
- * join table, so the elements of such a collection are never written. The generator does not copy this: a join column must
- * be updatable, and it states it so. This feature reports as fixed when the binder is.
+ * The elements of a unidirectional collection of entities are written whether or not the owner has another unidirectional
+ * to-many property. The classic binding of Grails 8 made the key of such a collection not updatable when the owner had more than
+ * one, so Hibernate's collection persister never wrote the rows of the join table (see {@link UnidirectionalBasicCollectionsSpec}
+ * for collections of basic values); the generated classes state the join column updatable.
*/
-class EntityCollectionKeyDefectSpec extends HibernateGormDatastoreSpec {
+class UnidirectionalEntityCollectionsSpec extends HibernateGormDatastoreSpec {
void setupSpec() {
manager.registerDomainClasses(DefectItem, DefectOtherItem, DefectItemOneOwner, DefectItemTwoOwner)
@@ -47,7 +45,6 @@ class EntityCollectionKeyDefectSpec extends HibernateGormDatastoreSpec {
DefectItemOneOwner.get(owner.id).items*.name.toSet() == ['a', 'b'].toSet()
}
- @PendingFeature(reason = 'the key of an entity collection is not updatable when its owner has two unidirectional collections, so the join table rows are never written')
void "the items of each of two unidirectional collections of an owner are persisted"() {
given:
DefectItemTwoOwner owner = new DefectItemTwoOwner(name: 'two')
(grails-core) 04/06: test(hibernate7): the classic oracle is frozen, and a new fixture is recorded from a native boot
Posted by bo...@apache.org.
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 b53eacbe30aa57ac1b06102068358ee64cde6323
Author: Walter Duque de Estrada <wb...@mac.com>
AuthorDate: Fri Oct 9 18:24:31 2026 -0500
test(hibernate7): the classic oracle is frozen, and a new fixture is recorded from a native boot
The classic binder is gone, so the VERIFY and REFREEZE modes of ClassicOracle, which booted
it, go too. The recorded files stay the oracle of the two differential specs (FROZEN, the
default: 799 groups, 0 mismatches, 85 known differences, 0 unknown, 0 refused, as before).
A contributor who adds an @Entity fixture records it with -Pgrails.test.recordClassicOracle=true:
RECORD boots only the scanned groups that have no record, natively, writes their facts at
their place in the scan order with the header marked source: native, drops the records of
groups no fixture makes up any more, and writes every other record back byte for byte, so
the diff to review is additions. The DDL differential compares such a group with its own
recorded schema, so a later change of native binding shows up as an unknown difference; the
generator differential reports it instead of comparing facets only a classic boot could give
(Hibernate's binder fills in a discriminator value, a cache strategy and a length on the
version that the classic binder never stated). ClassicOracleSpec proves the three RECORD
behaviours on a copy of the file and skips its completeness checks during a recording run,
whose classpath still holds the old file. Exercised end to end with a throwaway fixture:
10 lines added, none removed, and the FROZEN rerun green with the record in place.
Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
---
gradle/hibernate7-test-config.gradle | 14 +-
grails-data-hibernate7/README.md | 35 +++--
.../cfg/domainbinding/jpa/ClassicOracle.groovy | 148 ++++++++++-----------
.../cfg/domainbinding/jpa/ClassicOracleSpec.groovy | 121 ++++++++++++-----
...eneratedDomainClassesDdlDifferentialSpec.groovy | 51 +++----
.../GrailsDomainGeneratorDifferentialSpec.groovy | 86 ++++++------
6 files changed, 251 insertions(+), 204 deletions(-)
diff --git a/gradle/hibernate7-test-config.gradle b/gradle/hibernate7-test-config.gradle
index c5b100edf8..c2d093d9da 100644
--- a/gradle/hibernate7-test-config.gradle
+++ b/gradle/hibernate7-test-config.gradle
@@ -46,14 +46,12 @@ tasks.withType(Test).configureEach {
useJUnitPlatform()
- // The differential specs compare native domain binding against what the classic binder produced, recorded under
- // src/test/resources/classic-oracle/. By default they read the recorded files and do not boot the classic binder.
- // -Pgrails.test.verifyClassicOracle=true boots it too and asserts it still produces exactly the recorded data;
- // -Pgrails.test.refreezeClassicOracle=true boots it and rewrites the files (see ClassicOracle for the details).
- ['verifyClassicOracle', 'refreezeClassicOracle'].each { String oracleSwitch ->
- if (providers.gradleProperty("grails.test.${oracleSwitch}").map { it.toBoolean() }.getOrElse(false)) {
- systemProperty("grails.test.${oracleSwitch}", 'true')
- }
+ // The differential specs compare native domain binding against what the classic binder of Grails 8 produced, recorded
+ // under src/test/resources/classic-oracle/ before it was deleted. By default they read the recorded files; a scanned
+ // fixture with no record fails them. -Pgrails.test.recordClassicOracle=true boots such a fixture natively and writes its
+ // record, leaving the other records as they are (see ClassicOracle for the details).
+ if (providers.gradleProperty('grails.test.recordClassicOracle').map { it.toBoolean() }.getOrElse(false)) {
+ systemProperty('grails.test.recordClassicOracle', 'true')
}
// Lets TCK specs gate features on the running suite. Spock evaluates @IgnoreIf/@Requires
// preconditions before setupSpec() runs, so this must be set at the task level - a
diff --git a/grails-data-hibernate7/README.md b/grails-data-hibernate7/README.md
index dcfea0c232..38565d4999 100644
--- a/grails-data-hibernate7/README.md
+++ b/grails-data-hibernate7/README.md
@@ -55,34 +55,33 @@ Registered via `META-INF/services/org.grails.cli.compiler.CompilerAutoConfigurat
## Differential specs and the frozen classic oracle (contributors)
-Native domain binding (`hibernate.generatedDomainClasses`, `GrailsDomainGenerator`) is checked against what the classic domain binder
-(`GrailsDomainBinder`) produces for every `@Entity` in the TCK and in the Hibernate 7 tests, by two specs in
+Native domain binding (`GrailsDomainGenerator`, `GeneratedDomainClassBinder`) is the only binding since 9.0.x. It is checked against what
+the classic domain binder of Grails 8 produced for every `@Entity` in the TCK and in the Hibernate 7 tests, by two specs in
`core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa`:
* `GrailsDomainGeneratorDifferentialSpec` compares the facets the generator decides, and what Hibernate's annotation binder reads back from
the generated classes, with the facts the classic binder bound (per entity and property); it writes `build/differential-report.txt`.
-* `GeneratedDomainClassesDdlDifferentialSpec` boots every group of associated domain classes in the generated mode on H2 and compares the
- schema (tables, columns, keys, indexes, checks, sequences, and H2's `SCRIPT NODATA`) with the schema the classic binder derived; it
- writes `build/ddl-report.txt`.
+* `GeneratedDomainClassesDdlDifferentialSpec` boots every group of associated domain classes on H2 and compares the schema (tables, columns,
+ keys, indexes, checks, sequences, and H2's `SCRIPT NODATA`) with the schema the classic binder derived; it writes `build/ddl-report.txt`.
-The classic side of both comparisons is **recorded data**, not a live classic binder: `core/src/test/resources/classic-oracle/`
-(`generator-differential.txt`, `ddl-differential.txt`). `ClassicOracle` documents the format (one record per line, sorted keys, nothing that
-varies from run to run) and has three modes:
+The classic side of both comparisons is **recorded data**: `core/src/test/resources/classic-oracle/` (`generator-differential.txt`,
+`ddl-differential.txt`), written from the classic binder before it was deleted. `ClassicOracle` documents the format (one record per line,
+sorted keys, nothing that varies from run to run) and has two modes:
| Mode | How | What happens |
|---|---|---|
-| FROZEN (default) | `./gradlew :grails-data-hibernate7-core:test --tests '*DifferentialSpec'` | The classic binder is not booted. The recorded files are the oracle. A scanned fixture with no recorded group fails with a message that says to refreeze. |
-| VERIFY | add `-Pgrails.test.verifyClassicOracle=true` | The classic binder is booted too and what it produces must equal the recorded files exactly (the freeze is faithful and current); the comparison then runs as in FROZEN. |
-| REFREEZE | add `-Pgrails.test.refreezeClassicOracle=true` | The classic binder is booted and the files are rewritten. Review and commit the diff: a changed record is a change in what the classic binder does, or a new or changed fixture. |
-
-Run VERIFY after changing a fixture, classic binder code or Hibernate, and REFREEZE only to record that change. The `KNOWN`
+| FROZEN (default) | `./gradlew :grails-data-hibernate7-core:test --tests '*DifferentialSpec'` | The recorded files are the oracle. A scanned fixture with no recorded group, or whose group changed, fails with a message that says to record it; a recorded group no fixture makes up any more is reported. |
+| RECORD | add `-Pgrails.test.recordClassicOracle=true` | A scanned group that has no record is booted natively and its facts are written to the files, at its place in the scan order; the records of groups no fixture makes up any more are dropped; every other record is written back as it is. Review and commit the diff. |
+
+Every `@Entity` under `core/src/test` is scanned, so **a new domain class in a spec needs a record**: run the two differential specs once
+in RECORD mode and check that the diff of the two files is additions only (plus the lines of a fixture you deleted). The new records state
+what native binding does, since no classic binder is left to ask (the section is marked `source: native`: the DDL differential compares its
+schema, so a later change of native binding shows up as an unknown difference; the generator differential reports it instead of comparing
+facets only a classic boot could give). Prefer an existing fixture when a spec can use one. The `KNOWN`
list of the DDL spec states why each remaining difference between native and classic binding is kept; it is not part of the recording.
`ClassicOracleSpec` and the "changed recorded fact" features of the two differential specs prove that the serialisation is stable, that
-the files cover every scanned fixture, and that changing a recorded fact makes the comparison fail.
-
-The classic binder is internal code that is being retired. When it is deleted, the VERIFY and REFREEZE modes go with it, the recorded files
-become plain expectations, and a new fixture gets its records written by hand (copy the records of a similar fixture into the group of the
-new one, in the format `ClassicOracle` reads).
+the files cover every scanned fixture, that changing a recorded fact makes the comparison fail, and that RECORD touches only the records of
+new and gone groups.
## Using GORM Without Grails
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ClassicOracle.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ClassicOracle.groovy
index aea8ea2a97..a0e77b22f9 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ClassicOracle.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ClassicOracle.groovy
@@ -22,35 +22,40 @@ import groovy.json.JsonOutput
import groovy.json.JsonSlurper
/**
- * The frozen oracle of the differential specs: what the classic domain binder produced for the scanned test domains, recorded once
- * as text under {@code src/test/resources/classic-oracle/} so that the specs compare the native binding against recorded data
- * instead of against a live classic binder.
+ * The frozen oracle of the differential specs: what the classic domain binder of Grails 8 produced for the scanned test domains,
+ * recorded once, before it was deleted, as text under {@code src/test/resources/classic-oracle/}. The specs compare native binding
+ * against these recorded facts.
*
- * <p>There are three modes, chosen with Gradle properties (wired to system properties in {@code gradle/hibernate7-test-config.gradle}):</p>
+ * <p>There are two modes, chosen with a Gradle property (wired to a system property in {@code gradle/hibernate7-test-config.gradle}):</p>
* <ul>
- * <li><b>FROZEN</b> (the default): the classic binder is not booted; the recorded files are the oracle.</li>
- * <li><b>VERIFY</b> ({@code -Pgrails.test.verifyClassicOracle=true}): the classic binder is booted live, what it produces is
- * serialised the way the files are and must EQUAL the recorded files (the freeze is faithful and current); the comparison then runs
- * as in FROZEN mode.</li>
- * <li><b>REFREEZE</b> ({@code -Pgrails.test.refreezeClassicOracle=true}): the classic binder is booted live and the files are rewritten.</li>
+ * <li><b>FROZEN</b> (the default): the recorded files are the oracle. A scanned group with no record, or whose classes changed,
+ * fails with a message that says how to record it; a recorded group no fixture makes up any more is reported as drift.</li>
+ * <li><b>RECORD</b> ({@code -Pgrails.test.recordClassicOracle=true}): the way a contributor adds a fixture. A scanned group that
+ * has no record (or whose classes changed) is booted natively, by the closure the spec passes, and its facts are written to the
+ * file at its place in the scan order; the records of every other group are written back as they are, and the records of groups
+ * no fixture makes up any more are dropped. The diff is what the contributor reviews: for a new fixture it is only additions, and
+ * they state what native binding does, since no classic binder is left to ask. Such a section carries {@code source: native} in
+ * its header: the DDL differential compares its schema (a later change of native binding shows up), the generator differential
+ * does not compare its facets, which only a classic boot could give, and reports it.</li>
* </ul>
*
- * <p>Once the classic binder is deleted VERIFY and REFREEZE go with it; a new fixture then gets its recorded entries by hand.</p>
- *
* <p>The files are plain text, one record per line, sorted and without anything that varies from run to run. A line is
* {@code kind TAB key TAB json}; a line {@code @group TAB key TAB json} opens the section of one group of domain classes, whose
- * header lists the member classes (so a changed fixture set is detected) and, for a group the classic binder cannot boot, the
- * first line of the reason.</p>
+ * header lists the member classes (so a changed fixture set is detected) and, for a group that cannot boot, the first line of
+ * the reason.</p>
*/
class ClassicOracle {
- static final String VERIFY_PROPERTY = 'grails.test.verifyClassicOracle'
- static final String REFREEZE_PROPERTY = 'grails.test.refreezeClassicOracle'
+ static final String RECORD_PROPERTY = 'grails.test.recordClassicOracle'
+ /** The header value that marks a section recorded from a native boot. */
+ static final String NATIVE_SOURCE = 'native'
static final String RESOURCE_DIRECTORY = 'classic-oracle'
- static final String REFREEZE_HINT = 'run the spec with -Pgrails.test.refreezeClassicOracle=true (it boots the classic binder and rewrites ' +
- 'src/test/resources/classic-oracle/) and commit the changed files'
+ static final File DEFAULT_DIRECTORY = new File("src/test/resources/${RESOURCE_DIRECTORY}")
+ static final String RECORD_HINT = 'run the differential specs with -Pgrails.test.recordClassicOracle=true: a scanned group that has ' +
+ 'no record is booted natively and its facts are written to src/test/resources/classic-oracle/, the records of groups no ' +
+ 'fixture makes up any more are dropped, and every other record is written back as it is; review the diff and commit it'
- enum Mode { FROZEN, VERIFY, REFREEZE }
+ enum Mode { FROZEN, RECORD }
/** One group of domain classes: its header and its records. */
static class Section {
@@ -88,28 +93,30 @@ class ClassicOracle {
final String name
final Mode mode
+ private final File directory
private final Map<String, Section> recorded = new LinkedHashMap<String, Section>()
private final Map<String, Section> fresh = new LinkedHashMap<String, Section>()
- private final Set<String> visited = new LinkedHashSet<String>()
+ private final List<String> visited = []
+ /** FROZEN: the recorded groups no scanned fixture makes up any more. */
final List<String> drift = []
+ /** RECORD: the groups recorded by this run. */
+ final List<String> recordedNow = []
+ /** RECORD: the recorded groups dropped from the file because no scanned fixture makes them up any more. */
+ final List<String> dropped = []
ClassicOracle(String name) {
this(name, currentMode())
}
- ClassicOracle(String name, Mode mode) {
+ ClassicOracle(String name, Mode mode, File directory = DEFAULT_DIRECTORY) {
this.name = name
this.mode = mode
- if (mode != Mode.REFREEZE) {
- recorded.putAll(read(name))
- }
+ this.directory = directory
+ recorded.putAll(read(name))
}
static Mode currentMode() {
- if (Boolean.getBoolean(REFREEZE_PROPERTY)) {
- return Mode.REFREEZE
- }
- return Boolean.getBoolean(VERIFY_PROPERTY) ? Mode.VERIFY : Mode.FROZEN
+ return Boolean.getBoolean(RECORD_PROPERTY) ? Mode.RECORD : Mode.FROZEN
}
/** The recorded section of the group whose first member is the key, or null: for the specs of the oracle itself. */
@@ -121,53 +128,59 @@ class ClassicOracle {
return recorded.keySet()
}
- /** True when the classic binder has to be booted (VERIFY and REFREEZE). */
- boolean isLive() {
- return mode != Mode.FROZEN
- }
-
/**
- * The recorded section of a group. In FROZEN mode the closure is not called; in VERIFY mode it is called and its section must equal
- * the recorded one; in REFREEZE mode it is called and its section becomes the record.
+ * The section of a group: the recorded one when the group is recorded with these classes. Otherwise the group is new or
+ * changed: FROZEN fails and says how to record it, RECORD calls the closure and keeps its section for the file.
*
* @param key the first member of the group (groups never share a class)
* @param members the names of the classes of the group
- * @param classic boots the classic binder and builds the section
+ * @param record boots the group natively and builds its section
*/
- Section section(String key, List<String> members, Closure<Section> classic) {
+ Section section(String key, List<String> members, Closure<Section> record) {
visited << key
- if (mode == Mode.REFREEZE) {
- Section section = classic.call()
- fresh[key] = section
- return section
- }
Section stored = recorded[key]
- if (stored == null || stored.header.members != members) {
+ if (stored != null && stored.header.members == members) {
+ return stored
+ }
+ if (mode == Mode.FROZEN) {
throw new IllegalStateException(
"The classic oracle '${name}' has no recorded data for the group of ${key} with the classes ${members} " +
- "(a new or changed fixture): ${REFREEZE_HINT}".toString())
+ "(a new or changed fixture): ${RECORD_HINT}".toString())
}
- if (mode == Mode.VERIFY) {
- Section live = classic.call()
- fresh[key] = live
- if (live.render() != stored.render()) {
- drift << "${key}: ${firstDifference(stored.render(), live.render())}".toString()
- }
- }
- return stored
+ Section section = record.call()
+ fresh[key] = section
+ recordedNow << key
+ return section
}
- /** Ends a run: rewrites the files (REFREEZE), and reports recorded groups no fixture backs any more. */
+ /**
+ * Ends a run. FROZEN reports the recorded groups no fixture backs any more. RECORD writes the file when a group was recorded
+ * or a recorded group is gone: the recorded sections in their order, a recorded group inserted after the scanned group that
+ * precedes it, the groups no fixture makes up any more left out.
+ */
void finish() {
- if (mode == Mode.REFREEZE) {
- File file = new File("src/test/resources/${RESOURCE_DIRECTORY}/${name}.txt")
- file.parentFile.mkdirs()
- file.setText(render(fresh), 'UTF-8')
+ List<String> stale = recorded.keySet().findAll { String key -> !visited.contains(key) }.toList()
+ if (mode == Mode.FROZEN) {
+ stale.each { String key ->
+ drift << "${key}: recorded in '${name}' but no scanned fixture makes up this group any more: ${RECORD_HINT}".toString()
+ }
return
}
- recorded.keySet().findAll { String key -> !visited.contains(key) }.each { String key ->
- drift << "${key}: recorded in '${name}' but no scanned fixture makes up this group any more".toString()
+ dropped.addAll(stale)
+ if (fresh.isEmpty() && stale.isEmpty()) {
+ return
}
+ List<String> order = recorded.keySet().findAll { String key -> visited.contains(key) }.toList()
+ for (String key : recordedNow) {
+ int at = visited.indexOf(key)
+ String before = at == 0 ? null : (at - 1..0).collect { int i -> visited[i] }.find { String candidate -> order.contains(candidate) }
+ order.add(before == null ? 0 : order.indexOf(before) + 1, key)
+ }
+ Map<String, Section> sections = new LinkedHashMap<String, Section>()
+ order.each { String key -> sections[key] = fresh[key] ?: recorded[key] }
+ File file = new File(directory, "${name}.txt")
+ file.parentFile.mkdirs()
+ file.setText(render(sections), 'UTF-8')
}
static String render(Map<String, Section> sections) {
@@ -180,7 +193,7 @@ class ClassicOracle {
String path = "/${RESOURCE_DIRECTORY}/${name}.txt"
InputStream stream = ClassicOracle.getResourceAsStream(path)
if (stream == null) {
- throw new IllegalStateException("The classic oracle file ${path} is missing: ${REFREEZE_HINT}".toString())
+ throw new IllegalStateException("The classic oracle file ${path} is missing: ${RECORD_HINT}".toString())
}
return stream.withCloseable { InputStream input -> parseText(input.getText('UTF-8')) }
}
@@ -203,19 +216,6 @@ class ClassicOracle {
return sections
}
- private static String firstDifference(String recorded, String live) {
- List<String> a = recorded.readLines()
- List<String> b = live.readLines()
- for (int i = 0; i < Math.max(a.size(), b.size()); i++) {
- String left = i < a.size() ? a[i] : '<missing>'
- String right = i < b.size() ? b[i] : '<missing>'
- if (left != right) {
- return "line ${i + 1} differs: recorded=${left.take(300)} live=${right.take(300)}".toString()
- }
- }
- return 'no difference'
- }
-
/**
* The deterministic serialisation: map keys sorted, lists in order, no spaces; a map entry whose value is null is left out unless
* {@code keepNulls} (a recorded fact that is absent reads as null).
@@ -223,8 +223,8 @@ class ClassicOracle {
static String canonical(Object value, boolean keepNulls = false) {
StringBuilder out = new StringBuilder()
write(out, value, keepNulls)
- // the domain binder names an index after the closure mapped as the index of a collection (...$_closure2@3ff5aef4), which holds
- // the identity of the closure instance and differs on every boot
+ // an index named after the closure mapped as the index of a collection (...$_closure2@3ff5aef4) holds the identity of the
+ // closure instance, which differs on every boot
return out.toString().replaceAll(/(_closure\d+)@[0-9a-f]+/, '$1@0')
}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ClassicOracleSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ClassicOracleSpec.groovy
index d6bd6a95e2..648f5ac63d 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ClassicOracleSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ClassicOracleSpec.groovy
@@ -18,6 +18,7 @@
*/
package org.grails.orm.hibernate.cfg.domainbinding.jpa
+import spock.lang.IgnoreIf
import spock.lang.Shared
import spock.lang.Specification
import spock.lang.Unroll
@@ -25,9 +26,9 @@ import spock.lang.Unroll
/**
* The frozen oracle itself ({@link ClassicOracle}): that its serialisation is deterministic, that the recorded files are the canonical
* rendering of what they hold and cover every scanned fixture, that a fixture without recorded data is refused with a message that says how
- * to record it, and that the VERIFY mode notices a recorded group the classic binder no longer produces. That a changed recorded fact makes
- * the comparison fail is proven in {@code GrailsDomainGeneratorDifferentialSpec} and {@code GeneratedDomainClassesDdlDifferentialSpec},
- * which own the comparisons.
+ * to record it, and that the RECORD mode records exactly the groups that have no record and writes every other record back as it is. That
+ * a changed recorded fact makes the comparison fail is proven in {@code GrailsDomainGeneratorDifferentialSpec} and
+ * {@code GeneratedDomainClassesDdlDifferentialSpec}, which own the comparisons.
*/
class ClassicOracleSpec extends Specification {
@@ -100,6 +101,8 @@ class ClassicOracleSpec extends Specification {
oracle << ORACLES
}
+ @IgnoreIf(value = { ClassicOracle.currentMode() == ClassicOracle.Mode.RECORD },
+ reason = 'a recording run writes the file the differential specs read from the classpath; run again to check it')
@Unroll
void "the recorded file #oracle holds every scanned group, and only those"() {
given:
@@ -128,6 +131,8 @@ class ClassicOracleSpec extends Specification {
oracle << ORACLES
}
+ @IgnoreIf(value = { ClassicOracle.currentMode() == ClassicOracle.Mode.RECORD },
+ reason = 'a recording run writes the file the differential specs read from the classpath; run again to check it')
void "the groups the classic binder booted have their entities in the generator oracle and their tables and statements in the DDL oracle"() {
given:
ClassicOracle generator = new ClassicOracle('generator-differential', ClassicOracle.Mode.FROZEN)
@@ -156,7 +161,7 @@ class ClassicOracleSpec extends Specification {
then:
IllegalStateException e = thrown()
e.message.contains('org.example.NewFixture')
- e.message.contains('-Pgrails.test.refreezeClassicOracle=true')
+ e.message.contains('-Pgrails.test.recordClassicOracle=true')
e.message.contains('src/test/resources/classic-oracle/')
!booted
@@ -176,13 +181,13 @@ class ClassicOracleSpec extends Specification {
then:
IllegalStateException e = thrown()
- e.message.contains('-Pgrails.test.refreezeClassicOracle=true')
+ e.message.contains('-Pgrails.test.recordClassicOracle=true')
where:
oracle << ORACLES
}
- void "the frozen mode does not call the classic binder for a recorded group and returns the recorded section"() {
+ void "the frozen mode does not call the recorder for a recorded group and returns the recorded section"() {
given:
ClassicOracle frozen = new ClassicOracle('ddl-differential', ClassicOracle.Mode.FROZEN)
String key = frozen.recordedKeys().first()
@@ -194,49 +199,101 @@ class ClassicOracleSpec extends Specification {
then:
!booted
- !frozen.isLive()
section.is(frozen.recordedSection(key))
frozen.drift.isEmpty()
}
- void "the verify mode notices a group the classic binder no longer produces as it was recorded"() {
+ void "the frozen mode reports recorded groups that were not visited, with the way to drop them"() {
given:
- ClassicOracle verify = new ClassicOracle('ddl-differential', ClassicOracle.Mode.VERIFY)
- ClassicOracle.Section recorded = verify.recordedSection(verify.recordedKeys().find {
- verify.recordedSection(it).header.unbootable == null
- })
- List<String> members = (List<String>) recorded.header.members
- ClassicOracle.Section same = new ClassicOracle.Section(recorded.key, recorded.header)
- same.records.addAll(recorded.records)
- ClassicOracle.Section other = new ClassicOracle.Section(recorded.key, recorded.header)
- other.records.addAll(recorded.records)
- other.records[0] = [other.records[0][0], other.records[0][1], '{"changed":true}']
+ ClassicOracle frozen = new ClassicOracle('generator-differential', ClassicOracle.Mode.FROZEN)
when:
- verify.section(recorded.key, members) { same }
+ frozen.finish()
- then: "the same section is the recorded one"
- verify.isLive()
- verify.drift.isEmpty()
+ then:
+ frozen.drift.size() == frozen.recordedKeys().size()
+ frozen.drift.every { String line -> line.contains('no scanned fixture') && line.contains('-Pgrails.test.recordClassicOracle=true') }
+ }
+
+ void "the record mode returns a recorded group without calling the recorder, and writes nothing when every record is backed"() {
+ given:
+ File directory = File.createTempDir('classic-oracle', 'record')
+ ClassicOracle record = new ClassicOracle('ddl-differential', ClassicOracle.Mode.RECORD, directory)
+ boolean booted = false
when:
- verify.section(recorded.key, members) { other }
+ record.recordedKeys().each { String key ->
+ record.section(key, (List<String>) record.recordedSection(key).header.members) { booted = true; null }
+ }
+ record.finish()
- then: "a section that differs is reported with the first line that does"
- verify.drift.size() == 1
- verify.drift[0].contains(recorded.key)
- verify.drift[0].contains('differs')
+ then:
+ !booted
+ record.recordedNow.isEmpty()
+ record.dropped.isEmpty()
+ !new File(directory, 'ddl-differential.txt').exists()
+
+ cleanup:
+ directory.deleteDir()
}
- void "the verify mode reports recorded groups that were not visited"() {
+ void "the record mode records a group that has no record from the recorder, at its place in the scan order, and writes every other record back as it is"() {
given:
- ClassicOracle verify = new ClassicOracle('generator-differential', ClassicOracle.Mode.VERIFY)
+ File directory = File.createTempDir('classic-oracle', 'record')
+ String original = ClassicOracle.getResourceAsStream("/${ClassicOracle.RESOURCE_DIRECTORY}/ddl-differential.txt").getText('UTF-8')
+ ClassicOracle record = new ClassicOracle('ddl-differential', ClassicOracle.Mode.RECORD, directory)
+ List<String> keys = record.recordedKeys().toList()
+ ClassicOracle.Section fresh = new ClassicOracle.Section('org.example.NewFixture', [members: ['org.example.NewFixture']])
+ fresh.add('table', 'new_fixture', [columns: [id: [type: 'bigint']]], true)
+ int booted = 0
+
+ when: "the scan visits the new group after the third recorded one"
+ keys.eachWithIndex { String key, int index ->
+ record.section(key, (List<String>) record.recordedSection(key).header.members) { booted++; null }
+ if (index == 2) {
+ record.section('org.example.NewFixture', ['org.example.NewFixture']) { booted++; fresh }
+ }
+ }
+ record.finish()
+ String written = new File(directory, 'ddl-differential.txt').getText('UTF-8')
+
+ then: "the recorder ran for the new group only"
+ booted == 1
+ record.recordedNow == ['org.example.NewFixture']
+ record.dropped.isEmpty()
+
+ and: "the file is the original with the new section inserted after the third group, byte for byte otherwise"
+ written.length() == original.length() + fresh.render().length()
+ written.startsWith(original.substring(0, original.indexOf("@group\t${keys[3]}\t")))
+ written.endsWith(original.substring(original.indexOf("@group\t${keys[3]}\t")))
+ written.contains(fresh.render())
+ ClassicOracle.parseText(written).keySet().toList() == keys[0..2] + ['org.example.NewFixture'] + keys[3..-1]
+
+ cleanup:
+ directory.deleteDir()
+ }
+
+ void "the record mode drops a recorded group no scanned fixture makes up any more and says so"() {
+ given:
+ File directory = File.createTempDir('classic-oracle', 'record')
+ ClassicOracle record = new ClassicOracle('ddl-differential', ClassicOracle.Mode.RECORD, directory)
+ List<String> keys = record.recordedKeys().toList()
+ String gone = keys.last()
when:
- verify.finish()
+ keys.findAll { it != gone }.each { String key ->
+ record.section(key, (List<String>) record.recordedSection(key).header.members) { null }
+ }
+ record.finish()
+ Map<String, ClassicOracle.Section> written = ClassicOracle.parseText(new File(directory, 'ddl-differential.txt').getText('UTF-8'))
then:
- verify.drift.size() == verify.recordedKeys().size()
- verify.drift.every { String line -> line.contains('no scanned fixture') }
+ record.dropped == [gone]
+ record.recordedNow.isEmpty()
+ written.keySet().toList() == keys - gone
+ written.values()*.render() == (keys - gone).collect { String key -> record.recordedSection(key).render() }
+
+ cleanup:
+ directory.deleteDir()
}
}
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 5bb9d68b8b..67e5f75a42 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
@@ -45,18 +45,16 @@ import org.grails.datastore.mapping.reflect.ClassUtils
import org.grails.orm.hibernate.HibernateDatastore
/**
- * What a user with an existing database would see if they switched {@code hibernate.generatedDomainClasses} on: the schema
- * Hibernate derives from the generated classes against the schema the domain binder derives from the same domain classes.
- *
- * <p>Every group of associated domain classes of the scanned test domains ({@link ScannedDomainClasses}) is booted twice
- * on H2, once in each mode, and the Hibernate mapping model of both (tables, columns with their type, nullability, default,
- * length, precision and scale, primary keys with their column order, foreign keys, unique keys, indexes, check constraints,
- * sequences) is compared. As a backstop for what the model does not show, the schema H2 itself holds after the boot
- * ({@code SCRIPT NODATA}, with H2's generated constraint names normalised) is compared too, and a statement that differs
- * for a table with no difference in the model fails the spec as an unexplained difference.</p>
+ * Compares the schema native binding derives from every group of related domain classes of the test suites with the schema the
+ * classic domain binder of Grails 8 derived from them, recorded in {@code classic-oracle/ddl-differential.txt} before it was
+ * deleted ({@link ClassicOracle}): tables, columns with their types, nullability, defaults and lengths, primary keys and their
+ * column order, foreign keys, unique keys, indexes, check constraints and sequences, and H2's {@code SCRIPT NODATA} (with the
+ * generated constraint names normalised). What a user with an existing database created by Grails 8 sees when the upgraded
+ * application starts against it.
*
* <p>The spec fails on every difference that is not covered by an entry of {@link #KNOWN}, each of which states why the
- * difference is kept. The categorised report is written to {@code build/ddl-report.txt}.</p>
+ * difference is kept, and on an H2 statement that differs without a known difference explaining it. A new fixture gets its record
+ * from a native boot with {@code -Pgrails.test.recordClassicOracle=true} ({@link #nativeSection}).</p>
*/
class GeneratedDomainClassesDdlDifferentialSpec extends Specification {
@@ -143,7 +141,7 @@ class GeneratedDomainClassesDdlDifferentialSpec extends Specification {
int scriptStatements = 0
for (List<Class<?>> group : groups) {
String name = group*.simpleName.join(',').take(120)
- ClassicOracle.Section section = oracle.section(group.first().name, group*.name) { classicSection(group) }
+ ClassicOracle.Section section = oracle.section(group.first().name, group*.name) { nativeSection(group) }
if (section.header.unbootable != null) {
binderUnbootable[name] = section.header.unbootable.toString()
continue
@@ -154,7 +152,7 @@ class GeneratedDomainClassesDdlDifferentialSpec extends Specification {
}
Map generated
try {
- generated = (Map) ClassicOracle.normalized(snapshot(group, true), true)
+ generated = (Map) ClassicOracle.normalized(snapshot(group), true)
} catch (Throwable e) {
generatedRefused[name] = firstLine(e)
continue
@@ -173,17 +171,19 @@ class GeneratedDomainClassesDdlDifferentialSpec extends Specification {
}
/**
- * What the domain binder produces for a group, as a section of the oracle file: the snapshot of the schema it derived, or the first
- * line of the reason it cannot boot the group. Only called when the classic binder is booted (VERIFY and REFREEZE).
+ * The record of a group that has none, taken from a native boot (the files were recorded from the classic binder before it was
+ * deleted; this is how a new fixture joins them): the snapshot of the schema, or the first line of the reason the group cannot
+ * boot. Only called in the RECORD mode of {@link ClassicOracle}.
*/
- static ClassicOracle.Section classicSection(List<Class<?>> group) {
+ static ClassicOracle.Section nativeSection(List<Class<?>> group) {
Map schema
try {
- schema = snapshot(group, false)
+ schema = snapshot(group)
} catch (Throwable e) {
- return new ClassicOracle.Section(group.first().name, [members: group*.name, unbootable: ClassicOracle.stableReason(firstLine(e))])
+ return new ClassicOracle.Section(group.first().name,
+ [members: group*.name, source: ClassicOracle.NATIVE_SOURCE, unbootable: ClassicOracle.stableReason(firstLine(e))])
}
- ClassicOracle.Section section = new ClassicOracle.Section(group.first().name, [members: group*.name])
+ ClassicOracle.Section section = new ClassicOracle.Section(group.first().name, [members: group*.name, source: ClassicOracle.NATIVE_SOURCE])
((Map<String, Map>) schema.tables).keySet().sort().each { String table -> section.add('table', table, schema.tables[table], true) }
((Map<String, Map>) schema.sequences).keySet().sort().each { String sequence -> section.add('sequence', sequence, schema.sequences[sequence], true) }
((List<String>) schema.script).each { String statement -> section.add('script', '', statement, true) }
@@ -272,14 +272,12 @@ class GeneratedDomainClassesDdlDifferentialSpec extends Specification {
}
/**
- * Boots a group in one mode, with the settings of the other mode identical, and reads the schema model and the H2 script
- * back as plain data so that the datastore can be closed.
+ * Boots a group and reads the schema model and the H2 script back as plain data so that the datastore can be closed.
*/
- private static Map snapshot(List<Class<?>> group, boolean generated) {
+ private static Map snapshot(List<Class<?>> group) {
Map<String, Object> config = [
- 'dataSource.url' : "jdbc:h2:mem:ddlDiff${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
- 'dataSource.dbCreate' : 'create-drop',
- 'hibernate.generatedDomainClasses': generated,
+ 'dataSource.url' : "jdbc:h2:mem:ddlDiff${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
+ 'dataSource.dbCreate': 'create-drop',
]
if (group.any { Class<?> type -> ClassUtils.isMultiTenant(type) }) {
config['grails.gorm.multiTenancy.mode'] = MultiTenancySettings.MultiTenancyMode.DISCRIMINATOR
@@ -572,8 +570,11 @@ class GeneratedDomainClassesDdlDifferentialSpec extends Specification {
"with the domain binder, ${generatedRefused.size()} refused by the generated mode; ${tables} tables, " +
"${scriptStatements} H2 statements; ${differences.size()} differences, ${unknown.size()} not known, " +
"${unexplained.size()} unexplained H2 statements\n"
- report << "classic oracle: ${oracle.mode}${oracle.drift.isEmpty() ? '' : ", ${oracle.drift.size()} recorded groups differ from the live classic binder"}\n"
+ report << "classic oracle: ${oracle.mode}${oracle.recordedNow.isEmpty() ? '' : ", ${oracle.recordedNow.size()} groups recorded from a native boot"}" +
+ "${oracle.dropped.isEmpty() ? '' : ", ${oracle.dropped.size()} recorded groups dropped"}\n"
oracle.drift.each { report << " DRIFT ${it}\n" }
+ oracle.recordedNow.each { report << " RECORDED ${it}\n" }
+ oracle.dropped.each { report << " DROPPED ${it}\n" }
report << '\n'
report << "difference classes (kind, on a join table or not): count, example\n"
Map<String, List<Map>> byClass = differences.groupBy { Map d -> d.cls }
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 370a2a29ba..2bcd3bd7c2 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
@@ -64,16 +64,16 @@ import org.grails.orm.hibernate.cfg.domainbinding.util.ColumnNameForPropertyAndP
import org.grails.orm.hibernate.cfg.domainbinding.util.DefaultColumnNameFetcher
/**
- * Compares {@link GrailsDomainGenerator} with the domain binder on real entities. For every supported property of
- * every entity the binder can bind, the column facets the generator decides must equal the ones the binder put on the
- * bound Hibernate {@code Column} and {@code Property}. The binder is the oracle, so a mismatch is either a generator
- * bug or a rule that was mirrored wrongly.
+ * Compares {@link GrailsDomainGenerator} with the classic domain binder of Grails 8 on real entities. For every supported
+ * property of every entity the classic binder could bind, the column facets the generator decides must equal the ones the
+ * classic binder put on the bound Hibernate {@code Column} and {@code Property}. The classic binder is the oracle, so a mismatch
+ * is either a generator bug or a rule that was mirrored wrongly.
*
- * <p>The oracle is FROZEN: what the binder bound is read from {@code classic-oracle/generator-differential.txt}
- * ({@link ClassicOracle}, {@link ClassicFacts}), recorded once, and the classic binder is not booted. The generator's side is read
- * from the mapping of a datastore booted through the generated classes. {@code -Pgrails.test.verifyClassicOracle=true} boots the
- * classic binder too and requires it to produce exactly the recorded facts; {@code -Pgrails.test.refreezeClassicOracle=true}
- * rewrites the file from it.</p>
+ * <p>The oracle is FROZEN: what the classic binder bound is read from {@code classic-oracle/generator-differential.txt}
+ * ({@link ClassicOracle}, {@link ClassicFacts}), recorded once before the classic binder was deleted. The generator's side is read
+ * from the mapping of a datastore booted through the generated classes. A new fixture gets its record from a native boot with
+ * {@code -Pgrails.test.recordClassicOracle=true} ({@link #nativeSection}); its comparison is then native against native, and the
+ * diff of the recorded file is what is reviewed.</p>
*
* <p>The entities are every domain class in the TCK and in the Hibernate 7 tests, which are written to exercise
* binder permutations. They are grouped by association so each group boots as its own datastore; a group that cannot
@@ -157,6 +157,7 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec {
List<String> oracleProblems = []
Map<String, Integer> skipped = [:].withDefault { 0 }
Map<String, String> unbootable = [:]
+ Map<String, Integer> nativeRecorded = [:]
int compared = 0
int entities = 0
int derived = 0
@@ -177,11 +178,18 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec {
List<String> rejectedComposites = []
for (List<Class<?>> group : groups) {
- ClassicOracle.Section section = oracle.section(group.first().name, group*.name) { classicSection(group) }
+ ClassicOracle.Section section = oracle.section(group.first().name, group*.name) { nativeSection(group) }
if (section.header.unbootable != null) {
unbootable[group*.simpleName.join(',')] = section.header.unbootable.toString()
continue
}
+ if (section.header.source == ClassicOracle.NATIVE_SOURCE) {
+ // recorded from a native boot after the classic binder was deleted: the bound facts hold what Hibernate's own binder
+ // fills in (the default discriminator value, the default cache strategy, a length on the version), which no classic
+ // binding ever stated, so there are no classic facets to compare; the DDL differential compares the schema
+ nativeRecorded[group*.simpleName.join(',')] = section.parsedByKey('entity').size()
+ continue
+ }
classic = section.parsedByKey('entity')
classicFilters = section.parsedByKey('filter')
if (perturb != null) {
@@ -198,7 +206,7 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec {
List<GrailsHibernatePersistentEntity> boundEntities = datastore.mappingContext.getHibernatePersistentEntities()
.findAll { group.contains(it.javaClass) && classic.containsKey(it.name) }
if (boundEntities*.name.toSet() != classic.keySet()) {
- oracleProblems << "${group*.simpleName.join(',')}: the recorded entities ${classic.keySet()} are not the entities ${boundEntities*.name} the mapping holds: ${ClassicOracle.REFREEZE_HINT}".toString()
+ oracleProblems << "${group*.simpleName.join(',')}: the recorded entities ${classic.keySet()} are not the entities ${boundEntities*.name} the mapping holds: ${ClassicOracle.RECORD_HINT}".toString()
}
boundEntities.each { GrailsHibernatePersistentEntity entity -> replayJoinTables(entity) }
for (GrailsHibernatePersistentEntity entity : boundEntities) {
@@ -354,7 +362,7 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec {
}
}
return [
- mismatches: mismatches, oracleProblems: oracleProblems, skipped: skipped, unbootable: unbootable, compared: compared,
+ mismatches: mismatches, oracleProblems: oracleProblems, skipped: skipped, unbootable: unbootable, nativeRecorded: nativeRecorded, compared: compared,
entities: entities, derived: derived, embeddedProperties: embeddedProperties, embeddedLeaves: embeddedLeaves,
explicitTypes: explicitTypes, collections: collections, known: known, tenants: tenants, strategies: strategies,
hierarchies: hierarchies, annotationRead: annotationRead, associations: associations, constraints: constraints,
@@ -369,8 +377,11 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec {
report << "differential: ${candidates} candidate classes in ${groups} groups; " +
"${unbootable.size()} groups could not boot alone; ${result.entities} entities, ${result.compared} properties compared " +
"(${result.derived} derived); ${result.embeddedProperties} embedded properties compared, ${result.embeddedLeaves} embedded columns\n"
- report << "classic oracle: ${oracle.mode}${oracle.drift.isEmpty() ? '' : ", ${oracle.drift.size()} recorded groups differ from the live classic binder"}\n"
+ report << "classic oracle: ${oracle.mode}${oracle.recordedNow.isEmpty() ? '' : ", ${oracle.recordedNow.size()} groups recorded from a native boot"}" +
+ "${oracle.dropped.isEmpty() ? '' : ", ${oracle.dropped.size()} recorded groups dropped"}\n"
oracle.drift.each { report << "DRIFT ${it}\n" }
+ oracle.recordedNow.each { report << "RECORDED ${it}\n" }
+ oracle.dropped.each { report << "DROPPED ${it}\n" }
result.oracleProblems.each { report << "ORACLE ${it}\n" }
report << "explicit types compared: ${result.explicitTypes}\n"
report << "collections of basic values compared by kind: ${result.collections}\n"
@@ -388,28 +399,31 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec {
report << "unsupported by kind: ${result.skipped}\n"
report << "mismatches by facet: ${mismatches.groupBy { (it =~ /\s(\w+): generator=/)[0][1] }.collectEntries { k, v -> [k, v.size()] }}\n"
unbootable.each { report << "unbootable: ${it.key.take(120)} -> ${it.value.take(200)}\n" }
+ ((Map<String, Integer>) result.nativeRecorded).each { report << "recorded from a native boot, not compared: ${it.key.take(120)} (${it.value} entities)\n" }
mismatches.each { report << "MISMATCH ${it}\n" }
new File('build/differential-report.txt').text = report.toString()
}
/**
- * What the classic binder bound for a group, as a section of the oracle file: for each entity the facts {@link ClassicFacts} reads
- * from its {@code PersistentClass} (and the identifier generator the session factory holds for a root with a simple identifier), the
- * filter definitions of the session factory, or the first line of the reason it cannot boot the group. Only called when the classic
- * binder is booted (VERIFY and REFREEZE).
+ * The record of a group that has none, taken from a native boot (the files were recorded from the classic binder before it was
+ * deleted; this is how a new fixture joins them): for each entity the facts {@link ClassicFacts} reads from its bound
+ * {@code PersistentClass} (and the identifier generator the session factory holds for a root with a simple identifier), the join
+ * table state of its collection properties, the filter definitions of the session factory, or the first line of the reason the
+ * group cannot boot. Only called in the RECORD mode of {@link ClassicOracle}.
*/
- static ClassicOracle.Section classicSection(List<Class<?>> group) {
+ static ClassicOracle.Section nativeSection(List<Class<?>> group) {
HibernateDatastore datastore
try {
- datastore = boot(group)
+ datastore = bootGenerated(group)
} catch (Throwable e) {
return new ClassicOracle.Section(group.first().name, [
members : group*.name,
+ source : ClassicOracle.NATIVE_SOURCE,
unbootable: ClassicOracle.stableReason((e.message ?: e.getClass().simpleName).readLines().first()),
])
}
try {
- ClassicOracle.Section section = new ClassicOracle.Section(group.first().name, [members: group*.name])
+ ClassicOracle.Section section = new ClassicOracle.Section(group.first().name, [members: group*.name, source: ClassicOracle.NATIVE_SOURCE])
SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) datastore.sessionFactory
List<GrailsHibernatePersistentEntity> bound = datastore.mappingContext.getHibernatePersistentEntities()
.findAll { group.contains(it.javaClass) && it.persistentClass != null && it.persistentClass.entityName == it.name }
@@ -447,9 +461,9 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec {
}
/**
- * Puts back on the mapping of an entity the join tables the classic binder left on it. The classic binder writes into the mapping while it
- * binds (the inverse side of a many-to-many adopts the owning side's join table, a circular many-to-many gets a renamed key) and this
- * comparison has always read the mapping the binder left, so the generator reads the same state here, on a mapping the binder never touched.
+ * Puts back on the mapping of an entity the join table state recorded for it. The classic binder wrote into the mapping while it
+ * bound (the inverse side of a many-to-many adopted the owning side's join table, a circular many-to-many got a renamed key) and
+ * this comparison has always read the mapping it left, so the generator reads the same state here, on a mapping nothing wrote into.
*/
private void replayJoinTables(GrailsHibernatePersistentEntity entity) {
Map<String, Map> states = (Map<String, Map>) classic[entity.name].joinTables ?: [:]
@@ -459,36 +473,14 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec {
}
}
- /**
- * Boots a group of entities with the classic binder (stated, since native binding is the default). GORM only gives an entity a tenant id (and the binder only adds the tenant filter) in
- * discriminator multi-tenancy mode, so a group with multi-tenant entities is booted in that mode when it can be.
- */
- private static HibernateDatastore boot(List<Class<?>> group) {
- if (group.any { Class<?> type -> ClassUtils.isMultiTenant(type) }) {
- try {
- return new HibernateDatastore([
- 'dataSource.dbCreate' : 'create-drop',
- 'hibernate.generatedDomainClasses' : false,
- 'grails.gorm.multiTenancy.mode' : MultiTenancySettings.MultiTenancyMode.DISCRIMINATOR,
- 'grails.gorm.multiTenancy.tenantResolver': new SystemPropertyTenantResolver(),
- ], group as Class[])
- } catch (Exception ignored) {
- // a domain that needs another configuration is booted by default below
- }
- }
- // the same create-drop the no-argument constructor applies, which resolves the SQL types the records hold
- return new HibernateDatastore(['dataSource.dbCreate': 'create-drop', 'hibernate.generatedDomainClasses': false], group as Class[])
- }
-
/**
* Boots a group through the generated classes, which is what the comparison reads the mapping of: the entities, their properties and the
* facets the generator decides from them. The tenant mode is the one the classic binder was booted in.
*/
private static HibernateDatastore bootGenerated(List<Class<?>> group) {
Map<String, Object> config = [
- 'dataSource.url' : "jdbc:h2:mem:generatorDiff${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
- 'dataSource.dbCreate' : 'create-drop',
- 'hibernate.generatedDomainClasses': true,
+ 'dataSource.url' : "jdbc:h2:mem:generatorDiff${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(),
+ 'dataSource.dbCreate': 'create-drop',
]
if (group.any { Class<?> type -> ClassUtils.isMultiTenant(type) }) {
config['grails.gorm.multiTenancy.mode'] = MultiTenancySettings.MultiTenancyMode.DISCRIMINATOR