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/04/12 00:37:13 UTC
(grails-core) 02/17: docs: Update JACOCO_COVERAGE_VIOLATIONS.md and improve HibernateGormInstanceApiSpec tests
This is an automated email from the ASF dual-hosted git repository.
borinquenkid pushed a commit to branch 8.0.x-hibernate7-dev
in repository https://gitbox.apache.org/repos/asf/grails-core.git
commit 62d1f794b6e03b314914245a786fa53cfb9cc325
Author: Walter Duque de Estrada <wb...@mac.com>
AuthorDate: Sat Apr 11 16:01:28 2026 -0500
docs: Update JACOCO_COVERAGE_VIOLATIONS.md and improve HibernateGormInstanceApiSpec tests
---
JACOCO_COVERAGE_VIOLATIONS.md | 234 ++++++++++++++++++++
.../orm/hibernate/HibernateGormEnhancerSpec.groovy | 60 +++++
.../hibernate/HibernateGormInstanceApiSpec.groovy | 246 ++++++++++++---------
.../GrailsSequenceStyleGeneratorSpec.groovy | 140 ++++++++++++
.../generator/GrailsTableGeneratorSpec.groovy | 130 +++++++++++
.../hibernate/HibernatePersistentEntitySpec.groovy | 136 ++++++++++++
.../dirty/GrailsEntityDirtinessStrategySpec.groovy | 169 ++++++++++++++
7 files changed, 1015 insertions(+), 100 deletions(-)
diff --git a/JACOCO_COVERAGE_VIOLATIONS.md b/JACOCO_COVERAGE_VIOLATIONS.md
new file mode 100644
index 0000000000..17b311857b
--- /dev/null
+++ b/JACOCO_COVERAGE_VIOLATIONS.md
@@ -0,0 +1,234 @@
+You are a Groovy/Spock testing expert. Your task is to analyze a JaCoCo
+coverage markdown report and systematically improve test coverage for an
+entire module, working from lowest to highest coverage.
+
+## Inputs
+
+1. **Coverage Report** (Markdown): this document
+2. **Target Module**: `[e.g. grails-data-hibernate7-core]`
+3. **Source Root**: `[e.g. grails-data-hibernate7-core/src/main/groovy]`
+4. **Test Root**: `[e.g. grails-data-hibernate7-core/src/test/groovy]`
+
+## Step 1 — Extract the Module Table
+
+Read the markdown report and find the section with the header:
+`## Module: [Target Module]`
+
+Extract all rows from that module's table. The table is already sorted
+ascending by % Instructions Covered — do NOT reorder it. This is your
+work queue. Process rows strictly top-to-bottom.
+
+## Step 2 — Skip Closure-Only Rows
+
+For rows whose class name contains patterns like `._`, `.new`, `.$`,
+or `_closure`:
+- Do NOT create a dedicated spec for them
+- Note them as sub-targets: when you reach their parent class, these
+ closures are your highest-priority branches to trigger inside that spec
+- A parent class is the prefix before the first `_` or `.new` in the name
+
+## Step 3 — For Each Class (top-to-bottom)
+
+For each top-level class row, in order:
+
+### 3a. Locate Files
+- Source file: resolve `[Source Root]/[package/ClassName].groovy`
+- Spec file: look for `[Test Root]/[package/ClassNameSpec.groovy]`
+ - If found: read it and note what is already covered
+ - If not found: create a new Spock spec from scratch
+
+### 3b. Identify Coverage Gaps
+Read the source class and determine uncovered paths:
+- Conditionals: if/else, switch, ternary `?:`, null-safe `?.`
+- Exception handling: try/catch/finally blocks
+- Groovy closures: each{}, collect{}, find{}, with{} — check if any
+ corresponding `_closureN` row for this class is at 0.00%
+- Edge cases: nulls, empty collections, boundary values
+
+### 3c. Write Tests
+Add feature methods to the spec:
+- Name: `def "should [behavior] when [condition]"`
+- Structure: `given/when/then` or `expect` blocks
+- Use `where:` + `@Unroll` for multiple branches of the same method
+- Mock all dependencies with `Mock()` or `Stub()`
+- For every 0.00% closure row belonging to this class, write at least
+ one test that causes that closure to execute
+- Never delete or modify existing passing tests
+
+### 3d. Move to Next Row
+Once tests are written for the current class, proceed to the next row
+in the table without waiting for confirmation.
+
+## Step 4 — Stop Condition
+
+Stop processing when one of these is true:
+- All rows in the module table have been processed, OR
+- You reach a row at or above 95% coverage
+
+## Step 5 — Final Summary
+
+Output a table of everything done:
+
+| Class | Coverage Before | Tests Added | Closures Triggered |
+|-------|-----------------|-------------|--------------------|
+| ... | ...% | N | ... |
+
+# JaCoCo Coverage Report
+Generated on: 2026-04-09 19:19:20
+
+## Module: grails-async-gpars
+| Class | % Instructions Covered |
+| :--- | :--- |
+| org.grails.async.factory.gpars.GparsPromiseFactory._onError_closure3 | 0.00% |
+| org.grails.async.factory.gpars.LoggingPoolFactory.new RejectedExecutionHandler() {...} | 0.00% |
+| org.grails.async.factory.gpars.GparsPromise._accept_closure1 | 0.00% |
+| org.grails.async.factory.gpars.LoggingPoolFactory.1.new Thread.UncaughtExceptionHandler() {...} | 0.00% |
+| org.grails.async.factory.gpars.GparsPromiseFactory | 55.45% |
+| org.grails.async.factory.gpars.GparsPromise | 65.03% |
+| org.grails.async.factory.gpars.GparsPromiseFactory.__clinit__closure1 | 71.43% |
+| org.grails.async.factory.gpars.LoggingPoolFactory | 72.81% |
+| org.grails.async.factory.gpars.GparsPromise._onError_closure3 | 100.00% |
+| org.grails.async.factory.gpars.LoggingPoolFactory.new ThreadFactory() {...} | 100.00% |
+| org.grails.async.factory.gpars.GparsPromiseFactory._toGparsPromises_closure2 | 100.00% |
+| org.grails.async.factory.gpars.GparsPromise._onComplete_closure2 | 100.00% |
+
+## Module: grails-async-rxjava
+| Class | % Instructions Covered |
+| :--- | :--- |
+| org.grails.async.factory.rxjava.RxPromiseFactory._waitAll_closure2 | 0.00% |
+| org.grails.async.factory.rxjava.RxPromiseFactory._waitAll_closure1 | 0.00% |
+| org.grails.async.factory.rxjava.RxPromiseFactory | 63.08% |
+| org.grails.async.factory.rxjava.RxPromise | 73.22% |
+| org.grails.async.factory.rxjava.RxPromiseFactory._onComplete_closure3 | 85.71% |
+| org.grails.async.factory.rxjava.RxPromise._closure1 | 90.48% |
+| org.grails.async.factory.rxjava.RxPromiseFactory._onError_closure4 | 100.00% |
+
+## Module: grails-async-rxjava2
+| Class | % Instructions Covered |
+| :--- | :--- |
+| org.grails.async.factory.rxjava2.RxPromiseFactory._waitAll_closure1 | 0.00% |
+| org.grails.async.factory.rxjava2.RxPromiseFactory._waitAll_closure2 | 0.00% |
+| org.grails.async.factory.rxjava2.RxPromiseFactory | 63.36% |
+| org.grails.async.factory.rxjava2.RxPromise | 74.49% |
+| org.grails.async.factory.rxjava2.RxPromiseFactory._onComplete_closure3 | 86.36% |
+| org.grails.async.factory.rxjava2.RxPromise._closure1 | 90.48% |
+| org.grails.async.factory.rxjava2.RxPromise.new Observer() {...} | 100.00% |
+| org.grails.async.factory.rxjava2.RxPromiseFactory._onError_closure4 | 100.00% |
+
+## Module: grails-async-rxjava3
+| Class | % Instructions Covered |
+| :--- | :--- |
+| org.grails.async.factory.rxjava3.RxPromiseFactory._waitAll_closure2 | 0.00% |
+| org.grails.async.factory.rxjava3.RxPromiseFactory._waitAll_closure1 | 0.00% |
+| org.grails.async.factory.rxjava3.RxPromiseFactory | 63.36% |
+| org.grails.async.factory.rxjava3.RxPromise | 74.49% |
+| org.grails.async.factory.rxjava3.RxPromiseFactory._onComplete_closure3 | 86.36% |
+| org.grails.async.factory.rxjava3.RxPromise._closure1 | 90.48% |
+| org.grails.async.factory.rxjava3.RxPromise.new Observer() {...} | 100.00% |
+| org.grails.async.factory.rxjava3.RxPromiseFactory._onError_closure4 | 100.00% |
+
+## Module: grails-data-hibernate7-core
+| Class | % Instructions Covered |
+| :--- | :--- |
+| org.grails.orm.hibernate.HibernateDatastore | 73.47% | X
+| grails.orm.HibernateCriteriaBuilder | 74.43% | X
+| org.grails.orm.hibernate.support.ClosureEventTriggeringInterceptor | 78.96% | X
+| org.grails.orm.hibernate.HibernateDatastore.SchemaTenantGormEnhancer | 82.95% | X
+| org.grails.orm.hibernate.cfg.GrailsHibernateUtil | 83.80% | X
+| org.grails.orm.hibernate.HibernateGormInstanceApi | 84.68% | X
+| org.grails.orm.hibernate.connections.HibernateConnectionSourceFactory | 85.28% | X
+| org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyCollectionProperty | 85.71% | X
+| org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateEmbeddedPersistentEntity | 85.92% | X
+| org.grails.orm.hibernate.cfg.domainbinding.generator.GrailsNativeGenerator | 85.96% | X
+| org.grails.orm.hibernate.query.PredicateGenerator | 86.16% | X
+| org.grails.orm.hibernate.event.listener.HibernateEventListener | 87.53% | X
+| org.grails.orm.hibernate.HibernateGormStaticApi | 87.83% | X
+| org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsPropertyBinder | 88.24% | X
+| org.grails.orm.hibernate.compiler.HibernateEntityTransformation | 88.32% | X
+| org.grails.orm.hibernate.cfg.domainbinding.util.NamespaceNameExtractor | 88.46% | X
+| org.grails.orm.hibernate.cfg.domainbinding.generator.GrailsTableGenerator | 88.66% | X
+| org.grails.orm.hibernate.cfg.IdentityEnumType | 88.82% | X
+| org.grails.orm.hibernate.cfg.domainbinding.binder.ColumnBinder | 88.89% | X
+| org.grails.orm.hibernate.GrailsHibernateTemplate | 89.03% | X
+| org.grails.orm.hibernate.support.SoftKey | 89.09% | X
+| org.grails.orm.hibernate.cfg.domainbinding.util.UniqueKeyForColumnsCreator | 89.47% | X
+| org.grails.orm.hibernate.cfg.domainbinding.generator.GrailsSequenceStyleGenerator | 89.47% | X
+| org.grails.orm.hibernate.proxy.ByteBuddyGroovyInterceptor | 89.47% | X
+| org.grails.orm.hibernate.query.HibernateHqlQuery | 89.52% | X
+| grails.orm.CriteriaMethodInvoker | 89.68% | X
+| org.grails.orm.hibernate.access.TraitPropertyAccessStrategy | 89.81% | X
+| org.grails.orm.hibernate.query.MutationQueryDelegate | 90.41% | X
+| org.grails.orm.hibernate.cfg.ColumnConfig | 90.43% | X
+| org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty | 90.49% | X
+| org.grails.orm.hibernate.cfg.domainbinding.binder.ClassPropertiesBinder | 90.54% | X
+| org.grails.orm.hibernate.HibernateSession | 90.62% | X
+| org.grails.orm.hibernate.cfg.HibernateMappingContextConfiguration | 90.95% | X
+| org.grails.orm.hibernate.cfg.Mapping | 91.00% | X
+| org.grails.orm.hibernate.cfg.domainbinding.binder.RootPersistentClassCommonValuesBinder | 91.24% | X
+| org.grails.orm.hibernate.GrailsSessionContext | 91.51% | X
+| org.grails.orm.hibernate.query.HibernatePagedResultList | 91.67% | X
+| org.grails.orm.hibernate.support.ClosureEventListener | 91.99% | X
+| org.grails.orm.hibernate.cfg.domainbinding.binder.PropertyBinder | 92.00% | X
+| org.grails.orm.hibernate.dirty.GrailsEntityDirtinessStrategy | 92.02% | X
+| org.grails.orm.hibernate.cfg.domainbinding.util.GrailsEnumType | 92.50% | X
+| org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateMappingBuilder | 92.54% | X
+| org.grails.orm.hibernate.cfg.domainbinding.util.UniqueNameGenerator | 92.68% | X
+| org.grails.orm.hibernate.cfg.domainbinding.collectionType.CollectionType | 92.68% | X
+| org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyProperty | 92.81% | X
+| org.grails.orm.hibernate.support.HibernateRuntimeUtils | 92.89% | X
+| org.grails.orm.hibernate.cfg.domainbinding.binder.EnumTypeBinder | 92.89% | X
+| org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentEntity | 93.02% | X
+| org.grails.orm.hibernate.HibernateGormEnhancer | 93.24% | X
+| org.grails.orm.hibernate.HibernateGormInstanceApi._delete_closure1 | 93.33% | X
+| org.grails.orm.hibernate.connections.HibernateConnectionSourceSettings.HibernateSettings | 93.53% | X
+| org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateAssociation | 93.65% |
+| org.grails.orm.hibernate.query.HibernateQuery | 93.76% |
+| org.grails.orm.hibernate.cfg.NaturalId | 94.00% |
+| org.grails.orm.hibernate.cfg.domainbinding.secondpass.UnidirectionalOneToManyBinder | 94.34% |
+| org.grails.orm.hibernate.cfg.domainbinding.secondpass.MapSecondPassBinder | 94.74% |
+| org.grails.orm.hibernate.cfg.domainbinding.generator.GrailsSequenceGeneratorEnum | 94.83% |
+| org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity | 94.88% |
+| org.grails.orm.hibernate.dirty.GrailsEntityDirtinessStrategy._findDirty_closure1 | 94.96% |
+| org.grails.orm.hibernate.proxy.GroovyProxyInterceptorLogic | 95.00% |
+| org.grails.orm.hibernate.HibernateGormInstanceApi._performPersist_closure5 | 95.24% |
+| org.grails.orm.hibernate.multitenancy.MultiTenantEventListener | 95.28% |
+| org.grails.orm.hibernate.cfg.domainbinding.binder.CompositeIdentifierToManyToOneBinder | 95.30% |
+| org.grails.orm.hibernate.cfg.domainbinding.binder.GrailsDomainBinder | 95.63% |
+| org.grails.orm.hibernate.query.HqlQueryContext | 95.69% |
+| org.grails.orm.hibernate.compiler.HibernateEntityTransformation.new GroovyObject() {...} | 95.83% |
+| org.grails.orm.hibernate.HibernateGormValidationApi._validate_closure1 | 95.89% |
+| org.grails.orm.hibernate.query.HibernateQueryExecutor | 95.90% |
+| org.grails.orm.hibernate.cfg.ColumnConfig._getIndexAsMap_closure2 | 96.05% |
+| org.grails.orm.hibernate.HibernateGormValidationApi | 96.17% |
+| org.grails.orm.hibernate.cfg.domainbinding.binder.ComponentBinder | 96.32% |
+| org.grails.orm.hibernate.cfg.domainbinding.util.NamingStrategyWrapper | 96.33% |
+| org.grails.orm.hibernate.cfg.domainbinding.util.CascadeBehaviorFetcher | 96.50% |
+| org.grails.orm.hibernate.HibernateGormInstanceApi._performMerge_closure4 | 96.55% |
+| org.grails.orm.hibernate.query.HqlListQueryBuilder | 96.55% |
+| org.grails.orm.hibernate.GrailsHibernateTransactionManager | 96.84% |
+| org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateMappingFactory | 97.03% |
+| org.grails.orm.hibernate.cfg.IdentityEnumType.BidiEnumMap | 97.14% |
+| org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateOneToOneProperty | 97.18% |
+| org.grails.orm.hibernate.connections.HibernateConnectionSourceSettings.HibernateSettings.FlushSettings.FlushMode | 97.25% |
+| org.grails.orm.hibernate.cfg.domainbinding.util.LogCascadeMapping | 97.30% |
+| org.grails.orm.hibernate.cfg.CacheConfig | 97.41% |
+| org.grails.orm.hibernate.cfg.domainbinding.util.MultiTenantFilterBinder | 97.50% |
+| org.grails.orm.hibernate.cfg.CacheConfig.Include | 97.67% |
+| org.grails.orm.hibernate.support.HibernateDatastoreConnectionSourcesRegistrar | 97.71% |
+| org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateMappingBuilder._id_closure1 | 97.73% |
+| grails.gorm.hibernate.mapping.MappingBuilder.ClosureMappingDefinition | 97.78% |
+| org.grails.orm.hibernate.proxy.ByteBuddyGroovyProxyFactory | 97.89% |
+| org.grails.orm.hibernate.cfg.PropertyConfig | 97.97% |
+| org.grails.orm.hibernate.cfg.CacheConfig.Usage | 97.98% |
+| org.grails.orm.hibernate.query.ProjectionPredicate | 98.36% |
+| org.grails.orm.hibernate.query.HibernateQueryArgument | 98.82% |
+| org.grails.orm.hibernate.cfg.domainbinding.util.BasicValueCreator | 98.99% |
+| org.grails.orm.hibernate.connections.HibernateConnectionSourceSettingsBuilder | 99.12% |
+| org.grails.orm.hibernate.cfg.domainbinding.binder.ColumnConfigToColumnBinder | 99.19% |
+| org.grails.orm.hibernate.query.JpaCriteriaQueryCreator | 99.26% |
+| org.grails.orm.hibernate.query.JpaFromProvider | 99.34% |
+| org.grails.orm.hibernate.EventListenerIntegrator | 99.36% |
+| org.grails.orm.hibernate.cfg.HibernateMappingContext | 99.40% |
+| grails.orm.CriteriaMethods | 99.44% |
+| org.grails.orm.hibernate.cfg.domainbinding.util.OrderByClauseBuilder | 99.51% |
+
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/HibernateGormEnhancerSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/HibernateGormEnhancerSpec.groovy
new file mode 100644
index 0000000000..7a6181ec0f
--- /dev/null
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/HibernateGormEnhancerSpec.groovy
@@ -0,0 +1,60 @@
+/*
+ * 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
+
+import grails.gorm.annotation.Entity
+import grails.gorm.specs.HibernateGormDatastoreSpec
+import org.grails.datastore.gorm.GormEnhancer
+import org.grails.datastore.mapping.core.connections.ConnectionSource
+
+class HibernateGormEnhancerSpec extends HibernateGormDatastoreSpec {
+
+ void setupSpec() {
+ manager.addAllDomainClasses([HGESimple])
+ }
+
+ def "test findStaticApi"() {
+ expect:
+ HibernateGormEnhancer.findStaticApi(HGESimple, ConnectionSource.DEFAULT) != null
+ }
+
+ def "test getStaticApi, getInstanceApi, getValidationApi"() {
+ given:
+ def enhancer = manager.hibernateDatastore.gormEnhancer
+
+ expect:
+ enhancer.getStaticApi(HGESimple, ConnectionSource.DEFAULT) instanceof HibernateGormStaticApi
+ enhancer.getInstanceApi(HGESimple, ConnectionSource.DEFAULT) instanceof HibernateGormInstanceApi
+ enhancer.getValidationApi(HGESimple, ConnectionSource.DEFAULT) instanceof HibernateGormValidationApi
+ }
+
+ def "test deprecated constructor"() {
+ when:
+ def enhancer = new HibernateGormEnhancer(manager.hibernateDatastore, manager.transactionManager)
+
+ then:
+ enhancer != null
+ }
+}
+
+@Entity
+class HGESimple {
+ Long id
+ String name
+}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/HibernateGormInstanceApiSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/HibernateGormInstanceApiSpec.groovy
index 4d91c73ee5..cb529c246b 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/HibernateGormInstanceApiSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/HibernateGormInstanceApiSpec.groovy
@@ -21,13 +21,19 @@ package org.grails.orm.hibernate
import grails.gorm.specs.HibernateGormDatastoreSpec
import grails.gorm.annotation.Entity
import grails.gorm.hibernate.HibernateEntity
+import grails.gorm.transactions.Rollback
+import grails.validation.ValidationException
+import org.hibernate.Hibernate
+import org.hibernate.FlushMode
+import org.grails.orm.hibernate.query.HibernateHqlQuery
class HibernateGormInstanceApiSpec extends HibernateGormDatastoreSpec {
def setupSpec() {
- manager.addAllDomainClasses([PersonInstanceApi, BookInstanceApi, ConstrainedPerson, ConstrainedBook])
+ manager.addAllDomainClasses([PersonInstanceApi, BookInstanceApi, ConstrainedPerson, ConstrainedBook, HGIAuthor, HGIBook])
}
+ @Rollback
def "test save and get"() {
given:
def person = new PersonInstanceApi(name: 'Bob', age: 40)
@@ -47,6 +53,7 @@ class HibernateGormInstanceApiSpec extends HibernateGormDatastoreSpec {
found.age == 40
}
+ @Rollback
def "test delete"() {
given:
def person = new PersonInstanceApi(name: 'Bob', age: 40)
@@ -63,6 +70,32 @@ class HibernateGormInstanceApiSpec extends HibernateGormDatastoreSpec {
PersonInstanceApi.get(id) == null
}
+ @Rollback
+ def "test delete without flush"() {
+ given:
+ def person = new PersonInstanceApi(name: 'Bob', age: 40).save(flush: true)
+ def id = person.id
+
+ when:
+ person.delete()
+
+ then: "Entity is removed from session but still in DB"
+ PersonInstanceApi.get(id) == null
+ getSessionFactory().getCurrentSession().createNativeQuery("select count(*) from person_instance_api where id = :id", Long)
+ .setParameter("id", id)
+ .setHibernateFlushMode(FlushMode.MANUAL)
+ .uniqueResult() == 1L
+
+ when:
+ session.flush()
+
+ then:
+ getSessionFactory().getCurrentSession().createNativeQuery("select count(*) from person_instance_api where id = :id", Long)
+ .setParameter("id", id)
+ .uniqueResult() == 0L
+ }
+
+ @Rollback
def "test isDirty"() {
given:
def person = new PersonInstanceApi(name: 'Bob', age: 40)
@@ -78,6 +111,7 @@ class HibernateGormInstanceApiSpec extends HibernateGormDatastoreSpec {
person.getDirtyPropertyNames() == ['name']
}
+ @Rollback
def "test getPersistentValue"() {
given:
def person = new PersonInstanceApi(name: 'Bob', age: 40)
@@ -90,6 +124,7 @@ class HibernateGormInstanceApiSpec extends HibernateGormDatastoreSpec {
person.getPersistentValue('name') == 'Bob'
}
+ @Rollback
def "test discard"() {
given:
def person = new PersonInstanceApi(name: 'Bob', age: 40)
@@ -109,6 +144,7 @@ class HibernateGormInstanceApiSpec extends HibernateGormDatastoreSpec {
found.name == 'Bob'
}
+ @Rollback
def "test attach and merge"() {
given:
def person = new PersonInstanceApi(name: 'Bob', age: 40)
@@ -133,6 +169,7 @@ class HibernateGormInstanceApiSpec extends HibernateGormDatastoreSpec {
found.name == 'Fred'
}
+ @Rollback
def "merge on new instance assigns id and sets version to 0"() {
given:
def person = new PersonInstanceApi(name: 'Alice', age: 30)
@@ -146,6 +183,7 @@ class HibernateGormInstanceApiSpec extends HibernateGormDatastoreSpec {
merged.version == 0
}
+ @Rollback
def "merge on detached instance keeps id and increments version"() {
given:
def person = new PersonInstanceApi(name: 'Alice', age: 30)
@@ -164,6 +202,7 @@ class HibernateGormInstanceApiSpec extends HibernateGormDatastoreSpec {
PersonInstanceApi.get(originalId).name == 'Alice Updated'
}
+ @Rollback
def "test insert"() {
given:
def person = new PersonInstanceApi(name: 'Joe', age: 25)
@@ -176,6 +215,7 @@ class HibernateGormInstanceApiSpec extends HibernateGormDatastoreSpec {
PersonInstanceApi.get(person.id).name == 'Joe'
}
+ @Rollback
def "test refresh"() {
given:
def person = new PersonInstanceApi(name: 'Bob', age: 40)
@@ -190,10 +230,7 @@ class HibernateGormInstanceApiSpec extends HibernateGormDatastoreSpec {
person.name == 'Bob'
}
- // -------------------------------------------------------------------------
- // lock
- // -------------------------------------------------------------------------
-
+ @Rollback
def "lock acquires a pessimistic write lock on the entity"() {
given:
Long savedId = PersonInstanceApi.withTransaction {
@@ -210,10 +247,7 @@ class HibernateGormInstanceApiSpec extends HibernateGormDatastoreSpec {
noExceptionThrown()
}
- // -------------------------------------------------------------------------
- // save — shouldValidate/deepValidate/shouldFail branches
- // -------------------------------------------------------------------------
-
+ @Rollback
def "save with validate:false skips validation"() {
given:
def person = new ConstrainedPerson(name: '') // blank name violates constraint
@@ -228,6 +262,7 @@ class HibernateGormInstanceApiSpec extends HibernateGormDatastoreSpec {
result.id != null
}
+ @Rollback
def "save with deepValidate:false still runs validator without deep cascade"() {
given:
def person = new ConstrainedPerson(name: 'Alice')
@@ -242,6 +277,7 @@ class HibernateGormInstanceApiSpec extends HibernateGormDatastoreSpec {
result.id != null
}
+ @Rollback
def "save with invalid entity returns null and sets errors when failOnError is false"() {
given:
def person = new ConstrainedPerson(name: '') // blank violates constraint
@@ -257,6 +293,7 @@ class HibernateGormInstanceApiSpec extends HibernateGormDatastoreSpec {
person.errors.fieldErrors.any { it.field == 'name' }
}
+ @Rollback
def "save with invalid entity and failOnError:true throws an exception"() {
given:
def person = new ConstrainedPerson(name: '')
@@ -270,10 +307,7 @@ class HibernateGormInstanceApiSpec extends HibernateGormDatastoreSpec {
thrown(Exception)
}
- // -------------------------------------------------------------------------
- // shouldFlush — autoFlush=false (no flush arg)
- // -------------------------------------------------------------------------
-
+ @Rollback
def "save without flush argument uses autoFlush setting"() {
given: "autoFlush is false by default in the test datastore"
def person = new PersonInstanceApi(name: 'AutoFlushTest', age: 55)
@@ -289,20 +323,17 @@ class HibernateGormInstanceApiSpec extends HibernateGormDatastoreSpec {
PersonInstanceApi.get(person.id)?.name == 'AutoFlushTest'
}
- // -------------------------------------------------------------------------
- // isDirty edge cases
- // -------------------------------------------------------------------------
-
+ @Rollback
def "isDirty returns false for a non-attached (transient) instance"() {
given:
def person = new PersonInstanceApi(name: 'Transient', age: 10)
- // not saved — no EntityEntry in the session
expect:
!person.isDirty()
!person.isDirty('name')
}
+ @Rollback
def "getDirtyPropertyNames returns empty list for a non-attached instance"() {
given:
def person = new PersonInstanceApi(name: 'Ghost', age: 99)
@@ -311,10 +342,7 @@ class HibernateGormInstanceApiSpec extends HibernateGormDatastoreSpec {
person.getDirtyPropertyNames() == []
}
- // -------------------------------------------------------------------------
- // getPersistentValue edge cases
- // -------------------------------------------------------------------------
-
+ @Rollback
def "getPersistentValue returns null for an unknown field name"() {
given:
def person = new PersonInstanceApi(name: 'Bob', age: 40)
@@ -324,80 +352,73 @@ class HibernateGormInstanceApiSpec extends HibernateGormDatastoreSpec {
person.getPersistentValue('nonExistentField') == null
}
+ @Rollback
def "getPersistentValue returns null for a non-attached instance"() {
given:
def person = new PersonInstanceApi(name: 'Detached', age: 5)
- // not saved
expect:
person.getPersistentValue('name') == null
}
- // -------------------------------------------------------------------------
- // autoRetrieveAssociations — sub-branches via BookInstanceApi
- // -------------------------------------------------------------------------
-
- def "save book with null author skips association retrieval (null propValue branch)"() {
+ @Rollback
+ def "save book with null author skips association retrieval"() {
given:
- def book = new BookInstanceApi(title: 'Orphan Book') // no author
+ def book = new HGIBook(title: 'Orphan Book')
when:
- def result = BookInstanceApi.withTransaction {
+ HGIBook.withTransaction {
book.save(flush: true, validate: false)
}
then:
- result != null
- result.id != null
+ book.id != null
}
- def "save book with already-managed author skips re-retrieval (contains branch)"() {
+ @Rollback
+ def "save book with already-managed author skips re-retrieval"() {
given:
- def author = PersonInstanceApi.withTransaction {
- new PersonInstanceApi(name: 'Managed Author', age: 35).save(flush: true, failOnError: true)
+ def author = HGIAuthor.withTransaction {
+ new HGIAuthor(name: 'Managed Author').save(flush: true, failOnError: true)
}
- // author is still in session after save — template.contains returns true
- def book = new BookInstanceApi(title: 'Managed Book', author: author)
+ def book = new HGIBook(title: 'Managed Book', author: author)
when:
- def result = BookInstanceApi.withTransaction {
+ HGIBook.withTransaction {
book.save(flush: true, validate: false)
}
then:
- result != null
- result.id != null
+ book.id != null
}
- def "save book with detached author triggers association re-retrieval (full fetch path)"() {
+ @Rollback
+ def "save book with detached author triggers association re-retrieval"() {
given:
- def author = PersonInstanceApi.withTransaction {
- new PersonInstanceApi(name: 'Detached Author', age: 42).save(flush: true, failOnError: true)
+ def author = new HGIAuthor(name: 'Detached Author')
+ HGIAuthor.withTransaction {
+ author.save(flush: true, failOnError: true)
}
- // Evict the author via the hibernate template so it is no longer in the session
- manager.hibernateDatastore.hibernateTemplate.evict(author)
+ session.clear()
- def book = new BookInstanceApi(title: 'Fetched Book', author: author)
+ def book = new HGIBook(title: 'Fetched Book', author: author)
when:
- def result = BookInstanceApi.withTransaction {
+ HGIBook.withTransaction {
book.save(flush: true, validate: false)
}
then:
- result != null
- result.id != null
- result.author != null
- result.author.name == 'Detached Author'
+ book != null
+ book.id != null
+ book.author != null
+ book.author.id == author.id
}
- // -------------------------------------------------------------------------
- // handleValidationError with ToOne association
- // -------------------------------------------------------------------------
+ @Rollback
def "handleValidationError sets association to read-only"() {
given:
def author = new PersonInstanceApi(name: 'Valid Author', age: 30)
- // Book with title blank is invalid
def book = new ConstrainedBook(title: '', author: author)
when:
@@ -408,69 +429,80 @@ class HibernateGormInstanceApiSpec extends HibernateGormDatastoreSpec {
then:
result == null
book.hasErrors()
- // we can't easily verify the read-only status here without peering into hibernate session
- // but we just want to execute the loop over associations in handleValidationError
}
- // -------------------------------------------------------------------------
- // delete with exception
- // -------------------------------------------------------------------------
-
+ @Rollback
def "delete resets flush mode on exception"() {
given:
def person = new PersonInstanceApi(name: 'Bob', age: 40)
person.save(flush: true)
+ def api = new HibernateGormInstanceApi<PersonInstanceApi>(PersonInstanceApi, manager.hibernateDatastore, Thread.currentThread().contextClassLoader)
+ def mockTemplate = Mock(IHibernateTemplate)
+ api.hibernateTemplate = mockTemplate
+ int callCount = 0
+
when:
- PersonInstanceApi.withTransaction {
- def api = new HibernateGormInstanceApi<PersonInstanceApi>(PersonInstanceApi, manager.hibernateDatastore, Thread.currentThread().contextClassLoader)
- api.hibernateTemplate = new GrailsHibernateTemplate(sessionFactory, manager.hibernateDatastore) {
- @Override
- def <T> T execute(Closure<T> action) throws org.springframework.dao.DataAccessException {
- throw new org.springframework.dao.InvalidDataAccessApiUsageException("Simulated exception")
- }
- }
- api.delete(person, [flush: true])
- }
+ api.delete(person, [flush: true])
then:
+ (1.._) * mockTemplate.execute(_) >> { args ->
+ callCount++
+ if (callCount == 1) {
+ throw new org.springframework.dao.InvalidDataAccessApiUsageException("Simulated exception")
+ }
+ }
thrown(org.springframework.dao.InvalidDataAccessApiUsageException)
}
- // -------------------------------------------------------------------------
- // autoRetrieveAssociations
- // -------------------------------------------------------------------------
-
- def "autoRetrieveAssociations catches InvalidPropertyException"() {
+ @Rollback
+ def "reconcileCollections replaces stale PersistentCollection"() {
given:
- def author = new PersonInstanceApi(name: 'Detached Author', age: 42)
- author.id = 999L // detached
- def book = new BookInstanceApi(title: 'Fetched Book', author: author)
-
- when:
- BookInstanceApi.withTransaction {
- def api = new HibernateGormInstanceApi<BookInstanceApi>(BookInstanceApi, manager.hibernateDatastore, Thread.currentThread().contextClassLoader)
- def mockDatastore = Mock(org.grails.datastore.mapping.core.Datastore)
- def mockContext = Mock(org.grails.datastore.mapping.model.MappingContext)
- def mockReflector = Mock(org.grails.datastore.mapping.reflect.EntityReflector)
-
- mockDatastore.getMappingContext() >> mockContext
- mockContext.getEntityReflector(_) >> mockReflector
- mockReflector.getProperty(book, "author") >> author
- mockReflector.getProperty(author, "id") >> { throw new org.springframework.beans.InvalidPropertyException(PersonInstanceApi, "id", "simulated") }
-
- def method = api.getClass().getDeclaredMethod("autoRetrieveAssociations", org.grails.datastore.mapping.core.Datastore, org.grails.datastore.mapping.model.PersistentEntity, Object)
- method.setAccessible(true)
- method.invoke(api, mockDatastore, datastore.mappingContext.getPersistentEntity(BookInstanceApi.name), book)
+ def author = new HGIAuthor(name: 'Author').save(flush: true)
+ new HGIBook(title: 'Book', author: author).save(flush: true)
+ session.clear()
+
+ def loadedAuthor = HGIAuthor.get(author.id)
+ assert loadedAuthor.books.size() == 1
+ session.clear()
+
+ when: "merging the detached entity"
+ HGIAuthor.withTransaction {
+ loadedAuthor.save(flush: true)
}
-
+
then:
noExceptionThrown()
}
+
+ @Rollback
+ def "test prepareHqlQuery and executeUpdate via HibernateGormStaticApi"() {
+ given:
+ def staticApi = new HibernateGormStaticApi<>(PersonInstanceApi, datastore, [], Thread.currentThread().contextClassLoader, transactionManager)
+
+ when: "Calling prepareHqlQuery (protected, accessible in Groovy test)"
+ def query = staticApi.prepareHqlQuery("from PersonInstanceApi where name = 'Bob'", false, false, [:], [], [:])
+
+ then:
+ query != null
+ query instanceof HibernateHqlQuery
+
+ when: "Using doListInternal (protected)"
+ def results = staticApi.doListInternal("from PersonInstanceApi where name = 'Bob'", [:], [], [:], false)
+
+ then:
+ results != null
+
+ when: "Executing an update through the static API"
+ int updated = staticApi.executeUpdate("delete from PersonInstanceApi where name = 'NonExistent'", [:], [:])
+
+ then:
+ updated == 0
+ }
}
@Entity
-class ConstrainedBook implements HibernateEntity<ConstrainedBook> {
+class ConstrainedBook {
String title
static belongsTo = [author: PersonInstanceApi]
static constraints = {
@@ -479,21 +511,35 @@ class ConstrainedBook implements HibernateEntity<ConstrainedBook> {
}
@Entity
-class PersonInstanceApi implements HibernateEntity<PersonInstanceApi> {
+class PersonInstanceApi {
String name
Integer age
}
@Entity
-class BookInstanceApi implements HibernateEntity<BookInstanceApi> {
+class BookInstanceApi {
String title
+ PersonInstanceApi author
static belongsTo = [author: PersonInstanceApi]
}
@Entity
-class ConstrainedPerson implements HibernateEntity<ConstrainedPerson> {
+class ConstrainedPerson {
String name
static constraints = {
name blank: false, maxSize: 100
}
}
+
+@Entity
+class HGIAuthor implements HibernateEntity<HGIAuthor> {
+ String name
+ static hasMany = [books: HGIBook]
+}
+
+@Entity
+class HGIBook implements HibernateEntity<HGIBook> {
+ String title
+ HGIAuthor author
+ static belongsTo = [author: HGIAuthor]
+}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/generator/GrailsSequenceStyleGeneratorSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/generator/GrailsSequenceStyleGeneratorSpec.groovy
new file mode 100644
index 0000000000..2adc4878f9
--- /dev/null
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/generator/GrailsSequenceStyleGeneratorSpec.groovy
@@ -0,0 +1,140 @@
+/*
+ * 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.generator
+
+import grails.gorm.annotation.Entity
+import grails.gorm.specs.HibernateGormDatastoreSpec
+import org.grails.orm.hibernate.cfg.HibernateSimpleIdentity
+import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity
+import org.hibernate.boot.model.relational.Database
+import org.hibernate.boot.model.relational.SqlStringGenerationContext
+import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment
+import org.hibernate.generator.GeneratorCreationContext
+import org.hibernate.id.enhanced.DatabaseStructure
+import org.hibernate.mapping.RootClass
+
+class GrailsSequenceStyleGeneratorSpec extends HibernateGormDatastoreSpec {
+
+ static DatabaseStructure staticMockStructure
+
+ static class TestGrailsSequenceStyleGenerator extends GrailsSequenceStyleGenerator {
+ Properties capturedProps
+ Database capturedDatabase
+ SqlStringGenerationContext capturedSqlContext
+
+ TestGrailsSequenceStyleGenerator(GeneratorCreationContext context, HibernateSimpleIdentity mappedId, JdbcEnvironment jdbcEnvironment) {
+ super(context, mappedId, jdbcEnvironment)
+ }
+
+ @Override
+ void configure(GeneratorCreationContext context, Properties params) {
+ this.capturedProps = params
+ }
+
+ @Override
+ void registerExportables(Database database) {
+ this.capturedDatabase = database
+ }
+
+ @Override
+ void initialize(SqlStringGenerationContext context) {
+ this.capturedSqlContext = context
+ }
+
+ @Override
+ DatabaseStructure getDatabaseStructure() {
+ return staticMockStructure
+ }
+ }
+
+ void setupSpec() {
+ manager.addAllDomainClasses([
+ SequenceStyleGeneratorSpecEntity
+ ])
+ }
+
+ def "test constructor logic with default parameters"() {
+ given:
+ def binder = getGrailsDomainBinder()
+ def context = Mock(GeneratorCreationContext)
+ def persistentEntity = getPersistentEntity(SequenceStyleGeneratorSpecEntity) as GrailsHibernatePersistentEntity
+ def rootClass = new RootClass(binder.getMetadataBuildingContext())
+ persistentEntity.setPersistentClass(rootClass)
+
+ def database = binder.getMetadataBuildingContext().getMetadataCollector().getDatabase()
+ def jdbcEnvironment = binder.getJdbcEnvironment()
+ def mappedId = Mock(HibernateSimpleIdentity)
+ def props = new Properties()
+
+ context.getDatabase() >> database
+ context.getServiceRegistry() >> binder.getMetadataBuildingContext().getBuildingOptions().getServiceRegistry()
+ mappedId.getProperties() >> props
+
+ when:
+ def generator = new TestGrailsSequenceStyleGenerator(context, mappedId, jdbcEnvironment)
+
+ then:
+ generator.capturedProps.getProperty("increment_size") == "50"
+ generator.capturedProps.getProperty("optimizer") == "pooled-lo"
+ }
+
+ def "test constructor with null mappedId and null jdbcEnvironment"() {
+ given:
+ def binder = getGrailsDomainBinder()
+ def context = Mock(GeneratorCreationContext)
+
+ context.getServiceRegistry() >> binder.getMetadataBuildingContext().getBuildingOptions().getServiceRegistry()
+
+ when:
+ def generator = new TestGrailsSequenceStyleGenerator(context, null, null)
+
+ then:
+ generator.capturedProps.getProperty("increment_size") == "50"
+ generator.capturedProps.getProperty("optimizer") == "pooled-lo"
+ generator.capturedDatabase == null
+ }
+
+ def "test constructor with database structure and physical names"() {
+ given:
+ def binder = getGrailsDomainBinder()
+ def context = Mock(GeneratorCreationContext)
+ def database = binder.getMetadataBuildingContext().getMetadataCollector().getDatabase()
+ def jdbcEnvironment = binder.getJdbcEnvironment()
+ def structure = Mock(DatabaseStructure)
+ staticMockStructure = structure
+
+ context.getDatabase() >> database
+ context.getServiceRegistry() >> binder.getMetadataBuildingContext().getBuildingOptions().getServiceRegistry()
+
+ when:
+ def generator = new TestGrailsSequenceStyleGenerator(context, null, jdbcEnvironment)
+
+ then:
+ generator.capturedDatabase == database
+ generator.capturedSqlContext != null
+
+ cleanup:
+ staticMockStructure = null
+ }
+}
+
+@Entity
+class SequenceStyleGeneratorSpecEntity {
+ Long id
+}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/generator/GrailsTableGeneratorSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/generator/GrailsTableGeneratorSpec.groovy
new file mode 100644
index 0000000000..e20626e8aa
--- /dev/null
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/generator/GrailsTableGeneratorSpec.groovy
@@ -0,0 +1,130 @@
+/*
+ * 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.generator
+
+import grails.gorm.annotation.Entity
+import grails.gorm.specs.HibernateGormDatastoreSpec
+import org.grails.orm.hibernate.cfg.HibernateSimpleIdentity
+import org.hibernate.id.enhanced.TableGenerator
+import org.hibernate.generator.GeneratorCreationContext
+import org.hibernate.mapping.Property
+import org.hibernate.mapping.Table
+import org.hibernate.boot.model.relational.Database
+import org.hibernate.boot.model.relational.Namespace
+import org.hibernate.boot.model.naming.Identifier
+
+class GrailsTableGeneratorSpec extends HibernateGormDatastoreSpec {
+
+ void setupSpec() {
+ manager.addAllDomainClasses([
+ TableGeneratorSpecEntity
+ ])
+ }
+
+ def "test constructor with null mappedId"() {
+ given:
+ def binder = getGrailsDomainBinder()
+ def context = Mock(GeneratorCreationContext)
+ def property = Mock(Property)
+
+ context.getProperty() >> property
+ property.getName() >> "id"
+ context.getDatabase() >> binder.getMetadataBuildingContext().getMetadataCollector().getDatabase()
+ context.getServiceRegistry() >> binder.getMetadataBuildingContext().getBuildingOptions().getServiceRegistry()
+
+ when:
+ def generator = new GrailsTableGenerator(context, null, binder.getJdbcEnvironment())
+
+ then:
+ generator.getSegmentValue() == "default.id"
+ generator.getIncrementSize() == 50
+ }
+
+ def "test constructor with existing segment value and parameters"() {
+ given:
+ def binder = getGrailsDomainBinder()
+ def context = Mock(GeneratorCreationContext)
+ def property = Mock(Property)
+ def mappedId = Mock(HibernateSimpleIdentity)
+ def props = new Properties()
+ props.put(TableGenerator.SEGMENT_VALUE_PARAM, "custom_segment")
+ props.put(TableGenerator.INCREMENT_PARAM, "100")
+ props.put(TableGenerator.OPT_PARAM, "none")
+
+ context.getProperty() >> property
+ property.getName() >> "id"
+ context.getDatabase() >> binder.getMetadataBuildingContext().getMetadataCollector().getDatabase()
+ context.getServiceRegistry() >> binder.getMetadataBuildingContext().getBuildingOptions().getServiceRegistry()
+ mappedId.getProperties() >> props
+
+ when:
+ def generator = new GrailsTableGenerator(context, mappedId, binder.getJdbcEnvironment())
+
+ then:
+ generator.getSegmentValue() == "custom_segment"
+ generator.getIncrementSize() == 100
+ }
+
+ def "test constructor with mappedId but null name"() {
+ given:
+ def binder = getGrailsDomainBinder()
+ def context = Mock(GeneratorCreationContext)
+ def property = Mock(Property)
+ def mappedId = Mock(HibernateSimpleIdentity)
+
+ context.getProperty() >> property
+ property.getName() >> "id"
+ context.getDatabase() >> binder.getMetadataBuildingContext().getMetadataCollector().getDatabase()
+ context.getServiceRegistry() >> binder.getMetadataBuildingContext().getBuildingOptions().getServiceRegistry()
+ mappedId.getProperties() >> new Properties()
+ mappedId.getName() >> null
+
+ when:
+ def generator = new GrailsTableGenerator(context, mappedId, binder.getJdbcEnvironment())
+
+ then:
+ generator.getSegmentValue() == "default.id"
+ }
+
+ def "test constructor with mappedId name"() {
+ given:
+ def binder = getGrailsDomainBinder()
+ def context = Mock(GeneratorCreationContext)
+ def property = Mock(Property)
+ def mappedId = Mock(HibernateSimpleIdentity)
+
+ context.getProperty() >> property
+ property.getName() >> "id"
+ context.getDatabase() >> binder.getMetadataBuildingContext().getMetadataCollector().getDatabase()
+ context.getServiceRegistry() >> binder.getMetadataBuildingContext().getBuildingOptions().getServiceRegistry()
+ mappedId.getProperties() >> new Properties()
+ mappedId.getName() >> "myEntity"
+
+ when:
+ def generator = new GrailsTableGenerator(context, mappedId, binder.getJdbcEnvironment())
+
+ then:
+ generator.getSegmentValue() == "myEntity.id"
+ }
+}
+
+@Entity
+class TableGeneratorSpecEntity {
+ Long id
+}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernatePersistentEntitySpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernatePersistentEntitySpec.groovy
new file mode 100644
index 0000000000..b62848fa3e
--- /dev/null
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/hibernate/HibernatePersistentEntitySpec.groovy
@@ -0,0 +1,136 @@
+/*
+ * 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.hibernate
+
+import grails.gorm.annotation.Entity
+import grails.gorm.specs.HibernateGormDatastoreSpec
+import org.grails.orm.hibernate.cfg.HibernateSimpleIdentity
+import org.grails.orm.hibernate.cfg.Mapping
+import org.hibernate.MappingException
+import org.hibernate.mapping.RootClass
+
+class HibernatePersistentEntitySpec extends HibernateGormDatastoreSpec {
+
+ void setupSpec() {
+ manager.addAllDomainClasses([HPESimple, HPEComposite])
+ }
+
+ def "getIdentity returns null if identity is not HibernatePersistentProperty"() {
+ given:
+ def entity = getPersistentEntity(HPESimple) as HibernatePersistentEntity
+ // Manual override of identity to a non-Hibernate type
+ def originalIdentity = entity.identity
+ entity.identity = Mock(org.grails.datastore.mapping.model.PersistentProperty)
+
+ expect:
+ entity.getIdentity() == null
+
+ cleanup:
+ entity.identity = originalIdentity
+ }
+
+ def "getCompositeIdentity returns empty array if no composite identity"() {
+ given:
+ def entity = getPersistentEntity(HPESimple) as HibernatePersistentEntity
+
+ expect:
+ entity.getCompositeIdentity().length == 0
+ }
+
+ def "getIdentityProperty returns composite property if length > 1"() {
+ given:
+ def entity = getPersistentEntity(HPEComposite) as HibernatePersistentEntity
+
+ when:
+ def idProp = entity.getIdentityProperty()
+
+ then:
+ idProp instanceof HibernateCompositeIdentityProperty
+ }
+
+ def "getIdentityProperty throws MappingException if no identity"() {
+ given: "An entity created manually without registration"
+ def entity = new HibernatePersistentEntity(Object, getMappingContext())
+
+ when:
+ entity.getIdentityProperty()
+
+ then:
+ thrown(MappingException)
+ }
+
+ def "getIdentityGeneratorName handles tablePerConcreteClass"() {
+ given:
+ def entity = getPersistentEntity(HPESimple) as HibernatePersistentEntity
+ def identity = entity.getHibernateIdentity() as HibernateSimpleIdentity
+ def mapping = entity.getHibernateMappedForm()
+
+ // Force generator to 'native' to test the useSequence branch
+ def originalGenerator = identity.getGenerator()
+ identity.setGenerator('native')
+
+ def originalVal = mapping.isTablePerConcreteClass()
+ mapping.setTablePerConcreteClass(true)
+
+ expect:
+ // When generator is 'native' and tablePerConcreteClass is true,
+ // determineGeneratorName(true) returns 'sequence-identity'.
+ entity.getIdentityGeneratorName() == "sequence-identity"
+
+ cleanup:
+ mapping.setTablePerConcreteClass(originalVal)
+ identity.setGenerator(originalGenerator)
+ }
+
+ def "getIdentityGeneratorName throws MappingException for composite identity"() {
+ given:
+ def entity = getPersistentEntity(HPEComposite) as HibernatePersistentEntity
+
+ when:
+ entity.getIdentityGeneratorName()
+
+ then:
+ thrown(MappingException)
+ }
+
+ def "getRootClass returns root class from persistent class"() {
+ given:
+ def entity = getPersistentEntity(HPESimple) as HibernatePersistentEntity
+ def rootClass = new RootClass(getGrailsDomainBinder().getMetadataBuildingContext())
+ entity.setPersistentClass(rootClass)
+
+ expect:
+ entity.getRootClass().is(rootClass)
+ }
+}
+
+@Entity
+class HPESimple {
+ Long id
+ String name
+}
+
+@Entity
+class HPEComposite {
+ String a
+ String b
+ static mapping = {
+ id composite: ['a', 'b']
+ }
+}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/dirty/GrailsEntityDirtinessStrategySpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/dirty/GrailsEntityDirtinessStrategySpec.groovy
new file mode 100644
index 0000000000..6a0ef0f65d
--- /dev/null
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/dirty/GrailsEntityDirtinessStrategySpec.groovy
@@ -0,0 +1,169 @@
+/*
+ * 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.dirty
+
+import grails.gorm.annotation.Entity
+import grails.gorm.hibernate.HibernateEntity
+import grails.gorm.specs.HibernateGormDatastoreSpec
+import org.grails.datastore.mapping.dirty.checking.DirtyCheckable
+import org.hibernate.CustomEntityDirtinessStrategy
+import org.hibernate.Session
+import org.hibernate.engine.spi.SessionImplementor
+import org.hibernate.persister.entity.EntityPersister
+
+class GrailsEntityDirtinessStrategySpec extends HibernateGormDatastoreSpec {
+
+ void setupSpec() {
+ manager.addAllDomainClasses([DSBook, DSEmbeddedEntity])
+ }
+
+ def "canDirtyCheck returns true for DirtyCheckable"() {
+ given:
+ def strategy = new GrailsEntityDirtinessStrategy()
+ def book = new DSBook()
+ def nonDirty = "string"
+
+ expect:
+ strategy.canDirtyCheck(book, null, null)
+ !strategy.canDirtyCheck(nonDirty, null, null)
+ }
+
+ def "isDirty returns true if not in session or has changes"() {
+ given:
+ def strategy = new GrailsEntityDirtinessStrategy()
+ def nativeSession = sessionFactory.getCurrentSession()
+ def book = new DSBook(title: "T1").save(flush: true)
+
+ expect:
+ !strategy.isDirty(book, null, nativeSession)
+
+ when:
+ book.title = "T2"
+
+ then:
+ strategy.isDirty(book, null, nativeSession)
+
+ when:
+ nativeSession.evict(book)
+
+ then:
+ strategy.isDirty(book, null, nativeSession)
+ }
+
+ def "findDirty handles various attribute types and statuses"() {
+ given:
+ def strategy = new GrailsEntityDirtinessStrategy()
+ def nativeSession = sessionFactory.getCurrentSession()
+ def sessionImplementor = nativeSession as SessionImplementor
+ def persister = sessionImplementor.getSessionFactory().getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor(DSBook) as EntityPersister
+ def context = Mock(CustomEntityDirtinessStrategy.DirtyCheckContext)
+
+ def book = new DSBook(title: "B1", lastUpdated: new Date())
+ // book is NOT in session yet, so status will be null
+
+ when:
+ strategy.findDirty(book, persister, nativeSession, context)
+
+ then:
+ 1 * context.doDirtyChecking(_) >> { args ->
+ def checker = args[0] as CustomEntityDirtinessStrategy.AttributeChecker
+ def info = Mock(CustomEntityDirtinessStrategy.AttributeInformation)
+ assert checker.isDirty(info) == true // null status means always dirty
+ }
+
+ when:
+ book.save(flush: true)
+ book.title = "B2" // make it dirty
+ strategy.findDirty(book, persister, nativeSession, context)
+
+ then:
+ 1 * context.doDirtyChecking(_) >> { args ->
+ def checker = args[0] as CustomEntityDirtinessStrategy.AttributeChecker
+
+ def infoTitle = Mock(CustomEntityDirtinessStrategy.AttributeInformation)
+ infoTitle.getName() >> "title"
+ assert checker.isDirty(infoTitle) == true
+
+ def infoOther = Mock(CustomEntityDirtinessStrategy.AttributeInformation)
+ infoOther.getName() >> "other"
+ assert checker.isDirty(infoOther) == false
+ }
+ }
+
+ def "findDirty handles lastUpdated property"() {
+ given:
+ def strategy = new GrailsEntityDirtinessStrategy()
+ def nativeSession = sessionFactory.getCurrentSession()
+ def sessionImplementor = nativeSession as SessionImplementor
+ def persister = sessionImplementor.getSessionFactory().getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor(DSBook) as EntityPersister
+ def context = Mock(CustomEntityDirtinessStrategy.DirtyCheckContext)
+
+ def book = new DSBook(title: "B1").save(flush: true)
+
+ when:
+ book.title = "B2" // mark as changed
+ strategy.findDirty(book, persister, nativeSession, context)
+
+ then:
+ 1 * context.doDirtyChecking(_) >> { args ->
+ def checker = args[0] as CustomEntityDirtinessStrategy.AttributeChecker
+ def info = Mock(CustomEntityDirtinessStrategy.AttributeInformation)
+ info.getName() >> "lastUpdated"
+ assert checker.isDirty(info) == true
+ }
+ }
+
+ def "resetDirty tracks changes"() {
+ given:
+ def strategy = new GrailsEntityDirtinessStrategy()
+ def nativeSession = sessionFactory.getCurrentSession()
+ def book = new DSBook(title: "B1")
+ book.title = "B2"
+ assert book.hasChanged()
+
+ when:
+ strategy.resetDirty(book, null, nativeSession)
+
+ then:
+ !book.hasChanged()
+ }
+}
+
+@Entity
+class DSBook implements HibernateEntity<DSBook> {
+ Long id
+ String title
+ Date lastUpdated
+ DSEmbeddedEntity embeddedProp
+ static embedded = ['embeddedProp']
+ static constraints = {
+ title nullable: true
+ lastUpdated nullable: true
+ embeddedProp nullable: true
+ }
+}
+
+@Entity
+class DSEmbeddedEntity implements HibernateEntity<DSEmbeddedEntity> {
+ Long id
+ String name
+ static constraints = {
+ name nullable: true
+ }
+}