You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@grails.apache.org by jd...@apache.org on 2026/10/21 14:09:55 UTC
(grails-core) branch 8.0.x updated (af8cea578d -> 993c048ea6)
This is an automated email from the ASF dual-hosted git repository.
jdaugherty pushed a change to branch 8.0.x
in repository https://gitbox.apache.org/repos/asf/grails-core.git
from af8cea578d Merge pull request #16705 from apache/dependabot/github_actions/codeql-action-9159e49961
add 1978dab17d Restrict lookups by id to the current tenant
add 13304e6789 Convert ids and initialize withoutId proxies as the lookup by key does
add 9d47b98435 Cover lookups by id of an entity mapped with a composite id
add 34c879e803 Return held instances of the current tenant from lookups by id
add b36c2205f5 Stop SchemaBasedMultiTenancySpec from dropping the config database
add e8d235330a Use the 8.0.x cleanup of SchemaBasedMultiTenancySpec
add 70743888e0 Tell withoutId apart from the tenant id DEFAULT
add 14eaf0ce23 Run without a tenant only inside Tenants.withoutId
add d1db00ec21 Merge pull request #16703 from apache/fix/gorm-without-tenant-marker-7.0.x
add 89208a56bf Merge branch '7.0.x' into fix/multi-tenant-get-by-id
add 860f5dba9d Drop the isWithoutId feature that PartitionedMultiTenancyWithoutIdSpec covers
add 0a22d3033f Merge pull request #16515 from apache/fix/multi-tenant-get-by-id
add 555db8cbee [skip tests] Merge branch '7.0.x' into 7.1.x
add 145e0390d0 [skip tests] Merge branch '7.1.x' into 7.2.x
new 993c048ea6 [skip tests] Merge branch '7.2.x' into 8.0.x
The 1 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:
.../MongoLookupByIdMultiTenancySpec.groovy | 348 +++++++++++++++++++
.../asciidoc/multiTenancy/multiTenancyModes.adoc | 10 +
.../tests/multitenancy/MultiTenancySpec.groovy | 38 +++
.../partitioned/PartitionedLookupByIdSpec.groovy | 367 +++++++++++++++++++++
.../org/grails/datastore/gorm/GormStaticApi.groovy | 267 +++++++++++++++
.../src/en/guide/upgrading/upgrading80x.adoc | 9 +
6 files changed, 1039 insertions(+)
create mode 100644 grails-data-mongodb/core/src/test/groovy/org/grails/datastore/gorm/mongo/multitenancy/MongoLookupByIdMultiTenancySpec.groovy
create mode 100644 grails-datamapping-core-test/src/test/groovy/grails/gorm/multitenancy/partitioned/PartitionedLookupByIdSpec.groovy
(grails-core) 01/01: [skip tests] Merge branch '7.2.x' into 8.0.x
Posted by jd...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jdaugherty pushed a commit to branch 8.0.x
in repository https://gitbox.apache.org/repos/asf/grails-core.git
commit 993c048ea637d339c8db5c0d1ef2231dee2429e6
Merge: af8cea578d 145e0390d0
Author: James Daugherty <jd...@jdresources.net>
AuthorDate: Wed Oct 21 10:07:37 2026 -0400
[skip tests] Merge branch '7.2.x' into 8.0.x
# Conflicts:
# grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/query/AbstractHibernateCriteriaBuilder.java
# grails-data-hibernate5/docs/src/docs/asciidoc/multiTenancy/discriminatorMultiTenancy.adoc
# grails-data-mongodb/docs/src/docs/asciidoc/multiTenancy/multiTenancyModes.adoc
# grails-datamapping-core-test/src/test/groovy/grails/gorm/multitenancy/withoutid/PartitionedMultiTenancyWithoutIdSpec.groovy
# grails-datamapping-core/src/main/groovy/grails/gorm/multitenancy/Tenants.groovy
# grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/GormStaticApi.groovy
# grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/multitenancy/MultiTenantEventListener.java
# grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/services/DefaultTenantService.groovy
# grails-doc/src/en/guide/upgrading/upgrading60x.adoc
.../MongoLookupByIdMultiTenancySpec.groovy | 348 +++++++++++++++++++
.../asciidoc/multiTenancy/multiTenancyModes.adoc | 10 +
.../tests/multitenancy/MultiTenancySpec.groovy | 38 +++
.../partitioned/PartitionedLookupByIdSpec.groovy | 367 +++++++++++++++++++++
.../org/grails/datastore/gorm/GormStaticApi.groovy | 267 +++++++++++++++
.../src/en/guide/upgrading/upgrading80x.adoc | 9 +
6 files changed, 1039 insertions(+)
diff --cc grails-data-mongodb/docs/src/docs/asciidoc/multiTenancy/multiTenancyModes.adoc
index 012a341f4c,2ea37c5e6c..49cb1afe12
--- a/grails-data-mongodb/docs/src/docs/asciidoc/multiTenancy/multiTenancyModes.adoc
+++ b/grails-data-mongodb/docs/src/docs/asciidoc/multiTenancy/multiTenancyModes.adoc
@@@ -107,7 -107,17 +107,17 @@@ import static com.mongodb.client.model.
Book.find(eq("title", "The Stand")).first()
----
+ Lookups by id are restricted to the current tenant as well. `get`, `read`, `exists` and `getAll` find no document of another tenant, and the proxy returned by `load` fails to initialize for one, as it does for an id that does not exist:
+
+ [source,groovy]
+ ----
+ // null if the book belongs to another tenant
+ Book.get(id)
+ ----
+
-Without a current tenant a lookup by id throws `TenantNotFoundException`, as a query does. Inside `Tenants.withoutId` a lookup by id is not restricted to a tenant, and neither is a proxy returned by `load` that is initialized there. A tenant id of `DEFAULT` restricts a lookup by id to that tenant as it restricts a query.
++Without a current tenant a lookup by id throws `TenantNotFoundException`, as a query does. Inside `Tenants.withoutId` a lookup by id is not restricted to a tenant, and neither is a proxy returned by `load` that is initialized there. A tenant id of `default` restricts a lookup by id to that tenant as it restricts a query.
+
-When an instance is saved, GORM sets its `tenantId` to the current tenant id, also when that tenant id is `DEFAULT`, the name of the default connection source. Only inside `Tenants.withoutId` or a method annotated with `@WithoutTenant` does an instance keep the `tenantId` that is set on it.
+When an instance is saved, GORM sets its `tenantId` to the current tenant id, also when that tenant id is `default`, the name of the default connection source. Only inside `Tenants.withoutId` or a method annotated with `@WithoutTenant` does an instance keep the `tenantId` that is set on it.
But this logic bypasses any built into tenant id interception and inclusion:
diff --cc grails-data-neo4j/core/src/test/groovy/grails/gorm/tests/multitenancy/MultiTenancySpec.groovy
index 7c67416898,0000000000..5add2a4822
mode 100644,000000..100644
--- a/grails-data-neo4j/core/src/test/groovy/grails/gorm/tests/multitenancy/MultiTenancySpec.groovy
+++ b/grails-data-neo4j/core/src/test/groovy/grails/gorm/tests/multitenancy/MultiTenancySpec.groovy
@@@ -1,155 -1,0 +1,193 @@@
+/*
+ * 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.multitenancy
+
+import grails.gorm.MultiTenant
+import grails.gorm.annotation.Entity
++import grails.gorm.multitenancy.Tenants
+import grails.neo4j.Neo4jEntity
+import grails.neo4j.Relationship
+import org.grails.datastore.gorm.neo4j.Neo4jDatastore
+import org.grails.datastore.gorm.neo4j.config.Settings
+import org.grails.datastore.mapping.core.Session
+import org.grails.datastore.mapping.multitenancy.AllTenantsResolver
+import org.grails.datastore.mapping.multitenancy.exceptions.TenantNotFoundException
+import org.grails.datastore.mapping.multitenancy.resolvers.SystemPropertyTenantResolver
++import org.springframework.dao.DataIntegrityViolationException
+import spock.lang.AutoCleanup
+import spock.lang.Shared
+import spock.lang.Specification
+
+/**
+ * Created by graemerocher on 19/07/2016.
+ */
+class MultiTenancySpec extends Specification {
+
+ @Shared @AutoCleanup Neo4jDatastore datastore
+
+ void setupSpec() {
+ def tempDir = File.createTempDir()
+ tempDir.deleteOnExit()
+ // No explicit URL: the embedded server then binds a random free port, so this spec cannot
+ // collide with the embedded server of another spec running in a parallel test fork.
+ Map config = [
+ "grails.gorm.multiTenancy.mode" :"DISCRIMINATOR",
+ "grails.gorm.multiTenancy.tenantResolverClass": MyResolver,
+ "grails.neo4j.options.encryptionLevel" :"NONE",
+ (Settings.SETTING_NEO4J_TYPE) : "embedded",
+ (Settings.SETTING_NEO4J_LOCATION) : tempDir
+ ]
+ this.datastore = new Neo4jDatastore(config, getDomainClasses() as Class[])
+ }
+
+ void setup() {
+ System.setProperty(SystemPropertyTenantResolver.PROPERTY_NAME, "")
+ }
+
+ void cleanup() {
+ System.setProperty(SystemPropertyTenantResolver.PROPERTY_NAME, "")
+ }
+
+ void "Test persist and retrieve entities with multi tenancy"() {
+ when:"A tenant id is present"
+ System.setProperty(SystemPropertyTenantResolver.PROPERTY_NAME, "test1")
+
+ then:"the correct tenant is used"
+ CompanyC.count() == 0
+
+ when:"An object is saved"
+ CompanyC.withTransaction {
+ def f = new CompanyC(name: "Foo").save(flush:true)
+ def b = new CompanyC(name: "Bar").save(flush:true)
+ new BusinessPartner(from: f, to: b, value: 1000.0f).save(flush:true)
+ }
+
+
+ then:"The results are correct"
+ CompanyC.count() == 2
+ BusinessPartner.count() == 1
+
+ when:"A cypher query is executed without the tenant id"
+ CompanyC.withNewSession {
+ CompanyC.find("MATCH (p:CompanyC) WHERE p.name=\$name RETURN p", [name:"Foo"])
+ }
+
+ then:"An exception is thrown"
+ thrown(TenantNotFoundException)
+
+ when:"A cypher query is executed without the tenant id"
+ CompanyC result= CompanyC.withNewSession {
+ CompanyC.find("MATCH (p:CompanyC) WHERE p.name=\$name AND p.parent=\$tenantId RETURN p", [name:"Foo"])
+ }
+
+ then:"The entity is found"
+ result != null
+
+
+ when:"The tenant id is switched"
+ System.setProperty(SystemPropertyTenantResolver.PROPERTY_NAME, "test2")
+
+ then:"the correct tenant is used"
+ CompanyC.count() == 0
+ CompanyC.withTenant("test1") { Serializable tenantId, Session s ->
+ assert tenantId
+ assert s
+ CompanyC.count() == 2
+ }
+
+ when:"each tenant is iterated over"
+ Map tenantIds = [:]
+ CompanyC.eachTenant { String tenantId ->
+ tenantIds.put(tenantId, CompanyC.count())
+ }
+
+ then:"The result is correct"
+ tenantIds == [test1:2, test2:0]
+ }
+
++ void "Test lookups by id are restricted to the current tenant"() {
++ given:"an instance of another tenant and one of the current tenant"
++ System.setProperty(SystemPropertyTenantResolver.PROPERTY_NAME, "test1")
++ Serializable otherId = CompanyC.withTransaction { new CompanyC(name: "Other").save(flush: true).id }
++ System.setProperty(SystemPropertyTenantResolver.PROPERTY_NAME, "test2")
++ Serializable ownId = CompanyC.withTransaction { new CompanyC(name: "Own").save(flush: true).id }
++
++ expect:"get, read, exists and getAll find the instance of the current tenant only"
++ CompanyC.withNewSession { CompanyC.get(ownId)?.name } == "Own"
++ CompanyC.withNewSession { CompanyC.read(ownId)?.name } == "Own"
++ CompanyC.withNewSession { CompanyC.exists(ownId) }
++ CompanyC.withNewSession { CompanyC.get(otherId) } == null
++ CompanyC.withNewSession { CompanyC.read(otherId) } == null
++ !CompanyC.withNewSession { CompanyC.exists(otherId) }
++ CompanyC.withNewSession { CompanyC.getAll(otherId, ownId)*.name } == [null, "Own"]
++
++ and:"load initializes a proxy for the instance of the current tenant"
++ CompanyC.withNewSession { CompanyC.load(ownId).name } == "Own"
++
++ and:"inside withoutId a lookup by id is not restricted to a tenant"
++ Tenants.withoutId(datastore) { CompanyC.getAll(otherId, ownId)*.name } == ["Other", "Own"]
++
++ when:"a proxy for an instance of another tenant is used"
++ CompanyC.withNewSession { CompanyC.load(otherId).name }
++
++ then:"it fails to initialize like one for an instance that does not exist"
++ thrown(DataIntegrityViolationException)
++
++ when:"an instance is looked up by id without a tenant"
++ System.setProperty(SystemPropertyTenantResolver.PROPERTY_NAME, "")
++ CompanyC.withNewSession { CompanyC.get(ownId) }
++
++ then:"an exception is thrown"
++ thrown(TenantNotFoundException)
++ }
++
+ List getDomainClasses() {
+ [ CompanyC, BusinessPartner]
+ }
+
+ static class MyResolver extends SystemPropertyTenantResolver implements AllTenantsResolver {
+ @Override
+ Iterable<Serializable> resolveTenantIds() {
+ ['test1','test2']
+ }
+ }
+
+}
+@Entity
+class CompanyC implements Neo4jEntity<CompanyC>, MultiTenant {
+ String name
+ String parent
+
+ static mapping = {
+ tenantId name:'parent'
+ }
+
+}
+
+@Entity
+class BusinessPartner implements Relationship<CompanyC, CompanyC>, MultiTenant<BusinessPartner> {
+ Float value = 0.0
+ String parent
+
+ static mapping = {
+ tenantId name:'parent'
+ }
+
+}
diff --cc grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/GormStaticApi.groovy
index d81e46e93b,5e9cdeedf5..7e8ddbc8cc
--- a/grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/GormStaticApi.groovy
+++ b/grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/GormStaticApi.groovy
@@@ -19,10 -19,16 +19,13 @@@
package org.grails.datastore.gorm
import groovy.transform.CompileDynamic
-import groovy.transform.CompileStatic
-import groovy.transform.TypeCheckingMode
-import org.codehaus.groovy.runtime.InvokerHelper
+import groovy.util.logging.Slf4j
+ import jakarta.persistence.FlushModeType
+import jakarta.persistence.LockModeType
-import org.springframework.beans.PropertyAccessorFactory
-import org.springframework.beans.factory.config.AutowireCapableBeanFactory
+ import org.springframework.core.convert.ConversionFailedException
+ import org.springframework.core.convert.ConversionService
import org.springframework.transaction.PlatformTransactionManager
import org.springframework.transaction.TransactionDefinition
import org.springframework.transaction.support.DefaultTransactionDefinition
@@@ -43,369 -49,633 +46,599 @@@ import org.grails.datastore.mapping.cor
import org.grails.datastore.mapping.core.DatastoreUtils
import org.grails.datastore.mapping.core.Session
import org.grails.datastore.mapping.core.SessionCallback
+ import org.grails.datastore.mapping.core.SessionImplementor
import org.grails.datastore.mapping.core.StatelessDatastore
import org.grails.datastore.mapping.core.connections.ConnectionSource
-import org.grails.datastore.mapping.core.connections.ConnectionSourceSettings
import org.grails.datastore.mapping.core.connections.ConnectionSources
import org.grails.datastore.mapping.core.connections.ConnectionSourcesProvider
+ import org.grails.datastore.mapping.core.impl.PendingInsert
+ import org.grails.datastore.mapping.engine.AssociationQueryExecutor
+import org.grails.datastore.mapping.model.MappingContext
import org.grails.datastore.mapping.model.PersistentEntity
-import org.grails.datastore.mapping.model.PersistentProperty
-import org.grails.datastore.mapping.model.types.Association
import org.grails.datastore.mapping.multitenancy.MultiTenancySettings.MultiTenancyMode
import org.grails.datastore.mapping.multitenancy.MultiTenantCapableDatastore
+ import org.grails.datastore.mapping.query.Query
import org.grails.datastore.mapping.query.api.BuildableCriteria
-import org.grails.datastore.mapping.query.api.Criteria
+import org.grails.datastore.mapping.transactions.TransactionCapableDatastore
/**
- * Static methods of the GORM API.
+ * Static methods for GORM
*
* @author Graeme Rocher
- * @param <D> the entity/domain class
*/
-@CompileStatic
+@CompileDynamic
+@Slf4j
class GormStaticApi<D> extends AbstractGormApi<D> implements GormAllOperations<D> {
- protected final List<FinderMethod> gormDynamicFinders
+ private static final TransactionTemplateFactory DEFAULT_TRANSACTION_TEMPLATE_FACTORY = new DefaultTransactionTemplateFactory()
- protected final PlatformTransactionManager transactionManager
- protected final String defaultQualifier
+ protected final List<FinderMethod> finders
+
+ /**
+ * The multi-tenancy mode of the datastore this API was created for, resolved once at
+ * construction time. Retained for source/binary compatibility with out-of-tree
+ * {@code GormStaticApi} subclasses that reference this field directly.
+ */
protected final MultiTenancyMode multiTenancyMode
- protected final ConnectionSources connectionSources
+ @Deprecated
GormStaticApi(Class<D> persistentClass, Datastore datastore, List<FinderMethod> finders) {
- this(persistentClass, datastore, finders, null)
+ this(persistentClass, datastore?.mappingContext, finders, datastore != null ? ({ datastore } as DatastoreResolver) : null, ConnectionSource.DEFAULT, null)
}
+ @Deprecated
GormStaticApi(Class<D> persistentClass, Datastore datastore, List<FinderMethod> finders, PlatformTransactionManager transactionManager) {
- super(persistentClass, datastore)
- gormDynamicFinders = finders
- this.transactionManager = transactionManager
- String qualifier = ConnectionSource.DEFAULT
- if (datastore instanceof ConnectionSourcesProvider) {
- this.connectionSources = ((ConnectionSourcesProvider) datastore).connectionSources
- ConnectionSource<?, ? extends ConnectionSourceSettings> defaultConnectionSource = connectionSources.defaultConnectionSource
- qualifier = defaultConnectionSource.name
- multiTenancyMode = defaultConnectionSource.settings.multiTenancy.mode
+ this(persistentClass, datastore?.mappingContext, finders, datastore != null ? ({ datastore } as DatastoreResolver) : null, ConnectionSource.DEFAULT, null)
+ }
- }
- else {
- connectionSources = null
- multiTenancyMode = MultiTenancyMode.NONE
- }
- this.defaultQualifier = qualifier
+ GormStaticApi(Class<D> persistentClass, MappingContext mappingContext, List<FinderMethod> finders) {
+ this(persistentClass, mappingContext, finders, null, ConnectionSource.DEFAULT, null)
}
- /**
- * @return The PersistentEntity for this class
- */
- PersistentEntity getGormPersistentEntity() {
- persistentEntity
+ GormStaticApi(Class<D> persistentClass, MappingContext mappingContext, List<FinderMethod> finders, String qualifier) {
+ this(persistentClass, mappingContext, finders, null, qualifier, null)
}
- List<FinderMethod> getGormDynamicFinders() {
- gormDynamicFinders
+ GormStaticApi(Class<D> persistentClass, MappingContext mappingContext, List<FinderMethod> finders, DatastoreResolver resolver, String qualifier) {
+ this(persistentClass, mappingContext, finders, resolver, qualifier, null)
+ }
+
+ GormStaticApi(Class<D> persistentClass, MappingContext mappingContext, List<FinderMethod> finders, DatastoreResolver resolver, String qualifier, GormRegistry registry) {
+ super(persistentClass, mappingContext, resolver, qualifier, registry)
+ this.finders = finders
+ this.multiTenancyMode = resolveMultiTenancyMode(resolver)
}
/**
- * Property missing handler
- *
- * @param name The name of the property
+ * Resolves the multi-tenancy mode from the datastore this API is bound to. Safe to call at
+ * construction time: every code path that constructs a {@code GormStaticApi} passes either
+ * {@code null} or a resolver already bound to a concrete, already-registered datastore (see
+ * {@code GormRegistry.createStaticApi}) — never a tenant-resolving resolver that could throw
+ * before a tenant context is bound.
*/
- def propertyMissing(String name) {
- if (datastore instanceof ConnectionSourcesProvider) {
- return GormEnhancer.findStaticApi(persistentClass, name)
+ private static MultiTenancyMode resolveMultiTenancyMode(DatastoreResolver resolver) {
+ Datastore ds = resolver?.resolve()
+ if (ds instanceof ConnectionSourcesProvider) {
+ def defaultConnectionSource = ((ConnectionSourcesProvider) ds).connectionSources.defaultConnectionSource
+ return defaultConnectionSource.settings.multiTenancy.mode
}
- else {
- throw new MissingPropertyException(name, persistentClass)
+ return MultiTenancyMode.NONE
+ }
+
+ @Override
+ PlatformTransactionManager getTransactionManager() {
+ Datastore ds = getDatastore()
+ if (ds instanceof TransactionCapableDatastore) {
+ return ((TransactionCapableDatastore)ds).getTransactionManager()
}
+ return null
}
- /**
- * Property missing handler
- *
- * @param name The name of the property
- */
- void propertyMissing(String name, value) {
- throw new MissingPropertyException(name, persistentClass)
+ @Override
+ protected <T1> T1 executeQualified(String qualifier, SessionCallback<T1> callback) {
+ GormStaticApi<D> qualifiedApi = registry.findStaticApi(persistentClass, qualifier)
+ if (qualifiedApi != null && qualifiedApi != this) {
+ return (T1) qualifiedApi.execute(callback)
+ }
+ return DatastoreUtils.execute(getDatastore(), callback)
}
- /**
- * Method missing handler that deals with the invocation of dynamic finders
- *
- * @param methodName The method name
- * @param args The arguments
- * @return The result of the method call
- */
- @CompileDynamic
- def methodMissing(String methodName, Object args) {
- FinderMethod method = gormDynamicFinders.find { FinderMethod f -> f.isMethodMatch(methodName) }
- if (!method) {
- if (args && args[-1] instanceof Closure) {
- NamedCriteriaProxy proxy = GormEnhancer.createNamedQuery(persistentClass, methodName)
- if (proxy != null) {
- return proxy.call(args)
- }
- else {
- throw new MissingMethodException(methodName, persistentClass, args)
- }
- }
- else {
- throw new MissingMethodException(methodName, persistentClass, args)
- }
+ @Override
+ PersistentEntity getGormPersistentEntity() {
+ PersistentEntity entity = qualifier != null ? registry.apiResolver.findEntity(persistentClass, qualifier) : null
+ if (entity == null) {
+ entity = super.getGormPersistentEntity()
+ }
+ if (entity == null) {
+ entity = registry.apiResolver.findEntity(persistentClass)
}
+ // Final fallback: resolve from the mapping context captured when this API was constructed.
+ // Entity metadata is identical across tenants/connections (only the datastore/session differs),
+ // so this stable reference is the most reliable source and avoids a null entity when runtime
+ // registry resolution is disturbed by cross-spec state — e.g. a qualified API created by
+ // withTenant(tenantId) for DISCRIMINATOR/SCHEMA multi-tenancy.
+ if (entity == null && mappingContext != null) {
+ entity = mappingContext.getPersistentEntity(persistentClass.name)
+ }
+ entity
+ }
- // if the class is multi tenant, don't cache the method because the tenant will need to be resolved
- // for each method call
- if (!MultiTenant.isAssignableFrom(persistentClass)) {
+ @Override
+ List<FinderMethod> getGormDynamicFinders() {
+ return finders
+ }
- def mc = persistentClass.getMetaClass()
+ GormStaticApi<D> forQualifier(String qualifier) {
+ Datastore ds = getDatastore()
+ DatastoreResolver resolver = new DatastoreResolver() {
+ @Override Datastore resolve() { registry.apiResolver.findDatastore(persistentClass, qualifier) }
+ }
+ List<FinderMethod> qualifiedFinders = registry.createDynamicFinders(resolver, ds.mappingContext)
+ createStaticApi(persistentClass, ds.mappingContext, qualifiedFinders, resolver, qualifier)
+ }
- // register the method invocation for next time
- mc.static."$methodName" = { Object[] varArgs ->
- // FYI... This is relevant to http://jira.grails.org/browse/GRAILS-3463 and may
- // become problematic if http://jira.codehaus.org/browse/GROOVY-5876 is addressed...
- final argumentsForMethod
- if (varArgs == null) {
- argumentsForMethod = [null] as Object[]
- }
- // if the argument component type is not an Object then we have an array passed that is the actual argument
- else if (varArgs.getClass().componentType != Object) {
- // so we wrap it in an object array
- argumentsForMethod = [varArgs] as Object[]
- }
- else {
+ protected GormStaticApi<D> createStaticApi(Class<D> persistentClass, MappingContext mappingContext, List<FinderMethod> finders, DatastoreResolver resolver, String qualifier) {
+ new GormStaticApi<D>(persistentClass, mappingContext, finders, resolver, qualifier, registry)
+ }
- if (varArgs.length == 1 && varArgs[0].getClass().isArray()) {
- argumentsForMethod = varArgs[0]
- } else {
+ @Override
+ Object methodMissing(String name, Object args) {
+ Object[] argsArray = (args instanceof Object[]) ? (Object[]) args : ([args] as Object[])
+ for (FinderMethod fm : finders) {
+ if (fm.isMethodMatch(name)) {
+ return execute({ Session session ->
+ fm.invoke(persistentClass, name, argsArray)
+ } as SessionCallback)
+ }
+ }
+ throw new MissingMethodException(name, persistentClass, argsArray)
+ }
- argumentsForMethod = varArgs
- }
+ @Override
+ Object propertyMissing(String name) {
+ for (FinderMethod fm : finders) {
+ if (fm.isMethodMatch(name)) {
+ return { Object... args ->
+ Object[] finderArgs = args == null ? ([null] as Object[]) : args
+ execute({ Session session ->
+ fm.invoke(persistentClass, name, finderArgs)
+ } as SessionCallback)
+ }
+ }
+ }
+
+ Datastore ds = getDatastore()
+ if (ds instanceof ConnectionSourcesProvider) {
+ ConnectionSources sources = ((ConnectionSourcesProvider) ds).connectionSources
+ if (sources != null) {
+ if (sources.getConnectionSource(name) != null) {
+ return registry.findStaticApi(persistentClass, name)
+ }
+ if (name.equalsIgnoreCase(ConnectionSource.DEFAULT) || name.equalsIgnoreCase(ConnectionSource.OLD_DEFAULT)) {
+ return registry.findStaticApi(persistentClass, ConnectionSource.DEFAULT)
}
- method.invoke(delegate, methodName, argumentsForMethod)
}
}
+ // Fallback: the preferred/transactional datastore may be a single-datasource datastore
+ // that doesn't expose the named qualifier in its connectionSources. Check the registry
+ // directly so that entities mapped to multiple datasources (e.g. datasource 'ALL') can
+ // still be accessed via the qualifier even when a single-datasource transaction is active.
+ if (registry.getDatastoreByString(persistentClass.name, name) != null) {
+ return registry.findStaticApi(persistentClass, name)
+ }
+ throw new MissingPropertyException(name, persistentClass)
+ }
- return method.invoke(persistentClass, methodName, args)
+ @Override
+ void propertyMissing(String name, Object val) {
+ throw new MissingPropertyException(name, persistentClass)
}
- /**
- *
- * @param callable Callable closure containing detached criteria definition
- * @return The DetachedCriteria instance
- */
- DetachedCriteria<D> where(Closure callable) {
- new DetachedCriteria<D>(persistentClass).build(callable)
+ // GormInstanceOperations delegation
+ @Override
+ def propertyMissing(D instance, String name) {
+ registry.findInstanceApi(persistentClass, qualifier).propertyMissing(instance, name)
}
- /**
- *
- * @param callable Callable closure containing detached criteria definition
- * @return The DetachedCriteria instance that is lazily initialized
- */
- DetachedCriteria<D> whereLazy(Closure callable) {
- new DetachedCriteria<D>(persistentClass).buildLazy(callable)
+ @Override
+ boolean instanceOf(D instance, Class cls) {
+ registry.findInstanceApi(persistentClass, qualifier).instanceOf(instance, cls)
}
- /**
- *
- * @param callable Callable closure containing detached criteria definition
- * @return The DetachedCriteria instance
- */
- DetachedCriteria<D> whereAny(Closure callable) {
- (DetachedCriteria<D>) new DetachedCriteria<D>(persistentClass).or(callable)
+
+ @Override
+ D lock(D instance) {
+ registry.findInstanceApi(persistentClass, qualifier).lock(instance)
}
- /**
- * Uses detached criteria to build a query and then execute it returning a list
- *
- * @param callable The callable
- * @return A List of entities
- */
- List<D> findAll(Closure callable) {
- def criteria = new DetachedCriteria<D>(persistentClass).build(callable)
- return criteria.list()
+ @Override
+ def <T1> T1 mutex(D instance, Closure<T1> callable) {
+ registry.findInstanceApi(persistentClass, qualifier).mutex(instance, callable)
}
- /**
- * Uses detached criteria to build a query and then execute it returning a list
- *
- * @param args pagination parameters
- * @param callable The callable
- * @return A List of entities
- */
- List<D> findAll(Map args, Closure callable) {
- def criteria = new DetachedCriteria<D>(persistentClass).build(callable)
- return criteria.list(args)
+ @Override
+ D refresh(D instance) {
+ registry.findInstanceApi(persistentClass, qualifier).refresh(instance)
}
- /**
- * Uses detached criteria to build a query and then execute it returning a list
- *
- * @param callable The callable
- * @return A single entity
- */
- D find(Closure callable) {
- def criteria = new DetachedCriteria<D>(persistentClass).build(callable)
- return criteria.find()
+ @Override
+ D refresh(D instance, Map args) {
+ registry.findInstanceApi(persistentClass, qualifier).refresh(instance, args)
}
- /**
- * Saves a list of objects in one go
- * @param objectsToSave The objects to save
- * @return A list of object identifiers
- */
- List<Serializable> saveAll(Object... objectsToSave) {
- (List<Serializable>) execute({ Session session ->
- session.persist(Arrays.asList(objectsToSave))
- } as SessionCallback)
+ @Override
+ D save(D instance) {
+ registry.findInstanceApi(persistentClass, qualifier).save(instance)
}
- /**
- * Saves a list of objects in one go
- * @param objectToSave Collection of objects to save
- * @return A list of object identifiers
- */
- List<Serializable> saveAll(Iterable<?> objectsToSave) {
- (List<Serializable>) execute({ Session session ->
- session.persist(objectsToSave)
- } as SessionCallback)
+ @Override
+ D insert(D instance) {
+ registry.findInstanceApi(persistentClass, qualifier).insert(instance)
}
- /**
- * Deletes a list of objects in one go
- * @param objectsToDelete The objects to delete
- */
- void deleteAll(Object... objectsToDelete) {
- execute({ Session session ->
- session.delete(Arrays.asList(objectsToDelete))
- } as SessionCallback)
+ @Override
+ D insert(D instance, Map params) {
+ registry.findInstanceApi(persistentClass, qualifier).insert(instance, params)
}
- /**
- * Deletes a list of objects in one go and flushes when param is set
- * @param objectsToDelete The objects to delete
- */
- void deleteAll(Map params, Object... objectsToDelete) {
- execute({ Session session ->
- session.delete(Arrays.asList(objectsToDelete))
- if (params?.flush) {
- session.flush()
- }
- } as SessionCallback)
+ @Override
+ D merge(D instance) {
+ registry.findInstanceApi(persistentClass, qualifier).merge(instance)
}
- /**
- * Deletes a list of objects in one go
- * @param objectsToDelete Collection of objects to delete
- */
- void deleteAll(Iterable objectToDelete) {
- execute({ Session session ->
- session.delete(objectToDelete)
- } as SessionCallback)
+ @Override
+ D merge(D instance, Map params) {
+ registry.findInstanceApi(persistentClass, qualifier).merge(instance, params)
}
- /**
- * Deletes a list of objects in one go and flushes when param is set
- * @param objectsToDelete Collection of objects to delete
- */
- void deleteAll(Map params, Iterable objectToDelete) {
- execute({ Session session ->
- session.delete(objectToDelete)
- if (params?.flush) {
- session.flush()
- }
- } as SessionCallback)
+ @Override
+ D save(D instance, boolean validate) {
+ registry.findInstanceApi(persistentClass, qualifier).save(instance, validate)
}
- /**
- * Creates an instance of this class
- * @return The created instance
- */
- @CompileStatic(TypeCheckingMode.SKIP)
- D create() {
- D d = persistentClass.newInstance()
+ @Override
+ D save(D instance, Map params) {
+ registry.findInstanceApi(persistentClass, qualifier).save(instance, params)
+ }
- def applicationContext = datastore.applicationContext
+ @Override
+ Serializable ident(D instance) {
+ registry.findInstanceApi(persistentClass, qualifier).ident(instance)
+ }
- if (applicationContext != null) {
- applicationContext.autowireCapableBeanFactory.autowireBeanProperties(
- d, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false)
- }
+ @Override
+ D attach(D instance) {
+ registry.findInstanceApi(persistentClass, qualifier).attach(instance)
+ }
- return d
+ @Override
+ boolean isAttached(D instance) {
+ registry.findInstanceApi(persistentClass, qualifier).isAttached(instance)
}
- /**
- * Retrieves an object from the datastore. eg. Book.get(1)
- */
+ @Override
+ void discard(D instance) {
+ registry.findInstanceApi(persistentClass, qualifier).discard(instance)
+ }
+
+ @Override
+ void delete(D instance) {
+ registry.findInstanceApi(persistentClass, qualifier).delete(instance)
+ }
+
+ @Override
+ void delete(D instance, Map params) {
+ registry.findInstanceApi(persistentClass, qualifier).delete(instance, params)
+ }
+
+ // GormStaticOperations
+ @Override
D get(Serializable id) {
+ if (id != null && isRetrievedByQuery()) {
+ return retrieveAllByQuery([id], false)[0]
+ }
- (D) execute({ Session session ->
- session.retrieve((Class)persistentClass, id)
- } as SessionCallback)
+ execute({ Session session ->
+ session.retrieve(persistentClass, id)
+ } as SessionCallback<D>)
}
- /**
- * Retrieves an object from the datastore. eg. Book.read(1)
- *
- * Since the datastore abstraction doesn't support dirty checking yet this
- * just delegates to {@link #get(Serializable)}
- */
+ @Override
D read(Serializable id) {
get(id)
}
- /**
- * Retrieves an object from the datastore as a proxy. eg. Book.load(1)
- */
+ @Override
D load(Serializable id) {
+ if (id != null && isRetrievedByQuery()) {
+ return proxyByQuery(id)
+ }
- (D) execute({ Session session ->
- session.proxy((Class)persistentClass, id)
- } as SessionCallback)
+ execute({ Session session ->
+ session.proxy(persistentClass, id)
+ } as SessionCallback<D>)
}
- /**
- * Retrieves an object from the datastore as a proxy. eg. Book.proxy(1)
- */
+ @Override
D proxy(Serializable id) {
load(id)
}
- /**
- * Retrieve all the objects for the given identifiers
- * @param ids The identifiers to operate against
- * @return A list of identifiers
- */
- List<D> getAll(Iterable<Serializable> ids) {
- return getAll(ids as Serializable[])
+ @Override
+ List<D> getAll(Serializable... ids) {
++ if (isRetrievedByQuery()) {
++ List<Serializable> keys = (List<Serializable>) ids.flatten()
++ if (keys) {
++ return retrieveAllByQuery(keys, true)
++ }
++ }
+ execute({ Session session ->
+ session.retrieveAll(persistentClass, ids)
+ } as SessionCallback<List<D>>)
}
- /**
- * Retrieve all the objects for the given identifiers
- * @param ids The identifiers to operate against
- * @return A list of identifiers
- */
- List<D> getAll(Serializable... ids) {
- List<Serializable> keys = (List<Serializable>) ids.flatten()
- if (keys && isRetrievedByQuery()) {
- return retrieveAllByQuery(keys, true)
+ @Override
+ List<D> getAll(Iterable<Serializable> ids) {
++ if (isRetrievedByQuery()) {
++ List<Serializable> keys = ids.toList()
++ if (keys) {
++ return retrieveAllByQuery(keys, true)
++ }
+ }
- (List<D>) execute({ Session session ->
- session.retrieveAll(persistentClass, keys)
- } as SessionCallback)
+ execute({ Session session ->
+ session.retrieveAll(persistentClass, ids)
+ } as SessionCallback<List<D>>)
+ }
+
+ @Override
+ List<D> getAll() {
+ list()
}
+ /**
+ * Whether instances are retrieved by id through a query. In {@link MultiTenancyMode#DISCRIMINATOR} mode the
+ * multi-tenant event listener restricts a query to the current tenant, but a lookup by key bypasses it, so the
+ * instances of a multi-tenant entity are retrieved through a query instead. Inside
+ * {@link Tenants#withoutId(groovy.lang.Closure)} a lookup by id is not restricted to a tenant and stays a lookup by
+ * key.
+ *
+ * @return Whether instances are retrieved by id through a query
+ */
+ private boolean isRetrievedByQuery() {
- if (multiTenancyMode != MultiTenancyMode.DISCRIMINATOR
- || persistentEntity?.isMultiTenant() != true
- || persistentEntity.identity == null
- || persistentEntity.tenantId == null) {
++ if (multiTenancyMode != MultiTenancyMode.DISCRIMINATOR) {
++ return false
++ }
++ PersistentEntity entity = getGormPersistentEntity()
++ if (entity?.isMultiTenant() != true || entity.identity == null || entity.tenantId == null) {
+ return false
+ }
- return !Tenants.isWithoutId()
++ return !Tenants.isWithoutId(getDatastore())
+ }
+
+ /**
++ * The current tenant id of the datastore this API is bound to. Protected rather than private because the session
++ * callbacks of this class call it, and a call from a closure does not reach a private method when the API is a
++ * subclass instance.
++ *
+ * @return The current tenant id
+ * @throws org.grails.datastore.mapping.multitenancy.exceptions.TenantNotFoundException if there is no current tenant
+ */
- private Serializable currentTenantId() {
- datastore instanceof MultiTenantCapableDatastore
- ? Tenants.currentId((MultiTenantCapableDatastore) datastore)
- : Tenants.currentId(datastore.getClass())
++ protected Serializable currentTenantId() {
++ Datastore ds = getDatastore()
++ ds instanceof MultiTenantCapableDatastore
++ ? Tenants.currentId((MultiTenantCapableDatastore) ds)
++ : Tenants.currentId(ds.getClass())
+ }
+
+ /**
+ * Retrieves the instances for the given identifiers through a query, which the multi-tenant event listener
+ * restricts to the current tenant.
+ *
+ * @param ids The identifiers
+ * @param strict Whether an identifier that cannot be converted to the type of the identity throws
+ * @return The instances in the order of the identifiers, with {@code null} for an identifier no instance was found for
+ */
+ private List<D> retrieveAllByQuery(Collection<Serializable> ids, boolean strict) {
- (List<D>) execute({ Session session ->
++ execute({ Session session ->
+ findAllByKeys(session, ids.collect { Serializable id -> convertIdentifier(session, id, strict) })
- } as SessionCallback)
++ } as SessionCallback<List<D>>)
+ }
+
+ /**
+ * Finds the instances of the current tenant for the given keys. An instance the session already holds is returned
+ * without a query, as the lookup by key returns it, and the others are queried without flushing the session.
++ * Protected rather than private because the session callbacks of this class call it.
+ *
+ * @param session The session
+ * @param keys The keys, already converted to the type of the identity
+ * @return The instances in the order of the keys, with {@code null} for a key no instance was found for
+ * @throws org.grails.datastore.mapping.multitenancy.exceptions.TenantNotFoundException if there is no current tenant
+ */
- private List<Object> findAllByKeys(Session session, List<Serializable> keys) {
++ protected List<D> findAllByKeys(Session session, List<Serializable> keys) {
+ Map<Object, Object> found = [:]
+ Set<Serializable> missing = new LinkedHashSet<>()
+ if (keys.any { Serializable key -> key != null }) {
+ Serializable tenantId = currentTenantId()
+ for (Serializable key in keys) {
+ if (key == null || found.containsKey(key) || missing.contains(key)) {
+ continue
+ }
+ Object cached = findCachedInstance(session, key, tenantId)
+ if (cached != null) {
+ found.put(key, cached)
+ }
+ else {
+ missing.add(key)
+ }
+ }
+ }
+ if (missing) {
++ PersistentEntity entity = getGormPersistentEntity()
+ FlushModeType flushMode = session.flushMode
+ session.flushMode = FlushModeType.COMMIT
+ try {
+ Query query = session.createQuery(persistentClass)
+ if (missing.size() == 1) {
+ query.idEq(missing.first())
+ }
+ else {
- query.in(persistentEntity.identity.name, missing.toList())
++ query.in(entity.identity.name, missing.toList())
+ }
+ for (Object instance in query.list()) {
- found.put(persistentEntity.reflector.getIdentifier(instance), instance)
++ found.put(entity.reflector.getIdentifier(instance), instance)
+ }
+ }
+ finally {
+ session.flushMode = flushMode
+ }
+ }
- keys.collect { Serializable key -> key == null ? null : found.get(key) }
++ (List<D>) keys.collect { Serializable key -> key == null ? null : found.get(key) }
+ }
+
+ /**
+ * Returns the instance the session holds for the given key if it belongs to the given tenant. An instance that is
+ * waiting to be inserted and has no tenant id yet belongs to it as well, because the multi-tenant event listener
- * assigns the current tenant when it inserts the instance.
++ * assigns the current tenant when it inserts the instance. Protected rather than private because the session
++ * callbacks of this class call it.
+ *
+ * @param session The session
+ * @param key The key, already converted to the type of the identity
+ * @param tenantId The current tenant id
+ * @return The instance, or {@code null} if the session holds none for the key or it belongs to another tenant
+ */
- private Object findCachedInstance(Session session, Serializable key, Serializable tenantId) {
++ protected Object findCachedInstance(Session session, Serializable key, Serializable tenantId) {
+ if (!(session instanceof SessionImplementor)) {
+ return null
+ }
+ SessionImplementor implementor = (SessionImplementor) session
+ Object instance = implementor.getCachedInstance(persistentClass, key)
+ if (instance == null) {
+ return null
+ }
- Object instanceTenantId = persistentEntity.reflector.getProperty(instance, persistentEntity.tenantId.name)
++ PersistentEntity entity = getGormPersistentEntity()
++ Object instanceTenantId = entity.reflector.getProperty(instance, entity.tenantId.name)
+ if (instanceTenantId == null) {
+ return isPendingInsert(implementor, instance) ? instance : null
+ }
+ return isSameTenant(session, instanceTenantId, tenantId) ? instance : null
+ }
+
+ private static boolean isPendingInsert(SessionImplementor session, Object instance) {
+ session.pendingInserts.values().any { Collection<PendingInsert> inserts ->
+ inserts.any { PendingInsert insert -> insert.object.is(instance) }
+ }
+ }
+
+ private static boolean isSameTenant(Session session, Object instanceTenantId, Serializable tenantId) {
+ if (instanceTenantId == tenantId) {
+ return true
+ }
+ ConversionService conversionService = session.mappingContext.conversionService
+ Class tenantIdType = instanceTenantId.getClass()
+ if (!conversionService.canConvert(tenantId.getClass(), tenantIdType)) {
+ return false
+ }
+ try {
+ return instanceTenantId == conversionService.convert(tenantId, tenantIdType)
+ }
+ catch (ConversionFailedException ignored) {
+ return false
+ }
+ }
+
+ /**
+ * Returns the instance the session holds for the given id if it belongs to the current tenant, and otherwise a
+ * proxy that is initialized through a query by id, which the multi-tenant event listener restricts to the tenant
+ * that is current when the proxy is initialized. A proxy for an instance of another tenant then fails to
+ * initialize, as a proxy for an instance that does not exist does. A proxy initialized inside
+ * {@link Tenants#withoutId(groovy.lang.Closure)} looks the instance up by key, so it is not restricted to a tenant.
+ *
+ * @param id The identifier
+ * @return The instance or the proxy
+ */
+ private D proxyByQuery(Serializable id) {
- (D) execute({ Session session ->
++ execute({ Session session ->
+ Serializable key = convertIdentifier(session, id, true)
+ Object cached = findCachedInstance(session, key, currentTenantId())
+ if (cached != null) {
+ return cached
+ }
+ try {
+ return session.mappingContext.proxyFactory.createProxy(session, new IdQueryExecutor(this, session), key)
+ }
+ catch (UnsupportedOperationException ignored) {
+ // a proxy factory that cannot initialize a proxy through a query gets the instance itself
+ return findAllByKeys(session, [key])[0]
+ }
- } as SessionCallback)
++ } as SessionCallback<D>)
+ }
+
+ /**
+ * Converts an identifier to the type of the identity as the lookup by key converts it: {@code getAll} and
+ * {@code load} throw for an identifier that cannot be converted, and {@code get} finds no instance for it.
++ * Protected rather than private because the session callbacks of this class call it.
+ *
+ * @param session The session
+ * @param id The identifier
+ * @param strict Whether an identifier that cannot be converted throws
+ * @return The converted identifier, or {@code null} for an identifier that cannot be converted if not strict
+ */
- private Serializable convertIdentifier(Session session, Serializable id, boolean strict) {
- Class identityType = persistentEntity.identity.type
++ protected Serializable convertIdentifier(Session session, Serializable id, boolean strict) {
++ Class identityType = getGormPersistentEntity().identity.type
+ if (id == null || identityType.isInstance(id)) {
+ return id
+ }
+ ConversionService conversionService = session.mappingContext.conversionService
+ if (strict) {
+ return (Serializable) conversionService.convert(id, identityType)
+ }
+ if (!conversionService.canConvert(id.getClass(), identityType)) {
+ return null
+ }
+ try {
+ return (Serializable) conversionService.convert(id, identityType)
+ }
+ catch (ConversionFailedException ignored) {
+ return null
+ }
+ }
+
- /**
- * @return Synonym for {@link #list()}
- */
- List<D> getAll() {
- list()
- }
-
- /**
- * Creates a criteria builder instance
- */
- BuildableCriteria createCriteria() {
- new CriteriaBuilder(persistentClass, datastore.currentSession)
+ @Override
+ List<D> list() {
+ list(Collections.emptyMap())
}
- /**
- * Creates a criteria builder instance
- */
- def withCriteria(@DelegatesTo(Criteria) Closure callable) {
+ @Override
+ List<D> list(Map params) {
execute({ Session session ->
- InvokerHelper.invokeMethod(createCriteria(), 'call', callable)
- } as SessionCallback)
- }
-
- /**
- * Creates a criteria builder instance
- */
- def withCriteria(Map builderArgs, @DelegatesTo(Criteria) Closure callable) {
- def criteriaBuilder = createCriteria()
- def builderBean = PropertyAccessorFactory.forBeanPropertyAccess(criteriaBuilder)
- for (entry in builderArgs.entrySet()) {
- String propertyName = entry.key.toString()
- if (builderBean.isWritableProperty(propertyName)) {
- builderBean.setPropertyValue(propertyName, entry.value)
+ org.grails.datastore.mapping.query.Query q = session.createQuery(persistentClass)
+ org.grails.datastore.gorm.finders.DynamicFinder.populateArgumentsForCriteria(persistentClass, q, params)
+ if (params?.containsKey('max')) {
+ return new grails.gorm.PagedResultList(q)
}
- }
-
- if (builderArgs?.uniqueResult) {
- execute({ Session session ->
- InvokerHelper.invokeMethod(criteriaBuilder, 'get', callable)
- } as SessionCallback)
-
- }
- else {
- execute({ Session session ->
- InvokerHelper.invokeMethod(criteriaBuilder, 'list', callable)
- } as SessionCallback)
- }
-
+ q.list()
+ } as SessionCallback<List<D>>)
}
- /**
- * Locks an instance for an update
- * @param id The identifier
- * @return The instance
- */
- D lock(Serializable id) {
- (D) execute({ Session session ->
- session.lock((Class)persistentClass, id)
- } as SessionCallback)
+ @Override
+ Long count() {
+ // Capture the @Slf4j logger before entering the SessionCallback. With
+ // invokedynamic off (Grails 8 default), log.debug(...) inside that
+ // closure is dispatched through methodMissing as a dynamic finder on
+ // the persistent class (MissingMethodException: debug).
+ def logger = log
+ logger.debug('GormStaticApi.count() called for {}', persistentClass.name)
+ Long result = execute({ Session session ->
+ def query = session.createQuery(persistentClass)
+ query.projections().count()
+ def res = query.singleResult()
+ logger.debug('Query singleResult returned {}', res)
+ res instanceof Number ? ((Number)res).longValue() : 0L
+ } as SessionCallback<Long>)
+ logger.debug('count() result is {}', result)
+ return result
}
- /**
- * Merges an instance with the current session
- * @param d The object to merge
- * @return The instance
- */
@Override
- def propertyMissing(D instance, String name) {
- GormEnhancer.findInstanceApi(persistentClass, defaultQualifier).propertyMissing(instance, name)
+ Long getCount() {
+ count()
}
@Override
@@@ -990,86 -1398,64 +1223,120 @@@
throw new UnsupportedOperationException("String-based queries like [$method] are currently not supported in this implementation of GORM. Use criteria instead.")
}
- private Map createQueryMapForExample(PersistentEntity persistentEntity, D example) {
- def props = persistentEntity.persistentProperties.findAll { PersistentProperty prop ->
- !(prop instanceof Association)
+ @Override
+ grails.gorm.api.GormAllOperations<D> withTenant(Serializable tenantId) {
+ return (grails.gorm.api.GormAllOperations<D>) forQualifier(tenantId.toString())
+ }
+
+ @Override
+ def <T1> T1 withTenant(Serializable tenantId, Closure<T1> callable) {
+ withId(tenantId, callable)
+ }
+
+ @Override
+ grails.gorm.api.GormAllOperations<D> eachTenant(Closure callable) {
+ Datastore ds = registry.getDatastore(persistentClass.name, ConnectionSource.DEFAULT)
+ if (ds instanceof MultiTenantCapableDatastore) {
+ Tenants.eachTenant((MultiTenantCapableDatastore) ds, callable)
+ return this
}
+ throw new UnsupportedOperationException("eachTenant not supported for datastore: ${ds?.class?.simpleName}")
+ }
+
+ def <T1> T1 withTenantTransaction(Serializable tenantId, Closure<T1> callable) {
+ withId(tenantId, callable)
+ }
+
+ def <T1> T1 withTenantTransaction(Serializable tenantId, org.springframework.transaction.TransactionDefinition definition, Closure<T1> callable) {
+ withId(tenantId, callable)
+ }
- def queryMap = [:]
- for (PersistentProperty prop in props) {
- def val = example[prop.name]
- if (val != null) {
- queryMap[prop.name] = val
+ def <T1> T1 withId(Serializable tenantId, Closure<T1> callable) {
+ // For multi-tenancy, always resolve via the DEFAULT (root/parent) datastore.
+ // Resolving the tenant-specific datastore and then calling withNewSession() on it
+ // would fail because child datastores have empty datastoresByConnectionSource maps.
+ Datastore defaultDs = registry.getDatastore(persistentClass.name, ConnectionSource.DEFAULT)
+ if (defaultDs instanceof MultiTenantCapableDatastore) {
+ return (T1) Tenants.withId((MultiTenantCapableDatastore) defaultDs, tenantId, callable)
+ }
+ // Non-multi-tenant path: resolve the specific datastore for this connection/tenant key
+ Datastore tenantDatastore = registry.apiResolver.findDatastore(persistentClass, tenantId.toString())
+ return DatastoreUtils.execute(tenantDatastore, (Session session) -> {
+ return (T1) callable.call(session)
+ } as SessionCallback<T1>)
+ }
+
+ def <T1> T1 withoutId(Closure<T1> callable) {
+ Datastore defaultDs = registry.getDatastore(persistentClass.name, ConnectionSource.DEFAULT)
+ if (defaultDs instanceof MultiTenantCapableDatastore) {
+ MultiTenantCapableDatastore multiTenantDs = (MultiTenantCapableDatastore) defaultDs
+ // Bound rather than entered through Tenants.withoutId, which passes a closure with parameters the session
+ // only, so that the closure gets the tenant id and the session, as it does with withId.
+ return (T1) CurrentTenantHolder.withoutTenant(multiTenantDs) {
+ Tenants.withCurrent(multiTenantDs, callable)
}
}
- return queryMap
+ withId(ConnectionSource.DEFAULT, callable)
}
- private D internalFindOrCreate(Map queryMap, boolean shouldSave) {
- D result = findWhere(queryMap)
- if (!result) {
- def persistentMetaClass = GroovySystem.metaClassRegistry.getMetaClass(persistentClass)
- result = (D) persistentMetaClass.invokeConstructor(queryMap)
- if (shouldSave) {
- InvokerHelper.invokeMethod(result, 'save', null)
- }
+ /**
+ * Runs the callable in a new session for the tenant, with the tenant bound, so that the calls it makes on the
+ * class reach the tenant named here rather than the one that resolving would find.
+ *
+ * @param tenantId The tenant
+ * @param callable What to run
+ * @return What the callable returns
+ */
+ def <T1> T1 withNewSession(Serializable tenantId, Closure<T1> callable) {
+ DatastoreResolver resolver = new DatastoreResolver() {
+ @Override Datastore resolve() { registry.apiResolver.findDatastore(persistentClass, tenantId.toString()) }
+ }
+ Datastore tenantDatastore = resolver.resolve()
+ Closure<T1> inNewSession = { Serializable boundTenantId ->
+ DatastoreUtils.executeWithNewSession(tenantDatastore, { Session session ->
+ return (T1) callable.call(session)
+ } as SessionCallback<T1>)
+ }
+ Datastore defaultDatastore = registry.getDatastore(persistentClass.name, ConnectionSource.DEFAULT)
+ if (defaultDatastore instanceof MultiTenantCapableDatastore) {
+ // Bound rather than entered through Tenants.withId, which would open a session of its own for the
+ // tenant in the modes that give it a connection, leaving the one opened here unused.
+ return (T1) CurrentTenantHolder.withTenant(defaultDatastore, tenantId, inNewSession)
}
- result
+ return inNewSession.call(tenantId)
}
+
+ /**
+ * Finds an instance by id for a proxy created by {@link GormStaticApi#load(Serializable)}, as
+ * {@link GormStaticApi#get(Serializable)} finds it. Inside {@link Tenants#withoutId(groovy.lang.Closure)} the
+ * instance is looked up by key instead, as {@code load} looks it up there.
+ */
+ private static class IdQueryExecutor implements AssociationQueryExecutor<Serializable, Object> {
+
+ private final GormStaticApi<?> api
+ private final Session session
+
+ IdQueryExecutor(GormStaticApi<?> api, Session session) {
+ this.api = api
+ this.session = session
+ }
+
+ @Override
+ List<Object> query(Serializable id) {
- Object instance = Tenants.isWithoutId()
- ? session.retrieve(api.persistentClass, id)
++ Object instance = Tenants.isWithoutId(session.datastore)
++ ? session.retrieve(api.gormPersistentEntity.javaClass, id)
+ : api.findAllByKeys(session, [id])[0]
+ instance == null ? [] : [instance]
+ }
+
+ @Override
+ PersistentEntity getIndexedEntity() {
- api.persistentEntity
++ api.gormPersistentEntity
+ }
+
+ @Override
+ boolean doesReturnKeys() {
+ false
+ }
+ }
}
diff --cc grails-doc/src/en/guide/upgrading/upgrading80x.adoc
index 00e38448de,0000000000..04ae7c0ebd
mode 100644,000000..100644
--- a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc
+++ b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc
@@@ -1,4830 -1,0 +1,4839 @@@
+////
+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.
+////
+
+=== Upgrade Instructions for Grails and Related Dependencies
+
+To ensure compatibility with Grails {version}, please review the following upgrade instructions carefully.
+This guide outlines the necessary steps and warnings to upgrade your Grails project from Grails 7.x to Grails 8.
+
+[TIP]
+====
+**Before you start: add the Spring Boot properties migrator.**
+It is the fastest way to find deprecated or relocated configuration properties in your `application.yml` / `application.groovy`.
+Add it as a `runtimeOnly` dependency for the duration of your migration:
+
+[source,groovy]
+.build.gradle
+----
+runtimeOnly 'org.springframework.boot:spring-boot-properties-migrator'
+----
+
+Boot the application once; the migrator logs warnings for every deprecated property it finds and, in many cases, applies the rename automatically at runtime so the app keeps starting.
+Remove the dependency once your configuration is clean.
+====
+
+[TIP]
+====
+**Let your coding agent work through this guide.**
+Grails publishes the `grails-8-upgrade` agent skill, which turns this guide into a migration checklist for an AI coding agent.
+Extract it with the SkillsJars Gradle plugin, as xref:gettingStarted#agentSkills[Agent Skills] describes.
+While the application is still on Grails 7, declare the skill with its version, since the Grails 7 BOM does not manage it:
+
+[source,groovy,subs="attributes"]
+.build.gradle
+----
+skill 'org.apache.grails.skills:grails-8-upgrade:{version}'
+----
+====
+
+==== 1. Java 21 Minimum Requirement
+
+Grails 8 requires a minimum of Java 21 to both build and run Grails applications.
+This is an increase from Grails 7, which required Java 17.
+Update your project's toolchain, CI pipelines, and deployment environments to use JDK 21 or later.
+
+===== 1.1 Gradle 9.7 Minimum Requirement
+
+The Grails 8 Gradle plugins require Gradle 9.7 or later.
+Grails 7 applications were generated with a Gradle 8.14.x wrapper, and a wrapper carried over from Grails 7 does not work with Grails 8.
+The Groovy compiler configuration that the Grails Gradle plugin sets up relies on the `groovyOptions.configurationScriptFile` property, which only exists from Gradle 9.7 on.
+On an older Gradle version `compileGroovy` fails with a `NoSuchMethodError` for `GroovyCompileOptions.getConfigurationScriptFile()`.
+
+Update the Gradle wrapper of your project as part of the upgrade:
+
+[,console,subs="attributes"]
+----
+./gradlew wrapper --gradle-version {gradleVersion}
+----
+
+Afterwards, check that the `distributionUrl` in `gradle/wrapper/gradle-wrapper.properties` points to the new version.
+Gradle 9 has breaking changes of its own that may affect your build scripts and other Gradle plugins you use; consult the https://docs.gradle.org/{gradleVersion}/userguide/upgrading_major_version_9.html[Gradle 9 upgrade guide].
+See also <<groovy-compiler-config-scripts,Generated Groovy Compiler Configuration Scripts>> if your build assigns a Groovy compiler configuration script itself.
+
+==== 2. Spring Boot 4.1.x
+
+Grails 8 upgrades from Spring Boot 3.5.x to Spring Boot 4.1.x.
+This crosses the Spring Boot 4 major release boundary and adopts the Spring Boot 4.1 managed stack used by Grails 8: Spring Framework 7.0.x, Spring Security 7.1.x, Spring Data 2026.0.x, Micrometer 1.17.x, Jackson 3.1.x, Tomcat 11.0.x, and Jakarta Servlet 6.1.
+The upgrade includes the Spring Boot 4 module split, removed Spring Framework 6 deprecations, and additional Spring Boot 4.1 removals of APIs and properties that were deprecated in Spring Boot 4.0.
+
+For full details, consult:
+
+1. https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-4.0-Migration-Guide[Spring Boot 4.0 Migration Guide]
+2. https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-4.0-Release-Notes[Spring Boot 4.0 Release Notes]
+3. https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-4.1-Release-Notes[Spring Boot 4.1 Release Notes]
+4. https://github.com/spring-projects/spring-framework/wiki/Spring-Framework-7.0-Release-Notes[Spring Framework 7.0 Release Notes]
+
+==== 3. Spring Boot Autoconfigure Modularization
+
+Spring Boot 4 split the monolithic `spring-boot-autoconfigure` module into domain-specific modules.
+Auto-configuration classes have moved to new packages.
+If your application imports or references auto-configuration classes directly, you will need to update those references.
+
+Notable module changes:
+
+* Web MVC auto-configuration classes moved to `org.springframework.boot:spring-boot-webmvc`
+* Servlet auto-configuration classes moved to `org.springframework.boot:spring-boot-servlet`
+* MongoDB auto-configuration classes moved to `org.springframework.boot:spring-boot-mongodb`
+* Spring Integration auto-configuration moved to `org.springframework.boot:spring-boot-integration`. An application that depends on `spring-integration-core` alone no longer gets Spring Boot's `integrationGlobalProperties` bean or its `spring.integration.*` properties; add `spring-boot-starter-integration`, or `spring-boot-integration` alongside your Spring Integration modules, to keep them.
+
+For example, if your code imports `MongoAutoConfiguration`:
+
+[source,groovy]
+----
+// Before (Grails 7 / Spring Boot 3.x)
+import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration
+
+// After (Grails 8 / Spring Boot 4.x)
+import org.springframework.boot.mongodb.autoconfigure.MongoAutoConfiguration
+----
+
+In addition to the auto-configuration class moves, two foundational interfaces were relocated out of nested packages and into `org.springframework.boot` directly:
+
+[cols="1,1", options="header"]
+|===
+| Before (Spring Boot 3.x)
+| After (Spring Boot 4.x)
+
+| `org.springframework.boot.env.EnvironmentPostProcessor`
+| `org.springframework.boot.EnvironmentPostProcessor`
+
+| `org.springframework.boot.BootstrapRegistry` and related types in `org.springframework.boot`
+| `org.springframework.boot.bootstrap.BootstrapRegistry`, `org.springframework.boot.bootstrap.BootstrapRegistryInitializer`, `org.springframework.boot.bootstrap.ConfigurableBootstrapContext`
+|===
+
+The old locations are deprecated but retained for upgrade ease.
+If your application or plugin contributes an `EnvironmentPostProcessor` or `BootstrapRegistryInitializer`, update both the import and the corresponding `META-INF/spring.factories` key:
+
+[source,properties]
+.META-INF/spring.factories - Before
+----
+org.springframework.boot.env.EnvironmentPostProcessor=com.example.MyPostProcessor
+----
+
+[source,properties]
+.META-INF/spring.factories - After
+----
+org.springframework.boot.EnvironmentPostProcessor=com.example.MyPostProcessor
+----
+
+==== 4. Spring Boot Configuration Property Changes
+
+===== 4.1 MongoDB Configuration
+
+Spring Boot 4 renamed the MongoDB configuration property namespace for Spring Boot's own auto-configuration.
+If your `application.yml` or `application.groovy` uses `spring.data.mongodb.*` properties for Spring Boot auto-configuration, you must rename them to `spring.mongodb.*`.
+Note that Grails GORM for MongoDB uses its own `mongodb.*` configuration namespace, which is unaffected by this change.
+
+[source,yaml]
+.application.yml - Before (Grails 7)
+----
+spring:
+ data:
+ mongodb:
+ host: localhost
+ port: 27017
+ database: mydb
+----
+
+[source,yaml]
+.application.yml - After (Grails 8)
+----
+spring:
+ mongodb:
+ host: localhost
+ port: 27017
+ database: mydb
+----
+
+[[multipart-upload-configuration]]
+===== 4.2 Multipart Upload Configuration
+
+The `grails.controllers.upload.\*` configuration properties are no longer supported.
+Applications that still define any property under `grails.controllers.upload` fail at startup with migration instructions.
+This startup check is a migration aid for Grails 8 only and will be removed in Grails 9, after which leftover `grails.controllers.upload` properties are silently ignored.
+Move those settings to Spring Boot's `spring.servlet.multipart.*` namespace:
+
+[source,yaml]
+.application.yml - Before (Grails 7)
+----
+grails:
+ controllers:
+ upload:
+ maxFileSize: 200000
+ maxRequestSize: 200000
+----
+
+[source,yaml]
+.application.yml - After (Grails 8)
+----
+spring:
+ servlet:
+ multipart:
+ maxFileSize: 200MB
+ maxRequestSize: 200MB
+----
+
+Spring Boot also provides `spring.servlet.multipart.location`, `spring.servlet.multipart.fileSizeThreshold`, `spring.servlet.multipart.enabled`, `spring.servlet.multipart.resolveLazily`, and `spring.servlet.multipart.strictServletCompliance` as replacements for the corresponding legacy settings. See the {springBootReference}../appendix/application-properties/index.html[Spring Boot multipart application properties] reference for the complete list.
+
+Unlike the Grails 7 default, the multipart location is not set to `System.getProperty("java.io.tmpdir")`; when `spring.servlet.multipart.location` is not configured, the resulting `MultipartConfigElement` has an empty location and uploads use the servlet container's temporary directory. This can matter when the container's temporary storage is constrained or when an application expects uploaded files in `java.io.tmpdir`.
+When no upload limits are configured, Spring Boot's defaults apply: 1MB per file and 10MB per request. Set `spring.servlet.multipart.maxFileSize` and `spring.servlet.multipart.maxRequestSize` explicitly if your application requires different limits.
+
+==== 5. Hibernate ORM Package Relocations
+
+Spring Framework 7 removed the `org.springframework.orm.hibernate5` package entirely.
+Grails 8 vendors these classes from Spring Framework 6.2.x into `grails-data-hibernate5-spring-orm` and `grails-data-hibernate7-spring-orm` so that both Hibernate 5 and Hibernate 7 users have a drop-in replacement.
+
+This change is transparent for most applications since Grails manages the Hibernate integration internally.
+However, if your application directly imports any of the following classes, you must update your import statements based on which Hibernate version you are using.
+
+===== 5.1 Hibernate 5 (Default)
+
+If your application uses the default Grails Hibernate 5 integration (`org.apache.grails:grails-hibernate5` / `grails-data-hibernate5-spring-orm`), replace the `org.springframework.orm.hibernate5` package prefix with `org.grails.orm.hibernate.support.hibernate5`:
+
+[cols="1,1", options="header"]
+|===
+| Before (Spring Framework 6 / Grails 7)
+| After (Grails 8 — Hibernate 5)
+
+| `org.springframework.orm.hibernate5.HibernateTemplate`
+| `org.grails.orm.hibernate.support.hibernate5.HibernateTemplate`
+
+| `org.springframework.orm.hibernate5.HibernateTransactionManager`
+| `org.grails.orm.hibernate.support.hibernate5.HibernateTransactionManager`
+
+| `org.springframework.orm.hibernate5.LocalSessionFactoryBean`
+| `org.grails.orm.hibernate.support.hibernate5.LocalSessionFactoryBean`
+
+| `org.springframework.orm.hibernate5.SessionFactoryUtils`
+| `org.grails.orm.hibernate.support.hibernate5.SessionFactoryUtils`
+
+| `org.springframework.orm.hibernate5.SessionHolder`
+| `org.grails.orm.hibernate.support.hibernate5.SessionHolder`
+
+| `org.springframework.orm.hibernate5.HibernateCallback`
+| `org.grails.orm.hibernate.support.hibernate5.HibernateCallback`
+
+| `org.springframework.orm.hibernate5.support.OpenSessionInViewInterceptor`
+| `org.grails.orm.hibernate.support.hibernate5.support.OpenSessionInViewInterceptor`
+|===
+
+All other classes from `org.springframework.orm.hibernate5` follow the same pattern — replace the `org.springframework.orm.hibernate5` prefix with `org.grails.orm.hibernate.support.hibernate5`.
+
+===== 5.2 Hibernate 7
+
+If your application has opted in to Hibernate 7 (`org.apache.grails:grails-hibernate7` / `grails-data-hibernate7-spring-orm`), the equivalent vendored classes live under `org.grails.orm.hibernate.support.hibernate7`:
+
+[cols="1,1", options="header"]
+|===
+| Before (Spring Framework 6 / Grails 7)
+| After (Grails 8 — Hibernate 7)
+
+| `org.springframework.orm.hibernate5.HibernateTemplate`
+| `org.grails.orm.hibernate.support.hibernate7.HibernateTemplate`
+
+| `org.springframework.orm.hibernate5.HibernateTransactionManager`
+| `org.grails.orm.hibernate.support.hibernate7.HibernateTransactionManager`
+
+| `org.springframework.orm.hibernate5.LocalSessionFactoryBean`
+| `org.grails.orm.hibernate.support.hibernate7.LocalSessionFactoryBean`
+
+| `org.springframework.orm.hibernate5.SessionFactoryUtils`
+| `org.grails.orm.hibernate.support.hibernate7.SessionFactoryUtils`
+
+| `org.springframework.orm.hibernate5.SessionHolder`
+| `org.grails.orm.hibernate.support.hibernate7.SessionHolder`
+
+| `org.springframework.orm.hibernate5.HibernateCallback`
+| `org.grails.orm.hibernate.support.hibernate7.HibernateCallback`
+
+| `org.springframework.orm.hibernate5.support.OpenSessionInViewInterceptor`
+| `org.grails.orm.hibernate.support.hibernate7.support.OpenSessionInViewInterceptor`
+|===
+
+All other classes follow the same pattern — replace the `org.springframework.orm.hibernate5` prefix with `org.grails.orm.hibernate.support.hibernate7`.
+
+NOTE: See <<_hibernate_5_to_hibernate_7_migration>> below if you are also upgrading from Hibernate 5 to Hibernate 7 as part of this Grails 8 migration.
+
+==== 6. HttpStatus.MOVED_TEMPORARILY Removed
+
+Spring Framework 7 removed the deprecated `HttpStatus.MOVED_TEMPORARILY` constant.
+Use `HttpStatus.FOUND` instead - both represent HTTP 302 with no behavioral change.
+
+If your application references `HttpStatus.MOVED_TEMPORARILY` directly (for example, in custom redirect logic or interceptors), update the reference:
+
+[source,groovy]
+----
+// Before
+import org.springframework.http.HttpStatus
+response.status = HttpStatus.MOVED_TEMPORARILY.value()
+
+// After
+import org.springframework.http.HttpStatus
+response.status = HttpStatus.FOUND.value()
+----
+
+[[micronaut-integration]]
+==== 7. Micronaut Integration
+
+The Grails Micronaut plugin and its BOMs are now maintained and released from the https://github.com/apache/grails-micronaut[Apache Grails Micronaut repository].
+Applications using Grails Micronaut should follow that project's upgrade and dependency-management documentation.
+
+==== 8. Enum Serialization Default Changed
+
+As announced in the Grails 7.0.2 deprecation notice, the `SimpleEnumMarshaller` is now the default for JSON and XML enum serialization in Grails 8.
+Enums are serialized as simple string values (e.g., `"SUBMIT"`) instead of the verbose legacy format with type metadata.
+
+If you previously opted in via configuration, you can now remove it:
+
+[source,yaml]
+.application.yml - this is now the default and can be removed
+----
+grails:
+ converters:
+ json:
+ enum:
+ format: simple
+ xml:
+ enum:
+ format: simple
+----
+
+The legacy `org.grails.web.converters.marshaller.json.EnumMarshaller` and `org.grails.web.converters.marshaller.xml.EnumMarshaller` classes were removed in Grails 8.
+There is no Grails 8 configuration switch that restores the verbose enum-object shape.
+If an external API contract still requires that shape, register a custom object marshaller explicitly.
+
+[[jackson3-default]]
+==== 9. Jackson 3 is the New Default
+
+Spring Boot 4 ships Jackson 3 (`tools.jackson.*`) and auto-configures a `JsonMapper` bean instead of the Jackson 2 `ObjectMapper`.
+Grails 8 follows that change: any Grails module that previously declared `com.fasterxml.jackson.core:jackson-databind` (Jackson 2) now declares `tools.jackson.core:jackson-databind` (Jackson 3.1.x via the Spring Boot 4.1 BOM).
+
+**What stayed the same:**
+
+* **Jackson annotations.** All `@JsonProperty`, `@JsonCreator`, `@JsonIgnore`, `@JsonInclude`, `@JsonIgnoreProperties`, etc. remain at `com.fasterxml.jackson.annotation.*`.
+The Spring Boot 4 BOM explicitly permits the `jackson-annotations` 2.x artifact alongside the Jackson 3 BOM, so existing annotated DTOs and domain classes do **not** need to change.
+* The `readTree(String)`, `writeValueAsString(...)`, and `readValue(...)` method names on the mapper are unchanged.
+
+**What changed (and what you need to do if your code touches Jackson directly):**
+
+[cols="1,2,2",options="header"]
+|===
+| Concern | Jackson 2 | Jackson 3
+
+| Package
+| `com.fasterxml.jackson.databind.*`
+| `tools.jackson.databind.*`
+
+| Default mapper type
+| `ObjectMapper`
+| `tools.jackson.databind.json.JsonMapper`
+
+| Construction
+| `new ObjectMapper()`
+| `JsonMapper.builder().build()` (immutable; configuration locked after `build()`)
+
+| Exceptions
+| `JsonProcessingException` / `IOException` (checked)
+| `JacksonException` extends `RuntimeException` (unchecked)
+
+| Default date format
+| Numeric timestamps
+| ISO-8601 strings
+|===
+
+**If you inject the auto-configured mapper:**
+Spring Boot 4 provides a `tools.jackson.databind.json.JsonMapper` bean instead of `com.fasterxml.jackson.databind.ObjectMapper`.
+Update injection points to expect `JsonMapper`.
+
+**If you must stay on Jackson 2 temporarily:**
+Spring Boot 4 still manages the Jackson 2 BOM and provides an opt-in toggle so the auto-configured mapper preserves Jackson 2 defaults:
+
+[source,yaml]
+.application.yml
+----
+spring:
+ jackson:
+ use-jackson2-defaults: true
+----
+
+This is intended as a migration aid only; new code should target Jackson 3.
+
+**Spring Boot Jackson helper class renames.**
+If your code uses Spring Boot's Jackson helpers, rename them to the Jackson 3 equivalents:
+
+[cols="1,1", options="header"]
+|===
+| Spring Boot 3.x (Jackson 2)
+| Spring Boot 4.x (Jackson 3)
+
+| `Jackson2ObjectMapperBuilderCustomizer`
+| `JsonMapperBuilderCustomizer`
+
+| `JsonObjectSerializer`
+| `ObjectValueSerializer`
+
+| `JsonValueDeserializer`
+| `ObjectValueDeserializer`
+
+| `@JsonComponent`
+| `@JacksonComponent`
+
+| `@JsonMixin`
+| `@JacksonMixin`
+|===
+
+**Configuration property renames.**
+The `spring.jackson.*` namespace was reorganized.
+The `spring-boot-properties-migrator` (see the tip at the top of this guide) will detect most of these and warn at boot time:
+
+[cols="1,1", options="header"]
+|===
+| Before
+| After
+
+| `spring.jackson.read.*`
+| `spring.jackson.json.read.*`
+
+| `spring.jackson.write.*`
+| `spring.jackson.json.write.*`
+
+| `spring.jackson.parser.*`
+| `spring.jackson.json.read.*` (where equivalents exist)
+|===
+
+**Module auto-detection.**
+Jackson 3 auto-detects all Jackson modules on the classpath by default.
+If you need to disable this — for example, to avoid an unwanted module being picked up — set:
+
+[source,yaml]
+.application.yml
+----
+spring:
+ jackson:
+ find-and-modules: false
+----
+
+==== 10. Theme Support Removed
+
+Spring Framework 7 removed the theme infrastructure entirely.
+The following theme-specific classes and interfaces no longer exist:
+
+* `org.springframework.ui.context.ThemeSource`
+* `org.springframework.ui.context.Theme`
+* `org.springframework.ui.context.support.SimpleTheme`
+* `org.springframework.web.servlet.theme.SessionThemeResolver`
+
+NOTE: `JstlUtils` itself still exists in Spring WebMVC 7.0, but its theme-related methods have been removed.
+
+If your application uses Spring theme resolution (for example, switching CSS stylesheets via `ThemeResolver`), you must replace this with your own implementation.
+This was deprecated in Spring Framework 6.0 and fully removed in 7.0.
+
+GSP layouts and views that relied on theme resolution will need to use alternative approaches such as configuration properties or session-based preferences managed in application code.
+
+==== 11. Embedded Server Module Relocations
+
+Spring Boot 4 reorganized embedded server classes into separate modules.
+If your application or tests reference these classes directly, update the imports:
+
+[cols="1,1", options="header"]
+|===
+| Before (Spring Boot 3.x / Grails 7)
+| After (Spring Boot 4.x / Grails 8)
+
+| `org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory`
+| `org.springframework.boot.tomcat.servlet.TomcatServletWebServerFactory`
+
+| `org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory`
+| `org.springframework.boot.web.server.servlet.ConfigurableServletWebServerFactory`
+
+| `org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext`
+| `org.springframework.boot.web.server.servlet.context.AnnotationConfigServletWebServerApplicationContext`
+
+| `org.springframework.boot.web.context.WebServerApplicationContext`
+| `org.springframework.boot.web.server.context.WebServerApplicationContext`
+
+| `org.springframework.boot.web.servlet.context.AnnotationConfigServletWebApplicationContext`
+| `org.springframework.boot.web.context.servlet.AnnotationConfigServletWebApplicationContext`
+|===
+
+Applications using embedded Tomcat or Jetty should check for any direct class references and update accordingly.
+The `spring-boot-tomcat` module must now be an explicit dependency if you reference Tomcat classes directly.
+
+**Undertow support is now provided by the Grails Undertow plugin.**
+Spring Boot 4 removed its Undertow support (`spring-boot-starter-undertow`) before Undertow shipped Servlet 6.1 compatibility.
+Undertow has since released Servlet 6.1 support, and Grails 8 restores Undertow as an embedded servlet container through the `grails-undertow` plugin, which bundles the Spring Boot Undertow web server support.
+Applications that previously used `spring-boot-starter-undertow` should replace it with:
+
+[source,groovy]
+----
+implementation 'org.apache.grails:grails-undertow'
+----
+
+The existing `server.undertow.*` configuration properties continue to work.
+Note that `server.undertow.max-http-post-size` now defaults to 2MB, matching Undertow's hardened default (CVE-2024-3884, CVE-2024-4027); set it to `-1` to restore the previous unlimited behavior.
+The Grails Forge generator offers Undertow as a selectable servlet implementation again (for example, `--servlet=undertow` on the API/CLI, or the `grails-undertow` feature).
+
+==== 12. HandlerAdapter.getLastModified Removed
+
+Spring Framework 7 removed the deprecated `getLastModified` method from the `HandlerAdapter` interface.
+If your application implements `HandlerAdapter` directly and overrides this method, remove the override.
+The framework no longer calls this method for Last-Modified header management.
+
+==== 13. Spring Security Filter Ordering
+
+Spring Boot 4 removed the `SecurityProperties.DEFAULT_FILTER_ORDER` constant.
+Spring Security is moving toward the fluent `HttpSecurity` configuration API for filter chain management, rather than explicit filter ordering via constants.
+
+If your application references `DEFAULT_FILTER_ORDER` for custom filter positioning, replace it with the concrete value `-100` (computed as `OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100`).
+Longer term, consider migrating to the fluent `HttpSecurity` API for filter chain configuration.
+
+==== 14. Spring Dependency Management Plugin Replaced by Gradle Platforms
+
+Grails 8 standardizes on Gradle's native `platform()` dependency management and **no longer applies the `io.spring.dependency-management` plugin**.
+The Grails Gradle Plugin now contributes `grails-bom` as a Gradle `platform()` to eligible declarable project configurations, and a new bundled plugin (`org.apache.grails.gradle.bom-property-overrides`, applied automatically by the Grails Gradle Plugin) preserves the property-based version-override workflow that Spring DM provided.
+The platform is contributed lazily, when a configuration's dependencies are observed (through resolution, publication, or `incoming.dependencies`), so configurations populated on demand through `defaultDependencies`, such as the Grails `profile` configuration, keep their defaults.
+Dedicated tool and annotation-processor classpaths, including the `jacoco` plugin's `jacocoAgent` and `jacocoAnt` configurations, are excluded from automatic platform application so the application BOM does not change their transitive dependency versions.
+Until dependencies are observed, the auto-applied platform is not visible in a configuration's declared `dependencies` or `allDependencies`; build logic that looks for it should inspect `incoming.dependencies` or the resolution result instead.
+
+**No action is required for most applications.**
+The standard `gradle.properties` and `ext['…']` override forms continue to work exactly as before:
+
+[source,groovy]
+.build.gradle
+----
+ext['slf4j.version'] = '2.0.9'
+----
+
+[source,properties]
+.gradle.properties
+----
+slf4j.version=2.0.9
+----
+
+The `grails { springDependencyManagement = … }` flag on `GrailsExtension` is deprecated.
+For backward compatibility, setting it to `false` is still honored and is equivalent to `grails { bom = null }`: it suppresses the automatic Grails BOM `platform()` application, just as it previously prevented the Spring Dependency Management BOM from being applied.
+New builds should use `grails { bom = null }` instead.
+
+**Two Spring DM features have no automatic migration.**
+If your `build.gradle` uses either of the patterns below, update it as follows:
+
+[cols="2,3", options="header"]
+|===
+| Spring DM pattern (Grails 7)
+| Grails 8 replacement
+
+| `dependencyManagement { dependencies { dependency 'group:artifact:version' } }` to pin arbitrary non-BOM dependency versions
+| `dependencies { implementation 'group:artifact:version' }` for a direct dependency, or `configurations.all { resolutionStrategy.force 'group:artifact:version' }` to force a transitive version
+
+| Version-range strings (e.g. `1.+`, `[1.0,2.0)`) embedded in BOM `<properties>` values, resolved by Spring DM's own resolver
+| Now applied as Gradle strict version constraints, which use Gradle's range semantics. Concrete versions are unaffected. Only relevant if you consume a custom BOM whose `<properties>` block contains range strings.
+|===
+
+**Behavioural difference to be aware of: conflict resolution.**
+The BOM's *default* managed versions are applied via a regular Gradle `platform()`, which participates in standard conflict resolution (highest-version-wins).
+A transitive dependency can therefore pull a non-overridden managed version higher than the BOM default.
+If you require Spring DM's "BOM wins always" behaviour for the default managed versions, declare `enforcedPlatform("org.apache.grails:grails-bom:$grailsVersion")` instead of relying on the auto-applied non-enforced platform.
+
+An *explicit* property override (`ext['…']` or `gradle.properties`) is applied as a strict constraint and always wins - including when it downgrades a version - so overrides behave as they did under Spring DM.
+Overriding a property that selects an imported BOM's version (for example `spring-boot.version`) re-imports that BOM at the overridden version and applies its updated managed set.
+
+**Grails BOMs now follow the upstream BOM property names.**
+Where a Grails BOM overrides a version that an upstream BOM also manages - `spring-boot-dependencies`, or a BOM Spring Boot imports - it declares the override under the upstream BOM's own property name.
+One property therefore sets the version in both BOMs, and the property names in the Spring Boot documentation work unchanged in a Grails build.
+For a module Spring Boot manages through an imported BOM, that is the property Spring Boot imports the BOM with: `jackson-bom.version` moves every Jackson 3 module, whether `grails-bom` pins it or not.
+
+An override under a property name no BOM declares is silently ignored, so rename any Grails-specific property your build sets in `gradle.properties` or `ext['…']`, along with a Jackson 2 version set under Spring Boot 3's property name:
+
+[cols="1,2", options="header"]
+|===
+| Grails 7 property
+| Grails 8 property
+
+| `jackson.version`
+| `jackson-2-bom.version` for Jackson 2 (`com.fasterxml.jackson.*`). Jackson 3 (`tools.jackson.*`), the new default, is set by `jackson-bom.version`.
+
+| `jackson-bom.version` (Spring Boot 3's name for Jackson 2)
+| `jackson-2-bom.version`. In Grails 8, `jackson-bom.version` sets Jackson 3, so a Jackson 2 version there makes dependency resolution fail.
+|===
+
+Builds that adopted a Grails 8 milestone or release candidate should rename `jackson2.version` to `jackson-2-bom.version`, `jackson3.version` to `jackson-bom.version`, and, with `grails-neo4j-bom`, `neo4j-driver.version` to `neo4j-java-driver.version`.
+
+**Selecting or opting out of the auto-applied BOM.**
+The Grails Gradle plugin applies a single Grails BOM automatically, selected by the `grails.bom` property. Its value is the BOM artifact name within the `org.apache.grails` group, which the plugin resolves as `org.apache.grails:$bom:$grailsVersion`.
+It defaults to `grails-bom`, which preserves the Grails 7 behaviour and is the right choice for the vast majority of applications.
+Exactly one Grails BOM is ever applied; the BOMs are split by integration, so the plugin never layers two of them.
+
+Set it to `null` to suppress the automatic BOM application entirely - for example when you intentionally want to manage Grails dependency versions yourself (consuming Grails modules from a different curated platform):
+
+[source,groovy]
+.build.gradle
+----
+grails {
+ bom = null
+}
+----
+
+When set to `null`, the Grails Gradle plugin will not declare a Grails `platform()`/`enforcedPlatform()` on your configurations and will not apply the `org.apache.grails.gradle.bom-property-overrides` plugin.
+You are responsible for declaring the BOM yourself and, if you still want `gradle.properties` / `ext['...']` overrides, applying `id 'org.apache.grails.gradle.bom-property-overrides'` explicitly.
+
+==== 15. Spring Boot Starter Renames
+
+Spring Boot 4 renamed several starters as part of its modularization effort.
+If your `build.gradle` references any of the following, update the artifact id:
+
+[cols="1,1", options="header"]
+|===
+| Before (Spring Boot 3.x)
+| After (Spring Boot 4.x)
+
+| `spring-boot-starter-web`
+| `spring-boot-starter-webmvc`
+
+| `spring-boot-starter-aop`
+| `spring-boot-starter-aspectj`
+
+| `spring-boot-starter-web-services`
+| `spring-boot-starter-webservices`
+
+| `spring-boot-starter-oauth2-authorization-server`
+| `spring-boot-starter-security-oauth2-authorization-server`
+
+| `spring-boot-starter-oauth2-client`
+| `spring-boot-starter-security-oauth2-client`
+
+| `spring-boot-starter-oauth2-resource-server`
+| `spring-boot-starter-security-oauth2-resource-server`
+|===
+
+[source,groovy]
+.build.gradle - Before
+----
+implementation 'org.springframework.boot:spring-boot-starter-web'
+implementation 'org.springframework.boot:spring-boot-starter-aop'
+----
+
+[source,groovy]
+.build.gradle - After
+----
+implementation 'org.springframework.boot:spring-boot-starter-webmvc'
+implementation 'org.springframework.boot:spring-boot-starter-aspectj'
+----
+
+NOTE: If you want a faster, lower-friction migration that pulls in *all* Spring Boot modules without picking starters individually, Spring Boot 4 ships `spring-boot-starter-classic` (and `spring-boot-starter-test-classic`) as a transitional fallback.
+This is intended as a stopgap; new code should target the modular starters.
+
+==== 16. WAR Deployment Uses spring-boot-starter-tomcat-runtime
+
+For WAR deployment to an external Servlet container, Spring Boot 4 introduced a dedicated `spring-boot-starter-tomcat-runtime` artifact that contributes only the integration classes needed to start under an external container, without bundling the embedded Tomcat distribution into the WAR.
+
+Replace the previous "change scope to `provided`/`testImplementation`" idiom with the new starter:
+
+[source,groovy]
+.build.gradle - Before
+----
+providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
+----
+
+[source,groovy]
+.build.gradle - After
+----
+providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat-runtime'
+----
+
+The Grails deployment guides have been updated to reflect this idiom.
+Embedded Tomcat usage (the default for `grails run-app` and bootable WARs) continues to use `spring-boot-starter-tomcat` unchanged.
+
+==== 17. Test Infrastructure Changes
+
+Spring Boot 4 made several breaking changes to its test infrastructure.
+Most Grails tests use `GrailsUnitTest`, `GrailsWebUnitTest`, and `Integration` and are unaffected, but if your application uses `@SpringBootTest` directly the following apply.
+
+**`@SpringBootTest` no longer auto-configures `MockMvc`, `WebClient`, or `TestRestTemplate`.**
+Add the corresponding `@AutoConfigureMockMvc` / `@AutoConfigureWebClient` / `@AutoConfigureTestRestTemplate` annotations to opt in.
+
+[source,groovy]
+----
+// Before
+@SpringBootTest
+class MyControllerSpec extends Specification {
+ @Autowired MockMvc mockMvc // injected automatically
+ @Autowired TestRestTemplate rest // injected automatically
+}
+
+// After
+@SpringBootTest
+@AutoConfigureMockMvc
+@AutoConfigureTestRestTemplate
+class MyControllerSpec extends Specification {
+ @Autowired MockMvc mockMvc
+ @Autowired TestRestTemplate rest
+}
+----
+
+**`@MockBean` and `@SpyBean` were removed.**
+Replace them with `@MockitoBean` and `@MockitoSpyBean` from `org.springframework.test.context.bean.override.mockito`.
+The new annotations work as fields in test classes only — they cannot be declared in `@Configuration` classes.
+
+[source,groovy]
+----
+// Before
+import org.springframework.boot.test.mock.mockito.MockBean
+@SpringBootTest
+class MyServiceSpec extends Specification {
+ @MockBean BookRepository repo
+}
+
+// After
+import org.springframework.test.context.bean.override.mockito.MockitoBean
+@SpringBootTest
+class MyServiceSpec extends Specification {
+ @MockitoBean BookRepository repo
+}
+----
+
+**`MockitoTestExecutionListener` was removed.**
+If your test infrastructure registers it explicitly, remove the registration; Spring's bean override support handles `@MockitoBean` directly.
+
+**`TestRestTemplate` package change.**
+`TestRestTemplate` moved to `org.springframework.boot.resttestclient`.
+Update the import.
+A new `RestTestClient` and corresponding `@AutoConfigureRestTestClient` annotation are also available as a fluent alternative.
+
+===== 17.1 Test Helpers Moved to Test Fixtures
+
+Several legacy Grails test helpers are no longer included in the production classpath.
+They are published as Gradle test fixtures instead, so applications and plugins that use them directly must request the fixture variant explicitly.
+
+This affects the following helpers:
+
+* `grails.plugin.json.view.test.JsonViewTest` and related JSON view test helpers
+* `org.grails.gorm.graphql.testing.GraphQLSchemaSpec`
+* `org.grails.gorm.graphql.testing.MockDataFetchingEnvironment`
+* `grails.util.GrailsWebMockUtil`
+* Mock resource and plugin helpers from `grails-core`, including `MockResourceLoader`, `MockStringResourceLoader`, `MockFileResource`, `MockPluginDiscovery`, and `MockGrailsPluginManager`
+
+If your tests import one of these classes, add the corresponding `testFixtures(...)` dependency to the configuration that compiles those tests:
+
+[source,groovy]
+.build.gradle
+----
+dependencies {
+ testImplementation testFixtures('org.apache.grails:grails-core')
+ testImplementation testFixtures('org.apache.grails.web:grails-web-common')
+ testImplementation testFixtures('org.apache.grails:grails-views-gson')
+ testImplementation testFixtures('org.apache.grails.data:grails-data-graphql-core')
+}
+----
+
+Only add the fixture dependencies that provide helpers used by the project.
+Do not add them to `implementation`, because these artifacts contain test infrastructure and should not be part of the application runtime classpath.
+
+==== 18. DevTools Live Reload Disabled by Default
+
+Spring Boot 4 changed the default of `spring.devtools.livereload.enabled` from `true` to `false`.
+If you rely on browser live reload during development, opt in explicitly under the development environment so non-development environments still honor the new Spring Boot 4 default:
+
+[source,yaml]
+.application-development.yml
+----
+spring:
+ devtools:
+ livereload:
+ enabled: true
+----
+
+NOTE: Apps generated by the Grails Forge with the `spring-boot-devtools` reloading option **do** set this property automatically in `application-development.yml`, restoring Grails 7 livereload behavior for the dev profile only.
+You can opt out by changing the value to `false` or by deleting the `application-development.yml` block after generation.
+Existing Grails 7 applications that opt in to devtools must add this configuration manually.
+
+==== 19. Spring Retry No Longer Managed
+
+Spring Boot 4 removed `spring-retry` from its managed dependencies.
+Spring for Apache Kafka and Spring AMQP have moved off Spring Retry to Spring Framework's new retry support; if you used Spring Retry transitively through those projects you may not need it any more.
+
+If your application *directly* uses `@Retryable`, `@EnableRetry`, or `@Recover`, declare the dependency explicitly in `build.gradle`:
+
+[source,groovy]
+.build.gradle
+----
+implementation 'org.springframework.retry:spring-retry'
+----
+
+NOTE: The `grails-bom` pins a known-good Spring Retry version (`2.0.x`), so you do not need to specify a version when your build uses the Grails BOM, whether it is auto-applied by the Grails Gradle plugin or declared explicitly.
+Override the BOM-managed version in your build if you need a newer release.
+
+==== 20. Other Default Behavior Changes
+
+Spring Boot 4.0 and 4.1 made several smaller default-behavior changes that you may notice but rarely require code changes:
+
+* **Spring Boot 4.1 removes Spring Boot 4.0 deprecations.**
+If you tested against an earlier Grails 8 snapshot or Spring Boot 4.0.x directly, remove any use of APIs, methods, or configuration properties that were only deprecated there before moving to the current Grails 8 line.
+
+* **The Spring Boot `BuildInfo` task writes `META-INF/build-info.properties` by default.**
+If your build, packaging, or tests read `build-info.properties` from the root of the generated resources directory, update them to read `META-INF/build-info.properties` or configure the task's `filename` property.
+
+* **Spring Data JPA repository bootstrap modes were tightened.**
+Grails GORM is unaffected, but applications that also use Spring Data JPA directly should review any `spring.data.jpa.repositories.bootstrap-mode` setting when moving to Spring Boot 4.1.
+
+* **Derby support is deprecated in Spring Boot.**
+Grails does not use Derby by default, but applications that added Derby through Spring Boot auto-configuration should plan a migration to H2, HSQLDB, or another supported database.
+
+* **Logback default charset is now `UTF-8`** for log files (aligning with the existing Log4j2 default).
+Console output uses `Console#charset()` if available, otherwise `UTF-8`.
+If your log scraping tooling assumed a platform-default charset, switch it to UTF-8.
+
+* **Liveness and readiness probes are enabled by default** on the Health endpoint.
+The `liveness` and `readiness` health groups are exposed automatically.
+To disable, set:
++
+[source,yaml]
+.application.yml
+----
+management:
+ endpoint:
+ health:
+ probes:
+ enabled: false
+----
+
+* **`HttpMessageConverters` is deprecated.**
+If your application contributed `HttpMessageConverter` beans through this class, switch to the new `ClientHttpMessageConvertersCustomizer` and `ServerHttpMessageConvertersCustomizer` interfaces.
+
+* **JSpecify nullability annotations.**
+Spring Framework 7 deprecated `org.springframework.lang.Nullable` and `org.springframework.lang.NonNull` in favor of the JSpecify annotations (`org.jspecify.annotations.Nullable`, `org.jspecify.annotations.NonNull`).
+The Spring annotations still work, so this is non-blocking, but new code should prefer the JSpecify equivalents.
+
+* **`Resource[]` values expand location patterns.**
+A `classpath*:` or other location pattern converted to `Resource[]` now resolves to every matching resource, or to an empty array when nothing matches, as it does in a plain Spring application. Previously Grails' conversion of a `String` to a `Resource` also handled `Resource[]` values one element at a time, so `classpath*:META-INF/spring.integration.properties` became a single resource with the pattern as its path, and loading it failed when it was opened. This applies to `Resource[]` [...]
+A list or array of locations is also collected into a set, as Spring does: a list that names the same location twice now gives one resource instead of two, while a comma-delimited String keeps both. A `null` element in a list or array now fails the conversion instead of becoming a `null` entry, so a bean property given such a list fails at startup.
+
+* **Configuration lists are exposed as indexed properties.**
+Non-empty lists loaded from `application.yml` or `application.groovy` are exposed to Spring's `Environment` through indexed names such as `app.names[0]`. This lets Spring Boot bind each element to its declared type and resolve placeholders inside scalar lists. Code that reads a whole list using `environment.getProperty('app.names', List)` should instead bind it with `@ConfigurationProperties` or `Binder.get(environment).bind('app.names', Bindable.listOf(String)).orElse([])`, using `Bind [...]
+The list itself is no longer a property of the `Environment`: `environment.getProperty('app.names', String[])` returns `null` and `environment.containsProperty('app.names')` returns `false`. A `@Value('${app.names}')` placeholder can no longer read the list either. Without a default, the application fails to start with `Could not resolve placeholder 'app.names'`; with a default, the placeholder resolves to the default, or to a single value of the same name from a lower-priority source, [...]
+
+* **Namespaced link generation is namespace-aware.**
+When a link, form action, pagination link, sortable column link, redirect, chain, or include targets a controller without an explicit `namespace`, Grails now resolves the namespace automatically. The name is resolved nearest scope first: the current request's namespace if it defines a controller with that name, then the non-namespaced controller, then the namespace of the only controller with that name. `controller` and `action` therefore generate the correct namespaced or non-namespace [...]
+
+* **A resource link targets the most specific controller serving its domain class.**
+A link, form or redirect built from a domain instance, such as `<g:link resource="${book}">`, `redirect book`, or the `self` link of a HAL, Atom or JSON:API response, previously always targeted the controller named after the domain class, even when that controller did not exist. It now targets the nearest controller serving the domain class, a controller serving it when it is named after it or extends `RestfulController` parameterised on it, such as `PeopleController extends RestfulCont [...]
+
+* **A read-only transaction no longer flushes the session.**
+A read-only transaction (`@ReadOnly`, `@Transactional(readOnly = true)`) commits without flushing the session on every GORM datastore. Hibernate, Neo4j and the simple map datastore already behaved this way; GORM for MongoDB flushed the session when a read-only transaction committed, and no longer does.
++
+So on MongoDB, a write saved without `flush: true` before read-only code ran in the same session used to be persisted as a side effect of the read. It is now left queued: the read-only transaction does not write it, and it is written by whatever flushes the session next (a read-write commit, `save(flush: true)`, the flush at the end of the request), or discarded when the session closes if nothing does. Flush such writes explicitly with `save(flush: true)`, or perform them in a read-writ [...]
++
+A GORM datastore implementation outside the Grails repository inherits this if it uses `SessionOnlyTransaction`; one that supplies its own `Transaction` can honour `readOnly` by overriding the new `AbstractSession.beginTransactionInternal(TransactionDefinition)`, which now receives the transaction definition instead of discarding it.
+
+* **A transaction started inside another joins it.**
+On GORM for MongoDB, a transactional service method called from another, or `withTransaction` inside `withTransaction`, began a second transaction on the same session instead of joining the first. The inner one committed on its own and the outer one's commit then did nothing: without a session bound for the request, the outer transaction's writes after the call were never saved, and with one they were saved when the request ended, outside any transaction (not at all if a read-only call [...]
++
+These follow from the surrounding transaction now being recognized, on MongoDB and the simple map datastore:
++
+** `PROPAGATION_REQUIRES_NEW` suspends the surrounding transaction and runs in a session of its own (on Neo4j too), where it used to begin on the surrounding transaction's session. The new session starts empty: an entity loaded in the surrounding transaction belongs to that session and should be loaded again inside, and settings made on the surrounding session, such as the database or collection chosen with `withDatabase` or `withCollection`, do not carry over.
+** `PROPAGATION_NOT_SUPPORTED` suspends the surrounding transaction, `PROPAGATION_MANDATORY` inside a transaction works where it always threw, and `PROPAGATION_NEVER` and `PROPAGATION_NESTED` inside a transaction throw.
+** A read-write transaction started inside a read-only one joins it and is read-only, as on Hibernate, where it used to commit on its own. A write it leaves queued is not saved by the read-only commit, which logs a warning naming the session. Call such a method from read-write code, or give it `PROPAGATION_REQUIRES_NEW`. A write it flushes explicitly with `save(flush: true)` is saved, but outside any transaction, so a later failure cannot roll it back.
+** Transactional code run from a transaction's `afterCommit` or `afterCompletion` callbacks, such as an `@TransactionalEventListener`, begins a transaction of its own.
+** A read-only transaction puts the session's flush mode back when it completes (on Neo4j too). It used to leave the session in `COMMIT` mode, so a session bound for the whole request was not flushed when the request ended.
+** Committing a transaction that is no longer active throws `IllegalTransactionStateException`, where the commit used to be skipped without a word.
++
+Without multi-document transactions, GORM for MongoDB does not flush before a query while a transaction is in progress, so a write a joined transaction leaves queued is not visible to a query later in the same transaction. It used to be, because the inner transaction flushed it when it returned. Use `save(flush: true)` where a later query in the transaction must see the write. This includes integration tests annotated with `@Rollback`, whose service calls now join the test's transaction [...]
++
+With multi-document transactions enabled on MongoDB, a read-only transaction no longer starts a server-side transaction, and beginning a transaction on a session whose server-side transaction is still active throws `IllegalTransactionStateException` instead of discarding it. See link:{mongodb5Guide}index.html#nestedTransactions[Nested Transactions] in the GORM for MongoDB guide.
++
+A GORM datastore implementation outside the Grails repository whose transaction manager replaces `doBegin` must handle a transaction object that holds no session: a `PROPAGATION_REQUIRES_NEW` transaction arrives that way once the surrounding one is suspended, and needs a session of its own.
+
+* **`bindData` can clear omitted included fields.**
+`bindData(target, source, [include: [...], clearMissing: true])` now clears included properties that are absent from the binding source. The behavior is opt-in, requires an `include` list, and does not apply globally. Existing `bindData` calls without `clearMissing: true` keep omitted fields unchanged.
+
+* **GORM for MongoDB builds its indexes when the datastore starts, not when it is created.**
+Creating a `MongoDatastore` no longer connects to MongoDB or builds the declared indexes, whichever constructor creates it, including one given an application's own `MongoClient`. In an application Spring starts the datastore before `BootStrap` runs, so nothing changes there; code that creates a `MongoDatastore` itself and expects its indexes once the constructor returns has to call `start()`, although the first GORM query or save on a datastore nothing has started also starts it. See l [...]
+
+* **GORM for MongoDB rejects Map criterion values that contain `$` keys.**
+`findWhere`, `findAllWhere`, criteria queries, the `where` DSL and dynamic finders now throw `InvalidDataAccessResourceUsageException` when a `Map` passed as a criterion value contains a key starting with `$` at any level, on any property type including enums. MongoDB interprets such a value document as an operator expression rather than as a value. Maps without such keys are still sent as literal subdocument comparisons, so exact matches on `Map` properties, dotted paths and array elem [...]
+
+* **GORM for MongoDB no longer ends the index build on a `unique` index over duplicate values.**
+A declared `unique` index that could not be built because documents already shared a value ended the index build with a `DuplicateKeyException`: the indexes declared after it were not built, and with the default synchronous build the application did not start. It is now counted as a failed declaration like any other index the server refuses, logged at `ERROR`, and the build goes on; the application starts without that index. Remove the duplicates and build the index again to create it. [...]
+
+* **GORM for MongoDB builds only the indexes of the domain classes mapped to each connection.**
+The index build of a named connection also created the indexes of classes mapped only to another connection, in its own database. Each connection now builds the indexes of the classes mapped to it, including those mapped to `ConnectionSource.ALL`. Indexes already created elsewhere are left in place. See link:{mongodb5Guide}index.html#upgradeNotes[Upgrade Notes] in the GORM for MongoDB guide.
+
+==== 21. Tag Library Test Cleanup Changes
+
+Grails 8 removes the `purgeTagLibMetaClass` test hook used by some web and TagLib unit tests.
+TagLib metaclass cleanup now happens automatically as part of the web test infrastructure, so test specs should delete any custom `purgeTagLibMetaClass` property or getter.
+
+If your tests use `TagLibUnitTest` and mock additional tag libraries with `mockTagLib(...)` or `mockTagLibs(...)`, those mocked tag libraries are rebuilt automatically between feature methods.
+No replacement flag is required.
+
+IMPORTANT: Mocked tag libraries are cleared after each feature method.
+If your tests call `mockTagLib` directly (for example, when implementing `GrailsWebUnitTest` instead of `TagLibUnitTest`), move the call from `setupSpec()` to `setup()` so the mock is re-applied before every feature.
+`TagLibUnitTest` handles this automatically, but `GrailsWebUnitTest` does not.
+
+[source,groovy]
+----
+// Before
+class MyTagLibSpec extends Specification implements TagLibUnitTest<MyTagLib> {
+ boolean getPurgeTagLibMetaClass() {
+ true
+ }
+}
+
+// After
+class MyTagLibSpec extends Specification implements TagLibUnitTest<MyTagLib> {
+}
+----
+
+==== 22. Method-based TagLib Handlers
+
+Grails 8 introduces method-based tag handler syntax as the recommended way to define tags. Closure-based handlers are still supported for backward compatibility.
+
+[source,groovy]
+----
+import grails.gsp.Tag
+
+class DemoTagLib {
+ static namespace = 'demo'
+
+ def greet(Map attrs) {
+ out << "Hello, ${attrs.name}!"
+ }
+
+ @Tag
+ def greeting(String name) {
+ out << "Hello, ${name}!"
+ }
+}
+----
+
+Method tags with the conventional signatures `def tag(Map attrs)`, `def tag(Closure body)`, and `def tag(Map attrs, Closure body)` are discovered automatically. Zero-argument method tags and method tags that bind named attributes directly to method parameters must use `@grails.gsp.Tag`; this avoids exposing ordinary public helper methods as tags.
+
+Grails Gradle application builds preserve Java and Groovy method parameter names by default (see §22.3 below).
+If you compile TagLib classes outside those plugins, enable Java `-parameters` and Groovy `groovyOptions.parameters = true` so `@Tag` methods can bind attributes by parameter name.
+
+To exclude a conventional public method from being exposed as a tag (for example, a helper that must remain public to satisfy an interface), annotate it with `@grails.gsp.NotATag`:
+
+[source,groovy]
+----
+import grails.gsp.NotATag
+
+class DemoTagLib {
+ def greet(Map attrs) {
+ out << "Hello, ${attrs.name}!"
+ }
+
+ @NotATag
+ def helper(Map attrs) { /* ... */ }
+}
+----
+
+The compile-time deprecation warning emitted for closure-based tag fields can be silenced by setting the system property `grails.taglib.warnDeprecatedClosures=false`.
+
+===== 22.1 Behavior change: tag method registration
+
+In Grails 7, the metaclass tag dispatchers registered for the taglib's own namespace did not override existing methods. Because method-based tags are now real methods on the TagLib class, those dispatchers must override methods of the same name so that function-style invocation (for example `tagLib.myTag(attrs)`) returns captured tag output rather than writing directly to `out`.
+
+If a TagLib intentionally defines a method that shares a name with a default-namespace tag in another TagLib, the locally defined method will be shadowed by the tag dispatcher. Rename the helper method or move it behind a different namespace if the previous behavior is required.
+
+This shadowing is not reported at runtime by default. To audit which TagLib methods are being overridden by tag dispatchers, enable `DEBUG` logging for `org.grails.taglib.TagLibraryMetaUtils` in `logback.xml` (or `logback-spring.xml`):
+
+[source,xml]
+----
+<logger name="org.grails.taglib.TagLibraryMetaUtils" level="DEBUG"/>
+----
+
+Each override is logged as `Registering tag dispatcher <namespace>:<tagName> over existing method <Class>.<method>(<paramTypes>)`. Inspect the output after application startup; any entry whose `<Class>` is one of your own TagLibs identifies a method that has been replaced by the dispatcher.
+
+===== 22.2 Behavior change: parameter-name binding for `Map` and `Closure` parameters
+
+Method-based tag handlers bind attributes to method parameters by parameter name. Two reserved names participate in this resolution:
+
+- A `Map`-typed parameter named `attrs` receives the full attributes map.
+- A `Closure`-typed parameter named `body` receives the tag body.
+
+In earlier iterations of the method-based handler implementation, a `Closure`-typed parameter was bound to the body regardless of its parameter name, while a `Map`-typed parameter required the literal name `attrs`. That asymmetry has been removed. Both reserved names are now applied consistently: a `Closure` parameter named anything other than `body` is treated as a normal named attribute (and must be supplied by name), just as a `Map` parameter named anything other than `attrs` is.
+
+If you have method-based tag handlers whose `Closure` parameter uses a name other than `body`, rename the parameter so the body binds as expected:
+
+[source,groovy]
+----
+import grails.gsp.Tag
+
+class DemoTagLib {
+
+ // Will NOT receive the tag body; `renderer` is treated as a named attribute.
+ @Tag
+ def before(Closure renderer) {
+ out << renderer.call()
+ }
+
+ // Receives the tag body.
+ @Tag
+ def after(Closure body) {
+ out << body.call()
+ }
+}
+----
+
+If parameter names are not preserved at compile time (see §22.3 below for the `preserveParameterNames` Gradle extension property), the first `Map` parameter is bound to `attrs` and the first `Closure` parameter is bound to `body` regardless of declared names, matching the behavior of closure-based tag handlers.
+
+===== 22.3 Grails Gradle Extension Preserves Parameter Names By Default
+
+In Grails 8, the Grails Gradle extension defaults `preserveParameterNames` to `true`.
+This configures Groovy compilation to retain method and constructor parameter names in generated class files.
+
+This behavior supports framework features that bind by parameter name, including method-based TagLib handlers annotated with `@grails.gsp.Tag`:
+
+[source,groovy]
+----
+import grails.gsp.Tag
+
+class DemoTagLib {
+ @Tag
+ def greeting(String name) {
+ out << "Hello, ${name}!"
+ }
+}
+----
+
+If you need the previous Groovy compiler behavior, disable it in `build.gradle`:
+
+[source,groovy]
+----
+grails {
+ preserveParameterNames = false
+}
+----
+
+NOTE: This Gradle extension property controls Groovy compilation only (`groovyOptions.parameters`).
+Java parameter-name preservation is enabled by the Spring Boot Gradle plugin, which adds `-parameters` to every `JavaCompile` task by default since Spring Boot 3.2. Grails 8 applications inherit this through the Spring Boot Gradle plugin and require no additional configuration for Java sources.
+
+If you compile TagLib classes outside the Grails Gradle plugin (for example, in a standalone Groovy module, a plain Spring Boot application that does not apply `org.springframework.boot`, or a build that disables the Spring Boot plugin's compiler configuration), enable parameter-name preservation explicitly so `@grails.gsp.Tag` methods can bind attributes by parameter name:
+
+[source,groovy]
+----
+tasks.withType(JavaCompile).configureEach {
+ options.compilerArgs.add('-parameters')
+}
+
+tasks.withType(GroovyCompile).configureEach {
+ groovyOptions.parameters = true
+}
+----
+
+Without these flags, `Parameter.getName()` returns synthetic names such as `arg0`, the attribute lookup misses, and the call surfaces as `MissingMethodException` at runtime.
+The `@Tag`-annotated method itself produces no compile-time warning, because preservation is a property of the build, not of the source file.
+
+==== 23. Known Plugin Incompatibilities
+
+A Grails 7 plugin is not automatically incompatible with Grails 8. A plugin resolving, appearing in the load order, and letting the application start is encouraging, but it is not enough to establish compatibility. Exercise the plugin's documented public behavior, including web requests, outbound calls, serialization, commands, and any domain traits or annotations it exposes.
+
+When a released Grails 7 plugin fails, first check whether the maintainer has published a Grails 8 version. Some failures have a temporary application-side workaround. Others are binary incompatibilities in already-published bytecode and require the plugin author to rebuild and release the plugin against Grails 8. Do not add framework-internal compatibility classes to an application to work around those failures.
+
+Use the first distinctive failure to choose the next step:
+
+* `NoClassDefFoundError` mentioning `com/fasterxml/jackson/databind/exc/InvalidDefinitionException` while creating `OrderedFormContentFilter`: add the BOM-managed Jackson 2 `jackson-databind` dependency described below, then retest the plugin's public behavior.
+* `Could not find org.grails:...:.`: use a plugin version built against `org.apache.grails`, or use narrowly targeted dependency substitution as a temporary migration aid.
+* `MissingPropertyException` or `MissingMethodException` from `Metadata`: the plugin must be rebuilt against the typed metadata API.
+* `MalformedParameterizedTypeException` mentioning `$Trait$FieldHelper`, `NoClassDefFoundError` mentioning `ObjectUtil`, `IncompatibleClassChangeError` involving `HttpHeaders`, or an unexpected internal property after using a plugin annotation: the plugin must be rebuilt for Grails 8.
+
+===== 23.1 Metadata dynamic and map-style access
+
+A plugin that reads metadata through `Metadata.current.'some.key'` or `Metadata.current.get('some.key')` can start normally and fail only when that code path runs. The usual symptoms are `MissingPropertyException` or `MissingMethodException`, often as an HTTP 500 on a plugin endpoint. See https://github.com/apache/grails-core/issues/16122[Issue #16122].
+
+Plugin authors must replace the removed dynamic accessors with the typed public API:
+
+[source,groovy]
+----
+// Grails 7
+def version = Metadata.current.'info.app.grailsVersion'
+def name = Metadata.current.get('info.app.name')
+
+// Grails 8
+String version = Metadata.current.getProperty('info.app.grailsVersion', String, null)
+String name = Metadata.current.getProperty('info.app.name', String, null)
+----
+
+For a nested metadata value that does not need type conversion, `Metadata.current.navigate('some', 'nested', 'key')` is also available. This is a rebuild-only change for a published binary plugin. No Metadata compatibility shim is available.
+
+===== 23.2 Groovy 4 trait and AST-transform bytecode
+
+Groovy 5 can compile application code against a Groovy 4 plugin, but the following generated-bytecode patterns are known to be incompatible. These failures commonly occur only when the plugin's public feature is used, rather than at dependency resolution or startup. Rebuild the plugin with Grails 8 and Groovy 5. Consumers cannot reliably repair an already-published jar.
+
+* **Generic traits with fields.** A Grails 7 plugin that exposes a generic trait with fields can fail when an application implements that trait. JavaBeans, Spring, or Jackson introspection then throws `MalformedParameterizedTypeException` mentioning `<Trait>$Trait$FieldHelper`. The plugin's trait must be recompiled with Groovy 5. See https://github.com/apache/grails-core/issues/16123[Issue #16123]. Non-generic traits are not affected by this specific issue.
+
+* **AST transformations that target private trait methods.** A plugin transformation can compile successfully but silently lose a private trait method from the emitted application class. Using the annotated public feature then throws `MissingPropertyException` for an unexpected internal property. Plugin authors should change the transform to target a member emitted on the implementing class, then rebuild with Groovy 5. See https://github.com/apache/grails-core/issues/16126[Issue #16126].
+
+* **`@Immutable` classes.** A Groovy 4-compiled `@Immutable` class can throw `NoClassDefFoundError: org/apache/groovy/runtime/ObjectUtil` when constructed on Groovy 5. The missing call is generated by Groovy 4's AST transformation, so updating application source does not fix a released plugin jar. Rebuild affected plugin artifacts with Groovy 5. See https://github.com/apache/grails-core/issues/16128[Issue #16128].
+
+See <<groovy5-behavior-changes,Apache Groovy 5 Behavior Changes>> for source-level Groovy 5 changes that may affect the rebuilt plugin.
+
+===== 23.3 Jackson 2 dataformats without Jackson 2 databind
+
+Grails 8 uses Jackson 3 for databind, while a released plugin may still bring Jackson 2 Smile, CBOR, or YAML dataformat artifacts. If one of those dataformats is present while Jackson 2 databind is absent, Spring Framework detects an incomplete Jackson 2 classpath and application startup fails with `NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException`, usually while creating `OrderedFormContentFilter`. Jackson 2 core, annotations, and XML dataformat alone [...]
+
+The immediate consumer workaround is to supply the matching Jackson 2 databind artifact while the plugin is being migrated:
+
+[source,groovy]
+.build.gradle
+----
+dependencies {
+ implementation 'com.example:plugin-that-needs-jackson2-dataformats:1.0.0'
+
+ // Keep the Jackson 2 runtime classpath complete.
+ runtimeOnly 'com.fasterxml.jackson.core:jackson-databind'
+}
+----
+
+Use the Jackson 2 version managed by the Grails and Spring Boot platform. Do not add a version if the active BOM already manages it. Plugin authors should release a Grails 8 version that migrates to Jackson 3 where possible, or declares a complete, compatible Jackson 2 runtime when it must retain Jackson 2 dataformats. See https://github.com/apache/grails-core/issues/16124[Issue #16124] and <<jackson3-default,Jackson 3 is the New Default>>.
+
+===== 23.4 Pre-Apache `org.grails` coordinates
+
+Some older plugins import a pre-Apache `org.grails` BOM and declare versionless `org.grails:*` dependencies. Grails 8 does not publish those coordinates. Gradle often reports an unhelpful empty-version error such as `Could not find org.grails:grails-core:.`.
+
+No complete, general coordinate substitution map exists. A narrowly targeted application-level substitution rule can resolve some plugins, but module names and binary compatibility are not always one-to-one after the Apache group rename. Treat substitution as a temporary diagnostic or migration aid, not proof that a plugin is compatible. The supported migration is for plugin authors to rebuild against `org.apache.grails` coordinates and publish a Grails 8 release. See https://github.com [...]
+
+[source,groovy]
+.build.gradle - Plugin author migration
+----
+// Before: imported by an early Grails 7 plugin POM
+implementation platform('org.grails:grails-bom:7.0.0-M1')
+
+// After: compile against the Apache Grails 8 BOM
+implementation platform("org.apache.grails:grails-bom:$grailsVersion")
+----
+
+===== 23.5 Spring Framework 7 `HttpHeaders` binary incompatibility
+
+Spring Framework 7's `HttpHeaders` no longer implements `MultiValueMap`. A Grails 7 plugin compiled against Spring 6 can therefore boot and then throw `IncompatibleClassChangeError` when it passes `HttpHeaders` to an API expecting `MultiValueMap`, often during an outbound HTTP request. See https://github.com/apache/grails-core/issues/16127[Issue #16127].
+
+Plugin authors must compile against Spring Framework 7 and use the `HttpHeaders`-typed API. Remove any explicit `MultiValueMap` cast so recompilation selects Spring 7's `HttpEntity(T, HttpHeaders)` constructor instead of the deprecated `HttpEntity(T, MultiValueMap)` constructor:
+
+[source,groovy]
+----
+// Grails 7 / Spring 6 code that selected the MultiValueMap API
+HttpHeaders headers = new HttpHeaders()
+new HttpEntity(body, (MultiValueMap<String, String>) headers)
+
+// Grails 8 / Spring 7: use the HttpHeaders API
+HttpHeaders headers = new HttpHeaders()
+new HttpEntity(body, headers)
+----
+
+Changing only an application's dependencies cannot repair the plugin's existing bytecode. Upgrade to a plugin release compiled for Grails 8, or ask the maintainer to publish one.
+
+===== 23.6 Commands and plugin bean timing
+
+For a released Grails 7 plugin that implements `grails.dev.commands.ApplicationCommand`, keep the default `cliAutoProvision = true` and enable `grails { legacyCommandSupport = true }`. Run its commands with `./gradlew runCommand "-Pargs=<command> <arguments>"` or through the shell. Legacy commands do not create named Gradle tasks. Script, YAML, and profile commands do not need this bridge.
+
+The complete command migration, including the legacy bridge, script packaging, and companion artifact support delivered by https://github.com/apache/grails-core/pull/16011[PR #16011], https://github.com/apache/grails-core/pull/16082[PR #16082], and https://github.com/apache/grails-core/pull/15948[PR #15948], is covered in <<cli-companion-artifacts,CLI Commands Move to Companion `-cli` Artifacts>>. Plugin authors should still migrate commands to the current API and publish companion `-cl [...]
+
+The plugin bean lifecycle change is not a compatibility bridge. Existing `doWithSpring` plugins still run, but https://github.com/apache/grails-core/pull/15934[PR #15934] moved them before Spring Boot auto-configuration. During that callback, the initializing application is available through the plugin's `grailsApplication` property, but it has not yet been published to the process-global `Holders.grailsApplication` fallback. Plugins that read the global Holder from `doWithSpring` must [...]
+
+Plugin compatibility continues to evolve. Check the plugin's release notes and the https://github.com/apache/grails-core/issues?q=state%3Aopen%20label%3A%22relates-to%3A%20external-plugin%22[Grails external-plugin issues] for current status.
+
+==== 24. Custom JSON View Converters
+
+JSON views now use Groovy's `groovy.json.JsonGenerator` implementation instead of the previous Grails-specific
+JSON generator infrastructure.
+If you previously customized JSON view rendering with Grails-specific generator classes, migrate that logic to a
+`groovy.json.JsonGenerator.Converter` implementation.
+
+This change applies to JSON views rendered by the `grails-views-gson` module.
+The `grails.converters.JSON.registerObjectMarshaller(...)` API is still used by the `grails-converters` module
+for `render ... as JSON` and related converter-based rendering.
+
+To migrate your custom converters:
+
+- Implement `groovy.json.JsonGenerator.Converter` (was previously `grails.plugin.json.builder.JsonGenerator.Converter`)
+- Change the file name of the converter registration service loader to
+`src/main/resources/META-INF/services/groovy.json.JsonGenerator$Converter`
+(was previously `src/main/resources/META-INF/services/grails.plugin.json.builder.JsonGenerator$Converter`)
+
+==== 25. Rendering Enum values as JSON
+
+It is no longer possible to render a single enum value as JSON using the `render(Number.ONE as JSON)` syntax.
+Previously, rendering an enum value would produce a JSON string with the type and name of the enum value like:
+```json
+{
+ "enumType": "com.example.Number",
+ "name": "ONE"
+}
+```
+
+Rendering an enum value as JSON will now instead throw a `ConverterException`.
+See https://github.com/apache/grails-core/pull/15212[PR 15212] for more details on this change.
+
+[[_hibernate_5_to_hibernate_7_migration]]
+==== 26. Hibernate 5 to Hibernate 7 Migration
+
+Grails 8 supports both Hibernate 5 (the default) and Hibernate 7.
+If you are upgrading from Grails 7 and also want to migrate from Hibernate 5 to Hibernate 7, apply the `grails-hibernate7-bom` and the Hibernate 7 plugin in addition to the standard Grails 8 upgrade steps.
+
+[source,groovy]
+.build.gradle — switch to Hibernate 7
+----
+dependencies {
+ implementation enforcedPlatform("org.apache.grails:grails-hibernate7-bom:$grailsVersion")
+ implementation 'org.apache.grails:grails-hibernate7'
+}
+----
+
+The following sections cover every breaking change introduced between Hibernate ORM 5.6.x (used by Grails 7) and Hibernate ORM 7.0.x, and what you need to do in your Grails application.
+
+===== 26.1 Hibernate Session API Removals
+
+Hibernate 7 removed long-deprecated Hibernate-specific session methods in favour of the standard JPA equivalents.
+GORM's dynamic methods (`save()`, `delete()`, `get()`, `load()`, `merge()`, etc.) are **not** affected — these go through GORM's own persistence API and have been updated internally.
+
+You are only affected if your code calls the Hibernate `Session` or `StatelessSession` directly (e.g. inside a `withSession` or `withStatelessSession` block).
+
+[cols="1,1", options="header"]
+|===
+| Removed (Hibernate 5/6)
+| Replacement (Hibernate 7 / JPA)
+
+| `session.save(entity)`
+| `session.persist(entity)`
+
+| `session.update(entity)`
+| `session.merge(entity)`
+
+| `session.saveOrUpdate(entity)`
+| `session.persist(entity)` (new) or `session.merge(entity)` (detached)
+
+| `session.delete(entity)`
+| `session.remove(entity)`
+
+| `session.load(Class, id)`
+| `session.getReference(Class, id)`
+
+| `session.get(Class, id)`
+| `session.find(Class, id)`
+|===
+
+===== 26.2 Removed Hibernate Annotations
+
+The following Hibernate-specific annotations were removed in Hibernate 7.
+Where a replacement exists, migrate before upgrading.
+
+[cols="1,2", options="header"]
+|===
+| Removed annotation
+| Action required
+
+| `@org.hibernate.annotations.Where`
+| Replace with `@org.hibernate.annotations.SQLRestriction`
+
+| `@org.hibernate.annotations.WhereJoinTable`
+| Replace with `@org.hibernate.annotations.SQLJoinTableRestriction`
+
+| `@org.hibernate.annotations.Proxy`
+| Remove — proxy configuration is no longer supported
+
+| `@org.hibernate.annotations.LazyCollection`
+| Remove and use `@ManyToMany(fetch = FetchType.LAZY)` or `EAGER` directly
+
+| `@org.hibernate.annotations.Persister`
+| Remove — custom persisters are no longer supported
+
+| `@org.hibernate.annotations.SelectBeforeUpdate`
+| Remove — behaviour is now configurable via `@DynamicUpdate`
+
+| `@org.hibernate.annotations.Loader`
+| Remove — custom SQL loaders are no longer supported; use `@SQLSelect` on the entity itself
+|===
+
+NOTE: Grails domain classes that use the `mapping { }` DSL are not affected by annotation removals.
+These annotations only apply if you are using Hibernate annotations directly on Java or Groovy classes.
+
+===== 26.3 CascadeType.SAVE_UPDATE Removed
+
+`CascadeType.SAVE_UPDATE` (a Hibernate-specific cascade type) was removed in Hibernate 7.
+Persisting a transient entity that has detached associations now throws `EntityExistsException` instead of silently merging.
+
+If your domain mapping or annotated classes used `cascade = CascadeType.SAVE_UPDATE`, replace it with `cascade = CascadeType.ALL` or `cascade = [CascadeType.PERSIST, CascadeType.MERGE]` as appropriate.
+
+Also note that automatic `cascade = CascadeType.PERSIST` on `@Id` and `@MapsId` associations was removed.
+If you relied on this implicit behaviour, add an explicit `cascade = CascadeType.PERSIST` to the `@ManyToOne` or `@OneToOne` carrying `@MapsId`.
+
+===== 26.4 Detached Entity Operations
+
+Calling `refresh()` or `lock()` on a detached entity now throws `IllegalArgumentException` (JPA specification compliance).
+In Hibernate 5 and 6 this was silently permitted.
+
+If your code calls `entity.refresh()` or `entity.lock()` after the Hibernate session has been closed or the entity has been evicted, you must either re-attach the entity first (via `session.merge()`) or reload it before refreshing.
+
+===== 26.5 Native Query Temporal Type Changes
+
+Native SQL queries (via `executeQuery`, `withCriteria`, or a raw `Session.createNativeQuery`) now return `java.time` types (`LocalDate`, `LocalTime`, `LocalDateTime`) instead of the legacy `java.sql` types (`java.sql.Date`, `java.sql.Time`, `java.sql.Timestamp`).
+
+If your code casts results from native queries to `java.sql` date/time types, update those casts to use the `java.time` equivalents, or set the following property to restore legacy behaviour during a phased migration:
+
+[source,yaml]
+.application.yml
+----
+hibernate:
+ query:
+ native:
+ prefer_jdbc_datetime_types: true
+----
+
+===== 26.6 StatelessSession Now Uses Second-Level Cache by Default
+
+`StatelessSession` in Hibernate 7 participates in the second-level cache by default (it did not in Hibernate 5/6).
+If you use `withStatelessSession` for bulk operations where cache bypass was intentional, disable caching explicitly:
+
+[source,groovy]
+----
+YourDomain.withStatelessSession { StatelessSession session ->
+ session.setCacheMode(CacheMode.IGNORE)
+ // ... bulk operations
+}
+----
+
+===== 26.7 DDL Schema Changes
+
+If you use `dbCreate = 'create-drop'` or `dbCreate = 'update'` in development, or generate a schema with the `schema-export` command, be aware of the following DDL differences in Hibernate 7.
+
+[cols="1,1,2", options="header"]
+|===
+| Database
+| Column type
+| Change
+
+| All
+| `char` / `Character` fields
+| Now maps to `varchar(1)` instead of `char(1)` to avoid trailing-space issues in MySQL
+
+| Oracle
+| `float` / `double` fields
+| Now maps to `binary_float` / `binary_double` (IEEE 754). Set `hibernate.dialect.oracle.use_binary_floats=false` to restore the old mapping.
+
+| Oracle
+| `Timestamp` columns
+| Precision changed to 9 digits (nanoseconds). Existing columns with lower precision will need migration.
+
+| SQL Server
+| `Timestamp` columns
+| Precision changed to 7 digits (100 nanoseconds). Existing columns will need migration.
+
+| MySQL / MariaDB
+| Array-mapped columns
+| Now stored as JSON instead of `VARBINARY`. Set `hibernate.type.preferred_array_jdbc_type=VARBINARY` to restore old behaviour.
+|===
+
+WARNING: If you have an existing production database, validate the schema diff before enabling `dbCreate = 'update'` or running Liquibase migrations after the Hibernate 7 upgrade.
+
+===== 26.8 Hibernate 6 Intermediate Changes
+
+Hibernate 7 builds on Hibernate 6, which itself introduced breaking changes relative to Hibernate 5.
+The changes in Hibernate 6 that are most likely to affect a Grails application are listed here for completeness.
+
+*HQL / criteria result type*: An HQL query with a `JOIN` but no explicit `SELECT` clause now returns the root entity type (`List<Person>`) instead of `List<Object[]>`.
+If you depended on the old tuple-style result, add an explicit `SELECT` clause to your query.
+
+*Ordinal HQL parameters*: Ordinal parameters changed from 0-based to 1-based indexing (`:?1`, `:?2`, ...).
+The GORM dynamic finders and criteria API are not affected; only raw HQL strings with ordinal parameters need updating.
+
+*Legacy Hibernate Criteria API removed*: The legacy `Criteria` / `DetachedCriteria` API from Hibernate 5 was removed in Hibernate 6.
+GORM's `createCriteria()` and `withCriteria()` DSL are implemented on top of the JPA Criteria API and are **not** affected.
+
+*Boolean type mappings*: If your schema used string-based boolean type names (e.g. `type: 'yes_no'`), migrate to the corresponding converter class (`YesNoConverter`).
+
+*`javax.persistence` → `jakarta.persistence`*: This migration was already required for Grails 7; Grails 8 continues to require `jakarta.*`.
+
+[[_join_table_foreign_key_column_names]]
+===== 26.9 Join-Table Foreign-Key Column Names
+
+This change affects only a *unidirectional* `hasMany` — a collection with no `belongsTo` and no reciprocal `hasMany` on the other side. A *bidirectional* many-to-many association (both sides declare `hasMany`, or one side uses `belongsTo`) is **not** affected: both of its join-table foreign-key columns are still derived from the class names, identical to Grails 7.
+
+In Grails 7 (Hibernate 5), the default foreign-key column that referenced the associated entity in a unidirectional `hasMany` join table was derived from the simple name of that entity's domain class, after applying the column naming strategy.
+For example, the domain class `Book` produced the foreign-key column `book_id`, even when its physical table was mapped to a different name.
+
+In Grails 8 (Hibernate 7), that foreign-key column is instead derived from the physical table name of the associated domain class.
+The physical name includes an explicit `table` mapping and any transformation made by a custom physical naming strategy.
+For example, given the following mapping:
+
+[source,groovy]
+----
+class Book {
+ static mapping = {
+ table 'catalog_book'
+ }
+}
+
+class Shelf {
+ String label
+
+ static hasMany = [books: Book] // unidirectional: no belongsTo, no reciprocal hasMany
+}
+----
+
+Grails 7 used `book_id` by default in the `shelf_books` join table, whereas Grails 8 uses `catalog_book_id`. The other column in that same join table (`shelf_id`, derived from the owning `Shelf` class) is unchanged.
+This is a breaking schema change for an existing database if its join table still uses the Grails 7 column name.
+
+To keep the existing schema unchanged, configure the join table and its foreign-key column explicitly in the `static mapping` block:
+
+[source,groovy]
+----
+class Shelf {
+ String label
+
+ static hasMany = [books: Book]
+
+ static mapping = {
+ books joinTable: [
+ name: 'shelf_books',
+ key: 'shelf_id',
+ column: 'book_id'
+ ]
+ }
+}
+----
+
+Replace `shelf_books`, `shelf_id`, and `book_id` with the table and column names already used by your database.
+Declaring all three names prevents the naming strategy from changing the mapping during the upgrade.
+
+Separately, the element column of a *basic (non-enum) collection* (e.g. `static hasMany = [items: String]`) is now resolved through the naming strategy's *column* naming rules instead of its *table* naming rules for the property-name prefix, producing a `<property>_<element-type identifier>` column name. An enum collection is unaffected: its element column has no property-name prefix and already used the column naming rules before this change. Most naming strategies apply the same trans [...]
+
+===== 26.10 Table-per-Hierarchy Discriminator Defaults
+
+A table-per-hierarchy tree with no discriminator mapping uses the same defaults as Grails 7: a column named `class` that stores the fully qualified name of each class. Tables created by Grails 7 need no change.
+
+8.0.0-RC1 and 8.0.0-RC2 named the column `DTYPE` and stored the simple name of each subclass, for example `com.example.Vehicle`, `Car` and `SportsCar`. A table created by either release candidate now fails `dbCreate: 'validate'` with `missing column [class]`, and its subclass rows no longer match. To keep that layout without migrating the data, map the column on the root class and the simple name on each subclass:
+
+[source,groovy]
+----
+class Vehicle {
+ static mapping = {
+ discriminator column: 'DTYPE' // the root value stays the fully qualified class name
+ }
+}
+
+class Car extends Vehicle {
+ static mapping = {
+ discriminator 'Car'
+ }
+}
+
+class SportsCar extends Car {
+ static mapping = {
+ discriminator 'SportsCar'
+ }
+}
+----
+
+==== 27. GORM Properties Are Nullable by Default
+
+Grails 8 changes the validation default so that an *unconstrained persistent (domain) property is nullable by default* rather than required.
+This aligns Grails with the rest of the JVM persistence/validation ecosystem (JPA/Hibernate, Spring Data, Micronaut Data and Jakarta Bean Validation), all of which treat an unconstrained property as valid when `null`.
+
+Previously every domain property without an explicit constraint had an implicit `nullable: false` applied, so `save()` failed validation when the property was `null`.
+From Grails 8 such a property is optional unless you declare otherwise:
+
+[source,groovy]
+----
+class Book {
+ String title // Grails 7: required, Grails 8: nullable
+
+ static constraints = {
+ title nullable: false // declare explicitly to keep it required
+ }
+}
+----
+
+This change also affects persistence mapping. Columns for unconstrained properties are
+nullable by default, so schema creation and schema migration can produce nullable columns
+where Grails 7 produced `NOT NULL` columns. Review existing schemas and declare
+`nullable: false` explicitly for properties that must remain required before running
+schema migration or diff tools.
+
+Command objects are unaffected: Validateable command-object properties remain non-nullable by default, except for collections and maps, which remain nullable by default.
+
+The exception is a property that a command object imports with `importFrom` from a domain class that declares no `nullable` constraint for it.
+It gets the domain class's nullable default, so it is nullable unless you restore the required-by-default behaviour (below).
+
+To restore the legacy required-by-default behaviour for an entire application, set the new `grails.gorm.default.nullable` property to `false`:
+
+[source,yaml]
+.application.yml
+----
+grails:
+ gorm:
+ default:
+ nullable: false
+----
+
+The existing `grails.gorm.default.constraints` wildcard form also works:
+
+[source,groovy]
+.application.groovy
+----
+grails.gorm.default.constraints = {
+ '*'(nullable: false)
+}
+----
+
+Domains mocked with `DataTest` or `DomainUnitTest` use the same settings as the running application.
+They are read from `application.yml` or `application.groovy`.
+A specification can also set them in `doWithConfig`:
+
+[source,groovy]
+----
+class BookSpec extends Specification implements DomainUnitTest<Book> {
+
+ @Override
+ Closure doWithConfig() {{ config ->
+ config.grails.gorm.default.nullable = false
+ }}
+}
+----
+
+[[groovy5-behavior-changes]]
+==== 28. Apache Groovy 5 Behavior Changes
+
+Grails 8 upgrades from Apache Groovy 4 to Apache Groovy 5.
+Most applications need no changes, but a few stricter behaviors can affect application code.
+
+===== 28.1 Assigning a static field from a static closure requires the class name
+
+Under Groovy 5 with static compilation (`@CompileStatic` / `@GrailsCompileStatic`), assigning to a static field from inside a static closure - such as the `constraints`, `mapping`, or `namedQueries` blocks of a statically compiled class - no longer resolves an unqualified field name to the enclosing class's static field.
+Qualify the assignment with the class name:
+
+[source,groovy]
+----
+@GrailsCompileStatic
+class Book implements Validateable {
+ static boolean constraintsClosureCalled = false
+
+ static constraints = {
+ // Groovy 4: an unqualified assignment resolved to Book.constraintsClosureCalled
+ // Groovy 5: the field must be qualified with the class name
+ Book.constraintsClosureCalled = true
+ }
+}
+----
+
+Reading a static field is unaffected; only assignment from within the static closure needs the class-name qualifier.
+
+===== 28.2 Probing a `ConfigObject` for a missing key
+
+In Groovy 5, indexing a `groovy.util.ConfigObject` with the subscript operator for a key that does not exist creates and inserts an empty nested `ConfigObject` for that key, rather than reading back as a falsy value.
+Code that walks a configuration source with `[]` and expects a missing key to be `null` should test for the key explicitly before reading it:
+
+[source,groovy]
+----
+// Under Groovy 5 this inserts an empty entry for a missing key
+def value = configObject[key]
+
+// Probe without creating an entry
+def value = configObject.containsKey(key) ? configObject.get(key) : null
+----
+
+Grails applies this guard internally when resolving Spring profile activation keys; you only need it in application code that navigates a raw `ConfigObject` by subscript.
+
+===== 28.3 A getter on a map no longer hides behind a map entry
+
+In Groovy 4, reading or writing a property on a class that implements `Map` always addressed a map entry.
+In Groovy 5 a public JavaBean accessor declared on such a class is resolved first, so an entry whose name matches an accessor becomes unreadable, and assigning to it throws `groovy.lang.ReadOnlyPropertyException`.
+This affected `params`, where `getRequest()` and `getIdentifier()` made request parameters named `request` and `identifier` unreachable.
+
+Grails 8 removes those accessors, so `params` behaves as it did in Grails 7 - every parameter name is an ordinary map entry, in dotted and subscript form, and under static compilation:
+
+[source,groovy]
+----
+params.identifier = 'id1' // the request parameter, not a property
+params['request'] = 'req1' // the request parameter, not the HttpServletRequest
+----
+
+Two methods changed as a result:
+
+[cols="1,1", options="header"]
+|===
+| Grails 7
+| Grails 8
+
+| `params.getRequest()`
+| `params.request()`
+
+| `params.getIdentifier()`
+| `params.id` -- it only ever read the `id` parameter
+|===
+
+The same change applies to the `attrs` map passed to a GSP tag, whose internal implementation renames `isGspTagSyntaxCall()` to `gspTagSyntaxCall()`.
+Its setter is retained, so assigning `attrs.gspTagSyntaxCall` still invokes that setter rather than storing an attribute - as in Grails 7.
+Subscript assignment, `attrs['gspTagSyntaxCall'] = value`, now stores an attribute of that name, as `attrs.put('gspTagSyntaxCall', value)` does; in Grails 7 it invoked the setter.
+
+NOTE: When adding a class that extends `grails.util.TypeConvertingMap`, do not declare a no-argument `getX()` or `isX()` method on it, or the entry `x` becomes unreachable for the same reason. Statically compiled callers bind directly to the accessor, so the collision cannot be corrected at runtime.
+
+==== 29. MIME Types Are Now Framework Defaults
+
+Grails 8 ships the full set of supported MIME types as built-in framework defaults.
+Previously every newly generated application declared a `grails.mime.types` block in `grails-app/conf/application.yml`; the Grails Forge and the application profiles no longer generate that block, because the framework now supplies the same defaults out of the box.
+
+The built-in defaults cover `all`, `atom`, `css`, `csv`, `form`, `html`, `js`, `json`, `multipartForm`, `pdf`, `rss`, `text`, `hal` and `xml`, the same set new applications historically declared.
+
+**No action is required.**
+A declared `grails.mime.types` still *replaces* the defaults, exactly as in Grails 7. Your existing block remains authoritative and you get precisely the types you declared (including a deliberately narrowed set). New applications simply no longer need the block, because the framework supplies these defaults when none is configured.
+
+**Optional: merge instead of replace.**
+If you would rather add to the defaults than re-declare them, set `grails.mime.mergeDefaults` to `true`. Your declared entries are then merged over the built-in defaults. An entry replaces the default for its extension, and any extension you do not declare keeps its default, so you can register a single custom type without restating the full list:
+
+[source,yaml]
+.application.yml
+----
+grails:
+ mime:
+ mergeDefaults: true
+ types:
+ custom: application/vnd.example+json
+----
+
+==== 30. Accept Header Honored for All Clients
+
+Grails 8 honors the HTTP `Accept` header for content negotiation for **every** client by default, including browsers.
+
+In Grails 7 and earlier, the `Accept` header was ignored for the major browser rendering engines: `grails.mime.disable.accept.header.userAgents` defaulted to `['Gecko', 'WebKit', 'Presto', 'Trident']`.
+That was a workaround for very old browsers (Firefox 2 and 3) whose `Accept` header ranked XML above HTML.
+Modern browsers send a well-formed header that already prioritizes HTML (`text/html` at `q=1.0`, `application/xml` at `q=0.9`), so the workaround is no longer needed.
+
+The practical effect of the old default was that a browser-issued `fetch()` or `XMLHttpRequest` call requesting `application/json` would receive HTML instead of JSON, because those calls do not send an `X-Requested-With: XMLHttpRequest` header (only libraries such as jQuery add it automatically).
+In Grails 8 such a request correctly receives JSON.
+
+**What changed:** `grails.mime.disable.accept.header.userAgents` now defaults to unset, so no user agents are filtered.
+
+**Most applications need no action.**
+Browser page loads still resolve to HTML because modern browsers rank `text/html` highest, and `withFormat { html { } json { } }` continues to serve HTML to browsers and JSON to clients that ask for it.
+
+**`respond` endpoints without an HTML view now error for browser requests.**
+Because browsers now negotiate `text/html`, an action that uses `respond(...)` but has no corresponding HTML view (GSP) can no longer return JSON to a browser by accident. It negotiates `html` and attempts to render the missing view, which results in an error.
+Previously the browser's `Accept` header was ignored, so such an endpoint happened to return JSON.
+If you have browser-facing `respond` endpoints, add an HTML view for the action (or `render` an appropriate response directly).
+API clients that send a specific `Accept` such as `application/json` are unaffected.
+
+To restore the Grails 7 behavior of ignoring the `Accept` header for browsers, set the property explicitly:
+
+[source,yaml]
+.application.yml
+----
+grails:
+ mime:
+ disable:
+ accept:
+ header:
+ userAgents:
+ - Gecko
+ - WebKit
+ - Presto
+ - Trident
+----
+
+==== 31. @EnableWebMvc No Longer Added to Grails Applications
+
+In earlier versions, Grails added Spring's `@EnableWebMvc` annotation to the generated `Application` class at compile time.
+`@EnableWebMvc` is a Spring Framework configuration annotation that is not intended to be combined with Spring Boot: it imports `DelegatingWebMvcConfiguration`, which eagerly registers a fixed set of MVC beans and switches off Spring Boot's `WebMvcAutoConfiguration`.
+In a Boot application this produced bean-definition override warnings at startup (for example for `localeResolver` and `internalAutoProxyCreator`) and prevented Boot's conditional, more configurable auto-configuration from taking effect.
+
+Grails 8 removes the auto-injected `@EnableWebMvc`.
+Spring Boot's `WebMvcAutoConfiguration` is now active for Grails servlet web applications, which is the intended Boot behavior and resolves those override warnings.
+
+**No action is required for most applications.**
+Grails adapts internally so the change is transparent.
+The notes below explain the behavioral differences this introduces and the configuration toggles available if you need to control them.
+
+===== 31.1 Boot's default view resolver is removed automatically
+
+With `WebMvcAutoConfiguration` active, Boot contributes a catch-all `defaultViewResolver` (an `InternalResourceViewResolver`).
+For a Grails application that does not use JSP/`InternalResource` views (for example a REST/JSON-views application) this resolver maps any unmatched view name to a servlet forward, which can surface as:
+
+[source]
+----
+Circular view path [index]: would dispatch back to the current handler URL
+----
+
+To prevent this, Grails removes Boot's `defaultViewResolver` for every Grails servlet web application so that Grails' own view resolution is used instead.
+If you need to keep Boot's `defaultViewResolver` (for example, an application that genuinely relies on JSP/`InternalResource` views), opt out:
+
+[source,yaml]
+.application.yml
+----
+grails:
+ web:
+ removeDefaultViewResolverBean: false
+----
+
+NOTE: In GSP applications the GSP view resolver continues to be installed as the primary `viewResolver`, controlled as before by `spring.gsp.replaceViewResolverBean`.
+The earlier `spring.gsp.removeDefaultViewResolverBean` property (from when this removal lived in the GSP module) is still honoured for backward compatibility but is **deprecated** — `defaultViewResolver` removal is now handled centrally for all Grails servlet web applications by the `grails.web.removeDefaultViewResolverBean` property above, which takes precedence. Setting the old name logs a deprecation warning at startup.
+
+===== 31.2 GrailsWebRequest binding
+
+With `WebMvcAutoConfiguration` active, Boot would otherwise register its own `RequestContextFilter` that rebinds a plain `ServletRequestAttributes`, replacing the `GrailsWebRequest` bound earlier in the filter chain.
+Downstream code that expects a `GrailsWebRequest` would then fail with a `ClassCastException`.
+
+Grails 8 registers its request-binding filter as a `RequestContextFilter` bean so that Boot's filter backs off and the `GrailsWebRequest` remains bound for the whole request.
+This is handled internally and requires no configuration changes.
+Applications that defined their own `GrailsWebRequestFilter` bean, or their own `grailsWebRequestFilter` filter-registration bean, continue to override the Grails-provided ones.
+
+===== 31.3 Boot's static resources and welcome page are removed
+
+With `WebMvcAutoConfiguration` active, Boot would register a catch-all static-resource handler (`classpath:/META-INF/resources/`, `/resources/`, `/static/`, `/public/`) and a `WelcomePageHandlerMapping` that serves a static `index.html` for the root path.
+In a Grails application these can shadow URL mappings — a request that should fall through to Grails' URL-mapping error handling could instead be served as a static resource, and `/` could return a static `index.html` rather than being handled by your `UrlMappings`.
+
+So that Grails' own URL mappings and resource handling stay in control, Grails 8 disables both by default:
+
+* `spring.web.resources.add-mappings` defaults to `false`, which disables Boot's catch-all static-resource handler. Re-enable it with `spring.web.resources.add-mappings: true`.
+* Boot's welcome-page mapping is removed so `UrlMappings` owns `/`. Opt out with `grails.web.removeWelcomePageMapping: false`.
+
+===== 31.4 Other Boot MVC features now active
+
+Because Boot's `WebMvcAutoConfiguration` is now active, a handful of its features that `@EnableWebMvc` previously suppressed take effect for Grails servlet web applications.
+None require action for a typical application, but they are behavioral differences worth knowing about when you upgrade:
+
+* **Form-content filter for `PUT` / `PATCH` / `DELETE`.** A `FormContentFilter` parses `application/x-www-form-urlencoded` bodies of `PUT`, `PATCH` and `DELETE` requests so their fields are visible through the standard `request.getParameter(...)` API (and therefore in `params`). Boot's `OrderedFormContentFilter` provides it for a default application; for an application that declares `@EnableWebMvc` — where Boot's MVC auto-configuration backs off — Grails contributes an equivalent filter [...]
++
+[source,yaml]
+.application.yml
+----
+spring:
+ mvc:
+ formcontent:
+ filter:
+ enabled: false
+----
+
+* **`spring.mvc.*` and `spring.web.*` properties now apply.** Properties such as `spring.web.locale`, `spring.mvc.format.date` / `time` / `date-time`, and `spring.web.resources.*` were inert before and now take effect. Review any of these you may have set inadvertently (for example copied from Boot documentation).
+
+* **View resolution.** For non-GSP applications the primary `viewResolver` is now Boot's `ContentNegotiatingViewResolver`, which negotiates and delegates to the available view resolvers. GSP applications continue to use the GSP view resolver as before.
+
+* **Conversion and message converters.** `mvcConversionService` is now Boot's `ApplicationConversionService` (which honours the `spring.mvc.format.*` properties above), and the MVC HTTP message converters pick up Boot's customizations, including the application's Jackson `ObjectMapper`. This mainly affects MVC-layer data binding and `@RestController`-style endpoints.
+
+===== 31.5 Locale resolution
+
+Grails' locale resolution — including `?lang=` switching via `SessionLocaleResolver` — continues to work as before, and the resolver strategy is now configurable through `grails.i18n.localeResolver` (`session` (default), `cookie`, `acceptHeader` or `fixed`).
+Applications that opt into `@EnableWebMvc` are unaffected too: Grails removes the `AcceptHeaderLocaleResolver` that Spring's `WebMvcConfigurationSupport` would otherwise contribute, so the configured Grails resolver still wins.
+
+==== 32. More Framework Beans Are Cleanly Overridable
+
+Several Grails framework beans that were previously registered unconditionally are now guarded with `@ConditionalOnMissingBean`, so a bean of the same name (or type) defined in an application configuration class (a `@Bean` method) takes precedence cleanly instead of relying on bean-definition overriding:
+
+* i18n: `localeResolver`, `localeChangeInterceptor` and `messageSource`
+* URL mappings: `grailsCorsFilter`, `urlMappingsErrorPageCustomizer` and `urlMappingsInfoHandlerAdapter`
+* Controllers: `exceptionHandler`
+* Cache: `grailsCacheManager` and `customCacheKeyGenerator`
+
+**No action is required.**
+The framework beans still register by default; this only changes what happens when you define your own.
+Previously, defining one of these beans produced a bean-definition override (with a startup warning, or a failure when `spring.main.allow-bean-definition-overriding` is `false`).
+Now the framework bean simply backs off.
+
+NOTE: The clean back-off applies to beans that are registered before auto-configuration conditions are evaluated: `@Bean` methods in application configuration classes, and — as of the retimed plugin lifecycle (see _Plugin Beans Now Register Before Spring Boot Auto-Configuration_ below) — beans contributed through a plugin's `doWithSpring` or `beanRegistrar()`.
+Beans contributed through the application's `resources.groovy` or `resources.xml` register later and continue to take effect through bean-definition overriding, exactly as in previous releases.
+The one exception is a `@Configuration` class registered there, which is no longer processed — see <<resources-groovy-configuration-classes,`@Configuration` classes registered in `resources.groovy`>> below.
+
+[[plugin-beans-before-autoconfiguration]]
+==== 33. Plugin Beans Now Register Before Spring Boot Auto-Configuration
+
+In Grails 7 and earlier, the beans a plugin contributed through `doWithSpring` were registered *after* Spring Boot had processed its auto-configurations.
+A plugin that wanted to replace a Boot-provided bean therefore had to rely on bean-definition overriding, and Boot beans guarded by `@ConditionalOnMissingBean` never saw the plugin's bean in time to back off.
+
+In Grails 8 the plugin lifecycle is unified and retimed: plugin bean definitions — both `doWithSpring` and the new `beanRegistrar()` hook — are drained into the bean definition registry *before* Spring Boot expands its auto-configurations. The practical effects are:
+
+* **Plugin beans win `@ConditionalOnMissingBean` races.** When a plugin registers a bean, a Boot auto-configuration bean of the same name or type that is guarded by `@ConditionalOnMissingBean` now backs off in favor of the plugin's bean. Plugins no longer need to override or remove Boot's defaults after the fact.
+* **A single plugin manager and `GrailsApplication`.** The plugin manager and the `grailsApplication` are built once, early in the context lifecycle, and reused for the rest of startup, so plugins are loaded by a single manager pass rather than a throwaway pass followed by the real one. The global `Holders.grailsApplication` fallback is published after plugin `doWithSpring` and `beanRegistrar()` callbacks complete; plugins must not use it during those callbacks.
+* **Artefact discovery happens earlier.** Controllers, services, domain classes and other artefacts are discovered before plugin beans are registered, because core plugins iterate the application's artefacts while defining beans. The set of discovered artefacts is unchanged — only the timing moved.
+* **Side-effectful `doWithSpring` closures still run once**, just earlier. Closures that read `grailsApplication.config` continue to work; the configuration is fully loaded (including plugin-contributed configuration) before any bean-definition code runs.
+* **The application class is instantiated a second time during early artefact discovery.** A throwaway instance is created solely to compute the application's class scan; the real lifecycle bean is still created by Spring. An application-class constructor with side effects therefore runs twice per boot, so keep application-class constructors free of side effects.
+* **Plugins that inspect the bean definition registry see a pre-auto-configuration registry.** A `doWithSpring` closure that checks for the presence of a bean definition (for example `dispatcherServlet` as a "web application" signal) now runs before Spring Boot has registered its auto-configured beans, so such a check returns `false` where it previously returned `true`. Plugin code should test a registration-order-independent signal instead — for example whether the application context [...]
+* **The `annotationHandlerMapping` and `annotationHandlerAdapter` beans were removed.** These duplicated the request-mapping infrastructure that Spring's own MVC configuration already provides and were never consulted at runtime, but with plugin beans now registering first the bare duplicate adapter started shadowing Spring's fully configured one. `@Controller` annotated beans continue to be handled by Spring Boot's standard MVC infrastructure.
+
+**The bean builder DSL is deprecated.** `doWithSpring()` on `GrailsApplicationLifeCycle` and `grails.plugins.Plugin` is deprecated as of Grails 8 — it continues to work, but the recommended way to register beans is the new `beanRegistrar()` hook, which returns a Spring Framework `org.springframework.beans.factory.BeanRegistrar`.
+
+Before (deprecated bean builder DSL):
+
+[source,groovy]
+----
+import grails.plugins.Plugin
+
+class MyGrailsPlugin extends Plugin {
+
+ @Override
+ Closure doWithSpring() {
+ { ->
+ myService(MyServiceImpl) {
+ timeout = config.getProperty('myPlugin.timeout', Integer, 30)
+ }
+ }
+ }
+}
+----
+
+After (Spring `BeanRegistrar`). `BeanRegistrar` is a functional interface, so a closure coerced with `as BeanRegistrar` is all that is required — a separate class is optional and only worth it for more involved or reusable registration:
+
+[source,groovy]
+----
+import grails.plugins.Plugin
+import org.springframework.beans.factory.BeanRegistrar
+import org.springframework.beans.factory.BeanRegistry
+import org.springframework.core.env.Environment
+
+class MyGrailsPlugin extends Plugin {
+
+ @Override
+ BeanRegistrar beanRegistrar() {
+ { BeanRegistry registry, Environment environment ->
+ registry.registerBean('myService', MyServiceImpl) { spec ->
+ spec.supplier { context ->
+ new MyServiceImpl(timeout: environment.getProperty('myPlugin.timeout', Integer, 30))
+ }
+ }
+ } as BeanRegistrar
+ }
+}
+----
+
+Both hooks may be used on the same plugin during migration; when a registrar and the DSL register a bean under the same name, the registrar's definition wins.
+
+**Unit tests follow.** `doWithSpring()` on the `GrailsUnitTest` trait — and so on every testing trait — is deprecated too. A test now declares its beans in a `beans` block with the `beans` DSL, as an application or plugin does; overrides `beanRegistrar()`, applied where an application's is; or declares a static nested `@Configuration` class, which its context registers ahead of the framework's auto-configurations. A `beans` block compiles into one such class, named `BeansConfiguration`, [...]
+
+A unit test now registers an included plugin's `doWithSpring` and `beanRegistrar` beans before its configuration is read, as an application's early phase does. So a `@ConditionalOnMissingBean` bean, including one in the framework's own auto-configurations, backs off from them in a test as it does in an application. A test's `doWithSpring` bean now replaces an included plugin's bean of the same name, where the plugin's used to win. What a test's `doWithConfig` sets now also reaches the S [...]
+
+A test that already has a static nested `@Configuration` class meant for something other than its own context — one built for an `ApplicationContextRunner`, say — now has it registered there as well; override `getConfigurationClasses()` to leave it out.
+
+**A `beans` block names a nested type's bean by its simple name.** In 8.0.0-M6 and 8.0.0-RC1, `bean(Outer.Helper)` with no name given registered a bean named `outer$Helper`. It is now `helper`, the type's decapitalized simple name, as documented. Name it explicitly, `bean('outer$Helper', Outer.Helper)`, if anything looks it up by the old name.
+
+**Bean-definition overriding edge case.** Grails defaults `spring.main.allow-bean-definition-overriding` to `true`, and under that default nothing changes: an application bean (from the application class, `resources.groovy` or `resources.xml`) that uses the same name as a plugin bean still replaces the plugin's bean. However, because plugin beans now register earlier and application beans register in a separate, later step, an application that explicitly sets `spring.main.allow-bean-def [...]
+
+[[resources-groovy-configuration-classes]]
+**`@Configuration` classes registered in `resources.groovy` are no longer processed.** In Grails 7 and earlier, a class annotated with `@Configuration` could be registered as a bean in the application's `resources.groovy` or `resources.xml`, or in the `doWithSpring` of the `Application` class, and its `@Bean` methods, `@Import` and `@Enable...` annotations were still honored. This is a breaking change in Grails 8: those bean definitions register after Spring has finished parsing configu [...]
+
+`@Configuration` classes contributed by a plugin's `doWithSpring` or `beanRegistrar()` are not affected, because plugin beans now register before configuration classes are parsed.
+
+`resources.groovy` and `resources.xml` are for defining beans. Register a configuration class with Spring directly instead, either by importing it from the `Application` class:
+
+[source,groovy]
+----
+import org.springframework.context.annotation.Import
+
+import grails.boot.GrailsApp
+import grails.boot.config.GrailsAutoConfiguration
+
+@Import(MyConfiguration)
+class Application extends GrailsAutoConfiguration {
+
+ static void main(String[] args) {
+ GrailsApp.run(Application, args)
+ }
+}
+----
+
+or by annotating the `Application` class with `@ComponentScan` so that configuration classes in the application's packages are discovered.
+Alternatively, declare the beans themselves — in `resources.groovy`, or in a `beans` block on the `Application` class (see link:spring.html#springdslAdditional[Configuring Additional Beans]).
+
+Plugin authors who previously told users to replace a plugin-provided `@Configuration` class through `resources.groovy` should ship that class as a Spring Boot auto-configuration and let users customize it through `@ConditionalOnMissingBean`-guarded beans or configuration properties instead.
+
+
+==== 34. Compile-Time GORM Query Safety Check
+
+Grails 8 adds a compile-time check that can **break existing builds**: passing a GORM query method (`find`, `findAll`, `executeQuery`, `executeUpdate`, and the Neo4j Cypher equivalents) a `String`-typed variable that was built from an interpolated `GString` is now a compile error, not just a discouraged pattern.
+
+[source,groovy]
+----
+def vulnerable() {
+ String query = "from Book as b where b.title = ${params.title}" // fails to compile
+ def books = Book.executeQuery(query)
+}
+----
+
+This is flagged because passing the `GString` *directly* to `executeQuery` is safe — GORM binds the interpolated value as a query parameter — but assigning it to a `String`-typed local first causes Groovy to coerce it to a plain `String` at that point, silently discarding the safe binding; the interpolated value is then embedded as raw, unescaped query text. See <<sqlInjection,SQL injection>> for the full explanation and examples.
+
+If the interpolated expressions are values, fix it by keeping the query a `GString` all the way to the call, or by using named/positional parameters instead. If they are HQL fragments — restrictions or an `order by` clause chosen at runtime — do *not* switch to a `GString`: GORM would bind the fragment as a parameter value and the query would no longer work. Interpolating or appending *constant* text (string literals, `static final` constants, ternaries over them, and locals that only e [...]
+
+This check runs automatically wherever `grails-datamapping-core` is on the compile classpath, with no opt-in configuration required. If it produces a false positive with no workaround, the whole check can be disabled by setting the `protectSqlInjectionAttacks` system property to `false` (it defaults to `true`) — this is a last-resort, build-wide kill switch, not a substitute for the per-declaration or per-method `@SuppressWarnings` above.
+
+The same check also emits (non-build-breaking) **compile-time warnings**, not errors, for two related but lower-confidence patterns: a `String`-typed field assigned an interpolated `GString` and later read through `this.field` in a query call, and query text built with `+` concatenation from a non-constant value (constant text is never flagged) with no `GString` involved. Neither of these fails the build, but both are worth reviewing — see <<sqlInjection,SQL injection>> for examples of both.
+
+**Most applications and plugins need no action.** Behavior only changes where a plugin bean and a conditional Boot bean competed for the same name or type — the plugin bean now wins, which is almost always the intended outcome.
+
+==== 35. Extension API Compatibility Notes
+
+Most Grails applications do not call the Grails extension APIs listed below directly.
+They can affect applications, plugins, or build logic that import these public classes or override these public extension points directly.
+Unsupported internal implementation details are not covered here.
+
+[cols="1,2,2", options="header"]
+|===
+| Module
+| Changed or removed API
+| Migration note
+
+| `grails-codecs`
+| `org.grails.plugins.codecs.CodecsGrailsPlugin` no longer overrides `doWithSpring()`
+| Do not depend on that plugin override to contribute codec bean definitions.
+Custom plugins should register their own beans from their own `doWithSpring()` implementation.
+
+| `grails-controllers`
+| `ControllersAutoConfiguration.dispatcherServletRegistration(...)` now returns Spring Boot 4's `org.springframework.boot.webmvc.autoconfigure.DispatcherServletRegistrationBean`
+| Update direct imports, overrides, and binary integrations that referenced the Spring Boot 3 return type.
+
+| `grails-converters`
+| `grails.web.JSONBuilder`
+| Use Groovy's `groovy.json.JsonBuilder` or `groovy.json.StreamingJsonBuilder` for JSON builder code.
+
+| `grails-core`
+| `GrailsApplicationPostProcessor`, `ProfilingGrailsApplicationPostProcessor`, and `DefaultGrailsPluginManager` plugin-discovery wiring changed
+| Update custom bootstrapping code or subclasses that construct `GrailsApplicationPostProcessor` or `DefaultGrailsPluginManager` directly to pass the plugin-discovery dependency.
+`ProfilingGrailsApplicationPostProcessor` keeps its `GrailsApplicationLifeCycle`, `ApplicationContext`, and `Class...` constructor shape, but the application context must expose the `grailsPluginDiscovery` bean.
+This was introduced during the Grails 7.1 plugin-loading changes and remains required in Grails 8.
+
+| `grails-core`
+| `grails.plugins.PluginFilter`, `IncludingPluginFilter`, `ExcludingPluginFilter`, `NoOpPluginFilter`, and related filter types
+| Import replacement types from the `org.apache.grails.core.plugins.filters` package, such as `PluginFilter`, `IncludingPluginFilter`, `ExcludingPluginFilter`, and `NoOpPluginFilter`.
+
+| `grails-core`
+| Legacy mixin transform APIs such as `grails.util.Mixin`, `MixinTargetAware`, and `MixinTransformation`
+| Replace legacy mixin usage with Groovy traits, extension methods, or explicit composition.
+
+| `grails-core`
+| `grails.validation.ConstraintsEvaluator`
+| Use `org.grails.datastore.gorm.validation.constraints.eval.ConstraintsEvaluator`.
+
+| `grails-core`
+| `BinaryGrailsPluginDescriptor`, `CorePluginFinder`, and `BinaryGrailsPlugin.getBinaryDescriptor()`
+| Use the current plugin-discovery APIs and `BinaryGrailsPlugin.getPluginDescriptor()`.
+
+| `grails-domain-class`
+| `ConstraintEvaluatorAdapter` and `GrailsDomainClassAutoConfiguration.constraintsEvaluator(...)`
+| Code that imported the auto-configuration method should use the current `validateableConstraintsEvaluator(...)` bean path and the datastore constraint evaluator APIs. The auto-configuration itself is now named `org.grails.plugins.domain.DomainClassAutoConfiguration`, following the `*GrailsPlugin` -> `*AutoConfiguration` convention; update any `@EnableAutoConfiguration(exclude = ...)` or `spring.autoconfigure.exclude` entry that referenced the old name.
+
+| `grails-core`
+| `org.grails.plugins.core.CoreAutoConfiguration`
+| Now `org.grails.plugins.CoreAutoConfiguration`. The class is generated beside the plugin descriptor that declares its beans, and `CoreGrailsPlugin` lives in `org.grails.plugins`, so the simple name is unchanged but the package is not. Update any `@EnableAutoConfiguration(exclude = ...)`, `spring.autoconfigure.exclude`, or `@AutoConfigureAfter(name = ...)` entry naming the old package. Spring Boot only reports an invalid exclude for a class still on the classpath, so a stale entry is s [...]
+
+| `grails-cache`
+| `grails.plugin.cache.GrailsCacheAutoConfiguration`
+| Now `grails.plugin.cache.CacheAutoConfiguration`, following the `*GrailsPlugin` -> `*AutoConfiguration` convention. Update any `@EnableAutoConfiguration(exclude = ...)` or `spring.autoconfigure.exclude` entry that referenced the old name; the same silent-ignore applies as above.
+
+| `grails-databinding`
+| `org.grails.plugins.databinding.DataBindingConfiguration`
+| Now `org.grails.plugins.databinding.DataBindingAutoConfiguration`. It was registered as an auto-configuration while named only `*Configuration`; the name now says what it is. Update any `@EnableAutoConfiguration(exclude = ...)` or `spring.autoconfigure.exclude` entry that referenced the old name; the same silent-ignore applies as above.
+
+| `grails-fields`
+| `BeanPropertyAccessor.getBeanClass()`, its setter, `PropertyPathAccessor.getBeanClass()`, `FormFieldsTagLib.input(...)`, and direct `render*` helper methods
+| Use the `beanType` property exposed by the accessors.
+Custom field renderers should go through the documented `f:field`, `f:widget`, and `f:displayWidget` tags and templates instead of calling private render helpers directly.
+
+| `grails-gradle-plugins`
+| `ApplicationContextCommandTask`, `ApplicationContextScriptTask`, `ProfileCompilerTask`, and `GrailsRunTask` are abstract; `GrailsGradlePlugin.createBuildPropertiesTask(...)` no longer returns a task value; several `IntegrationTestGradlePlugin` constants were removed
+| Register these task types through Gradle task registration and update custom plugins that subclass `GrailsGradlePlugin` or read integration-test constants to use Gradle source sets, configurations, and the current test-phase APIs.
+
+| `grails-shell-cli`
+| `AetherGrapeEngine` and `AetherGrapeEngineFactory`
+| Use `MavenResolverGrapeEngine` and `MavenResolverGrapeEngineFactory` if you extend the legacy shell dependency resolver.
+
+| `grails-shell-cli`
+| JLine 2 `complete(...)` signatures
+| Implement the JLine 3 `org.jline.reader.Completer` contract, `complete(LineReader, ParsedLine, List<Candidate>)`.
+
+| `grails-spring`
+| `GrailsApplicationContext.onRefresh()`
+| Custom context subclasses should use supported Spring lifecycle extension points instead of overriding this removed hook.
+Spring theme APIs removed from the same area are covered in section 10.
+|===
+
+==== 36. Logback Configuration No Longer Generated by Default
+
+Newly generated Grails 8 applications no longer include a `grails-app/conf/logback-spring.xml` file.
+
+Logging still works out of the box. A generated application depends on `grails-logging`, which brings in Spring Boot's logging starter, so Logback and Spring Boot's own default Logback configuration apply automatically when the application supplies no configuration of its own. This matches the Spring Boot convention of needing no logging configuration file unless one is actually required.
+
+NOTE: This change affects *application generation* only. Existing applications that already contain `grails-app/conf/logback-spring.xml` are unaffected and continue to use that file.
+
+With no configuration file present you get Spring Boot's defaults: an `INFO` root level and a colorized console pattern. Levels and patterns can be tuned from `application.yml` with no XML:
+
+[source,yaml]
+.application.yml
+----
+logging:
+ level:
+ root: INFO
+ com.example.myapp: DEBUG # your packages
+ org.hibernate.SQL: DEBUG # see the generated SQL
+ pattern:
+ console: "%d{HH:mm:ss.SSS} %-5level %logger{36} - %msg%n"
+ file:
+ name: logs/myapp.log # setting this activates Spring Boot's file appender
+----
+
+Per-environment logging also needs no XML. Grails environments map to Spring profiles, so an `environments` block in `application.yml` applies levels to a single environment — for example, verbose logging for your own packages in development only:
+
+[source,yaml]
+.application.yml
+----
+environments:
+ development:
+ logging:
+ level:
+ com.example.myapp: DEBUG
+----
+
+A profile-specific `grails-app/conf/application-development.yml` containing the same `logging.level` entries works as well.
+
+Add a `logback-spring.xml` file when properties are not enough — for example custom appenders, structured/JSON output, or per-environment appender routing. Use the `-spring` variant (not plain `logback.xml`), because it is processed by Spring Boot and unlocks `<springProfile>` and `<springProperty>`. Note that once the file exists it *replaces* Spring Boot's bundled configuration entirely, so it must declare its own appenders — the simplest approach is to compose Spring Boot's own includes:
+
+[source,xml]
+.grails-app/conf/logback-spring.xml
+----
+<?xml version="1.0" encoding="UTF-8"?>
+<configuration>
+ <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
+ <include resource="org/springframework/boot/logging/logback/console-appender.xml"/>
+
+ <root level="INFO">
+ <appender-ref ref="CONSOLE"/>
+ </root>
+
+ <springProfile name="development">
+ <logger name="org.hibernate.SQL" level="DEBUG"/>
+ </springProfile>
+</configuration>
+----
+
+TIP: When generating a project with https://start.grails.org[Grails Forge], select the *Logback Configuration* feature to have a starter `grails-app/conf/logback-spring.xml` — the configuration shown above composed with a `<springProfile name="development">` block — generated for you.
+
+[[cli-companion-artifacts]]
+==== 37. CLI Commands Move to Companion `-cli` Artifacts
+
+Grails commands (`ApplicationCommand` implementations) no longer ship inside runtime plugin
+artifacts. Each command-bearing module publishes a companion artifact under its own coordinate with
+a `-cli` suffix, and commands are registered in a dedicated `META-INF/grails-cli.factories` file
+instead of `META-INF/grails.factories`.
+
+**Package rename.** The command contract moved from `grails.dev.commands.*` (in `grails-core`) to
+`org.apache.grails.core.cli.*` (in the new `org.apache.grails:grails-core-cli` artifact). Update
+imports in your `grails-app/commands` classes:
+
+[source,groovy]
+----
+// Grails 7
+import grails.dev.commands.ApplicationCommand
+import grails.dev.commands.ExecutionContext
+
+// Grails 8
+import org.apache.grails.core.cli.ApplicationCommand
+import org.apache.grails.core.cli.ExecutionContext
+----
+
+**New `grailsCli` configuration.** The Grails Gradle plugin registers a `grailsCli` configuration
+that is compile-visible for `grails-app/commands` sources and on the command-runner classpath, but
+never on `runtimeClasspath` — so commands and their CLI-only dependencies are excluded from
+`bootRun`, `bootJar`, and `bootWar`.
+
+**CLI dependencies are discovered automatically.** The plugin adds
+`org.apache.grails:grails-core-cli` (the command contract) and `org.apache.grails:grails-console`
+(the command runner) to `grailsCli`, and walks the application's resolved dependency graph —
+including transitive plugins — for jars carrying the `Grails-Cli-Artifact` manifest attribute,
+adding each advertised companion automatically. The per-command Gradle tasks (e.g. `dbmUpdate`)
+are registered from those companions as well, so no `buildscript` classpath entry is required. In
+most applications, upgrading therefore requires **no build changes** to keep plugin commands
+working:
+
+[source,groovy]
+.build.gradle
+----
+dependencies {
+ // the dbm-* commands are discovered automatically: the plugin jar advertises
+ // org.apache.grails:grails-data-hibernate7-dbmigration-cli, which is added to grailsCli
+ implementation 'org.apache.grails:grails-data-hibernate7-dbmigration'
+}
+----
+
+The `console` and `shell` tasks also draw from the provisioned cli tier, so the
+`console "org.apache.grails:grails-console"` dependency that earlier Grails versions generated in
+`build.gradle` is no longer needed and can be removed (the `console` configuration itself remains
+for additional console-only dependencies).
+
+The deprecated Grails 7 command contract is isolated in
+`org.apache.grails:grails-core-cli-legacy`. When both `cliAutoProvision` (default `true`) and
+`legacyCommandSupport` (default `false`) are enabled, the plugin adds this artifact to the
+execution-only `grailsCliLegacy` bucket. `grailsCliClasspath` includes that bucket, but application
+and plugin compile classpaths do not. Opt in so existing Grails 7 command plugins keep working
+without exposing the deprecated API to new command sources.
+
+Two flags control auto-provisioning:
+
+* `cliAutoProvision` (default `true`) controls the modern CLI tier: `grails-core-cli`,
+ `grails-console`, and discovered companion `-cli` artifacts.
+* `legacyCommandSupport` (default `false`) controls only the Grails 7 application-command bridge.
+ It is consulted only when `cliAutoProvision` is also enabled.
+
+Disable the modern CLI tier with `grails { cliAutoProvision = false }` and declare dependencies
+explicitly when full control over the command classpath is preferred:
+
+[source,groovy]
+.build.gradle
+----
+grails {
+ cliAutoProvision = false
+}
+
+dependencies {
+ implementation 'org.apache.grails:grails-data-hibernate7-dbmigration'
+ grailsCli 'org.apache.grails:grails-core-cli'
+ grailsCli 'org.apache.grails:grails-console'
+ grailsCli 'org.apache.grails:grails-data-hibernate7-dbmigration-cli'
+ grailsCliLegacy 'org.apache.grails:grails-core-cli-legacy'
+}
+----
+
+WARNING: `grails-console` is not optional in that list. It carries the entry points the Gradle tasks
+run - `grails.ui.console.GrailsSwingConsole`, `grails.ui.shell.GrailsShell`,
+`grails.ui.command.GrailsApplicationContextCommandRunner` and
+`grails.ui.script.GrailsApplicationScriptRunner`. Earlier versions reached them through the `console`
+configuration that the application generator wrote into every `build.gradle`, so the tasks worked
+without any CLI tier at all. Generated applications no longer declare that dependency, so with
+auto-provisioning off and `grails-console` omitted, `console`, `shell`, `runCommand`, `runScript` and
+`urlMappingsReport` fail with `Could not find or load main class`.
+
+Keep modern companion auto-provisioning while enabling only the Grails 7 bridge:
+
+[source,groovy]
+.build.gradle
+----
+grails {
+ legacyCommandSupport = true
+}
+----
+
+The renamed framework command packages are:
+
+|===
+|Grails 7 | Grails 8 (`-cli` artifact)
+
+|`grails.dev.commands.*` (grails-core)
+|`org.apache.grails.core.cli.*` (grails-core-cli)
+
+|`org.grails.web.mapping.reporting.UrlMappingsReportCommand`
+|`org.apache.grails.web.mapping.cli.UrlMappingsReportCommand` (grails-web-url-mappings-cli)
+
+|`scaffolding.*` commands
+|`org.apache.grails.scaffolding.cli.*` (grails-scaffolding-cli)
+
+|`grails.plugin.hibernate.commands.SchemaExportCommand`
+|`org.apache.grails.data.hibernate5.cli` / `...hibernate7.cli` (grails-data-hibernate5-cli / -7-cli)
+
+|`org.grails.plugins.databasemigration.command.*`
+|`org.apache.grails.data.hibernate5.dbmigration.cli` / `...hibernate7.dbmigration.cli`
+
+|`grails.plugin.springsecurity` s2 commands
+|`org.apache.grails.security.cli.*` (grails-spring-security-cli)
+|===
+
+===== 37.1 Backwards Compatibility for Existing Command Plugins
+
+Grails 8 provides a deprecated, execution-only compatibility layer for already-published Grails 7 command
+plugins. Application commands created with `create-command` that implement
+`grails.dev.commands.ApplicationCommand` or `grails.dev.commands.GrailsApplicationCommand` remain
+available without a plugin re-release when the bridge is enabled. The deprecated
+`grails.dev.commands.*` types are retained in `org.apache.grails:grails-core-cli-legacy`, which is
+provisioned only on the command runner classpath when both `cliAutoProvision` and
+`legacyCommandSupport` are enabled (`legacyCommandSupport` defaults to `false`), and registrations
+in `META-INF/grails.factories` under `grails.dev.commands.ApplicationCommand` continue to be
+discovered at runtime.
+
+Enable the bridge in the consuming application:
+
+[source,groovy]
+.build.gradle
+----
+grails {
+ legacyCommandSupport = true
+}
+----
+
+Or set the project property `grailsLegacyCommandSupport=true`.
+
+When the bridge is disabled, Grails still inspects legacy `META-INF/grails.factories` resources at
+command runtime without loading their command classes. If a plugin still publishes
+`grails.dev.commands.ApplicationCommand` entries, Grails logs an error naming the plugin artifact.
+An unknown command also includes the remediation to enable `legacyCommandSupport` or upgrade the
+plugin. This detection does not resolve application dependencies during Gradle configuration.
+
+Grails logs a one-time deprecation warning when it uses this compatibility layer. It is intended
+to keep existing published plugins working while plugin authors migrate; it is deprecated and may
+be removed in a future major release. No removal major has been announced.
+
+Legacy application commands do not receive a dedicated Gradle task. Run them through the generic
+`runCommand` task (or the shell, which routes legacy adapters there), for example:
+
+[source,bash]
+----
+./gradlew runCommand "-Pargs=generate-controller example.Book"
+----
+
+Named per-command Gradle tasks remain available only for migrated commands published in a
+companion `-cli` artifact.
+
+New and migrated commands should always compile against `org.apache.grails.core.cli.*` from
+`grails-core-cli`. A plugin that intentionally continues to author commands against the deprecated
+contract must declare `compileOnly 'org.apache.grails:grails-core-cli-legacy'` explicitly. Consumers
+of already-published Grails 7 command plugins must opt in with
+`grails { legacyCommandSupport = true }` (or declare `grailsCliLegacy` themselves).
+
+**What just works:**
+
+* Code generation scripts created with `create-script`, including scripts packaged as
+ `META-INF/commands/*.groovy` such as `audit-quickstart` and `s2-quickstart`, remain executable
+ through the CLI. When a plugin publishes a companion `-cli` artifact, those scripts (and
+ `META-INF/commands/*.yml` / `*.json` multi-step commands under `src/main/scripts`) are packaged
+ into the companion only - not the runtime plugin jar - and stay available via
+ `grailsCliClasspath`. Plugins without a companion continue to ship `src/main/scripts` in the
+ runtime jar, matching Grails 7 packaging.
+* Existing published Grails 7 application-command plugins continue to work on Grails 8 without a
+ re-release once `legacyCommandSupport` is enabled.
+
+**What consumers of Grails 7 command plugins must do:**
+
+* Enable `grails { legacyCommandSupport = true }` (or `-PgrailsLegacyCommandSupport=true`), or
+ declare `grailsCliLegacy 'org.apache.grails:grails-core-cli-legacy'` explicitly when
+ `cliAutoProvision` is disabled.
+
+**What plugin authors must do:**
+
+* Migrate application commands to the `org.apache.grails.core.cli.*` API and register them in
+ `META-INF/grails-cli.factories`.
+* Publish commands in a companion `-cli` artifact for the CLI classpath split and per-command
+ Gradle task support. See xref:commandLine#creatingCustomCommands[Creating Custom Commands] for
+ the complete workflow. Applying `org.apache.grails.gradle.grails-plugin-cli` also routes
+ `src/main/scripts` into that companion automatically - leave scripts under `src/main/scripts`
+ or place them under `src/cli/resources/META-INF/commands`.
+* The `copyCommands` and `copyTemplates` tasks stage into a directory of their own instead of
+ writing into the `processResources` output, and are registered when the plugin is applied rather
+ than in `afterEvaluate`. They are still `Copy` tasks, and paths are still relative to
+ `META-INF/templates` (or `META-INF/commands`), so a build script that configures them only needs
+ to drop the `afterEvaluate { }` wrapper that used to be required:
++
+[source,groovy]
+----
+tasks.named('copyTemplates', Copy) {
+ from(layout.projectDirectory.dir('grails-app/views')) {
+ into('views')
+ }
+}
+----
+* After first applying `grails-plugin-cli` on a project that was already built without it, consider
+ running `./gradlew clean` once. Older plugin packaging wrote command scripts directly into
+ `build/resources/main/META-INF/commands`; the first build on 8.0 drops those files, but the empty
+ directories they lived in remain until the build directory is cleaned. Fresh builds never place
+ companion scripts on the runtime classpath.
+
+NOTE: The compatibility layer applies only to the legacy application-command contract. Independently
+of it, a Grails 7 plugin that relies on APIs removed in Grails 8, Spring Boot 4, or other Grails 8
+changes still requires an update.
+
+==== 38. jQuery Webjar Upgraded to 4.0.0
+
+The jQuery webjar managed by the `grails-bom` (`org.webjars.npm:jquery`) moves from 3.7.1 to 4.0.0.
+jQuery 4 is a major release: it drops Internet Explorer and other legacy browsers and removes long-deprecated utilities such as `jQuery.trim`, `jQuery.type`, `jQuery.isArray`, `jQuery.isFunction`, `jQuery.proxy`, and `jQuery.isWindow`.
+See the https://jquery.com/upgrade-guide/4.0/[jQuery 4.0 Upgrade Guide] for the complete list of changes.
+
+Because the version is managed by the BOM, any application that references the jQuery webjar without an explicit version picks up 4.0.0 automatically once it adopts the Grails 8 BOM.
+This includes the generated create-app welcome page, whose assets have been verified against 4.0.0.
+
+If your application's own JavaScript relies on the removed APIs, migrate those call sites.
+If you are not ready to migrate, pin the previous version in your gradle build:
+
+[source,properties]
+.gradle.properties
+----
+jquery.version=3.7.1
+----
+
+==== 39. spring-security-ui Rewritten on Bootstrap 5
+
+The `spring-security-ui` plugin's screens are rewritten on Bootstrap 5 with no bundled styling of their own.
+The plugin no longer ships or depends on jQuery UI, jquery-form, jGrowl, DataTables, bgiframe or the bundled jdMenu/positionBy plugins, and every plugin stylesheet and image has been removed — dialogs are Bootstrap modals, tabs are nav-tabs, notifications render through `g:flashMessages`, and the autocomplete search uses a native `datalist`.
+jQuery (4.x) and Bootstrap are expected from the host application, as provided by the create-app layout.
+
+Plugin pages now render through the host application's own layout — configured with `grails.plugin.springsecurity.ui.gsp.parentLayout` (default `main`) — inheriting its theme, including Bootstrap dark mode, locale selector and branding.
+The security menu and login state are contributed to the host navbar through `nav` and `navActions` content blocks, which the create-app layout renders with `<g:pageProperty name="page.nav"/>` and `<g:pageProperty name="page.navActions"/>`; a custom layout that wants the menu in its navbar renders the same page properties.
+
+If you upgrade an application that customized the plugin:
+
+* Views previously copied into the application with `s2ui-override` reference removed stylesheets and rely on the old table-based markup of the `s2ui` field-row tags, which now emit Bootstrap form groups; regenerate or update those copies.
+* CSS written against the old `s2ui_*` and `jd_menu` classes no longer has anything to match; restyle against Bootstrap classes.
+* Applications that used the plugin's transitive webjars (jQuery UI, jGrowl, DataTables, jquery-form) must now declare those dependencies themselves.
+* The `grails.plugin.springsecurity.ui.Constants` class and the `spring-security-ui-register.js` and `spring-security-ui-*` stylesheet assets have been removed.
+* `LogoutController` now declares a computed `allowedMethods` restricting its action to POST while `logout.postOnly` is active (the default), making the restriction visible to tooling such as the create-app welcome page.
+
+==== 40. Stack Trace Filterer Configuration Reaches All Callers
+
+`grails.logging.stackTraceFiltererClass` and `grails.exceptionresolver.logFullStackTraceOnFilter` now also
+apply to paths outside the exception resolver — including GSP view-render exceptions — so the same two keys
+control which filterer is used and whether it emits, everywhere the framework filters a stack trace, not
+just for resolver-driven requests.
+
+[source, yaml]
+.grails-app/conf/application.yml
+----
+grails:
+ logging:
+ stackTraceFiltererClass: com.example.MyStackTraceFilterer
+ exceptionresolver:
+ logFullStackTraceOnFilter: false
+----
+
+Applications that previously had to silence the `StackTrace` logger in logback purely to suppress
+render-time noise can set `logFullStackTraceOnFilter: false` instead and reach every caller of the filterer.
+
+The configured filterer is resolved once during application startup, before the application context
+refreshes. Any context not started through `SpringApplication` — the CLI, plain `main()` usage, Grails unit
+tests — keeps the previous fallback behaviour unchanged: a plain `DefaultStackTraceFilterer` with no
+configuration applied. The filterer is JVM-global rather than per-context, so in a JVM hosting more than one
+application context the last one booted supplies the filterer for all of them.
+
+==== 41. Jansi Removed and Developer Tooling Off the Application Classpath
+
+Grails no longer depends on a separate ANSI library. The console renders its escape sequences directly,
+and the FuseSource Jansi artifact - unmaintained, and the subject of an unfixed CVE - is gone from the
+dependency graph along with the `org.jline:jansi` fork that briefly replaced it.
+
+At the same time, developer-only tooling no longer ships with an application. These artifacts could reach
+an application's production runtime classpath, by a different route for each:
+
+* `org.apache.grails:grails-console` - the Swing console, the Groovy shell, and the script and command
+ runners - and the `org.apache.groovy:groovy-console`, `groovy-groovysh` and `groovy-swing` libraries it
+ brings with it, through the `console` configuration the application generator declared
+* the JLine family, including `org.jline:jansi`, and the FuseSource Jansi artifact, declared directly by
+ the generated build
+
+None of these are on an application's runtime classpath now. They are provisioned onto the `grailsCli`
+configuration instead, which the Grails Gradle plugin puts on the compile and test classpaths but never on
+`runtimeClasspath` - so `bootRun`, `bootJar` and `bootWar` no longer carry them. The `console` and `shell`
+tasks are unaffected and continue to work exactly as before.
+
+===== What you need to change
+
+Applications generated by earlier versions of Grails declare Jansi explicitly:
+
+[source,groovy]
+.build.gradle
+----
+runtimeOnly "org.fusesource.jansi:jansi"
+----
+
+Delete that line. New projects are generated without it.
+
+If your own code imports Jansi directly, it must move off it - there is no Grails-managed replacement
+coordinate. Application code that needs coloured output should use Spring Boot's
+`org.springframework.boot.ansi.AnsiOutput`, or JLine's `org.jline.utils.AttributedStringBuilder` if the
+project already depends on JLine.
+
+If your code, or a `runtimeOnly` dependency of it, genuinely needs the Groovy shell, Swing console or JLine
+at application runtime, declare that dependency explicitly rather than relying on the starter:
+
+[source,groovy]
+.build.gradle
+----
+runtimeOnly "org.apache.groovy:groovy-groovysh"
+----
+
+===== Controlling ANSI output
+
+Jansi's global switch went away with the library. Console colour is now driven by Spring Boot's own
+property, so it is configured in one place alongside the rest of the application's output settings:
+
+[source,yaml]
+.application.yml
+----
+spring:
+ output:
+ ansi:
+ enabled: never # always | detect | never
+----
+
+`detect` is the default and keeps the previous behaviour - colour only when the attached terminal
+supports it. `never` suppresses it entirely, and `always` forces it on even when the terminal is not
+detected as capable, which is useful for CI logs that render ANSI.
+
+The same property works as a system property, which is how the CLI reads it since it has no Spring
+`Environment` to bind from:
+
+[source,bash]
+----
+grails -Dspring.output.ansi.enabled=never run-app
+----
+
+Note that passing `-D` to `gradlew` sets the property on the Gradle daemon, not on the JVM that
+`bootRun` forks for your application, so it has no effect there. To disable colour for `bootRun`, use
+the `application.yml` form above or set it on the task itself:
+
+[source,groovy]
+----
+tasks.named('bootRun') {
+ systemProperty 'spring.output.ansi.enabled', 'never'
+}
+----
+
+If you previously disabled colour through Jansi's own switch, replace it - the property no longer has any
+effect now that the library is gone:
+
+[cols="1,1"]
+|===
+|Before |Now
+
+|`-Dorg.fusesource.jansi.Ansi.disable=true`
+|`-Dspring.output.ansi.enabled=never`
+|===
+
+===== Remove `withJansi` from your Logback configuration
+
+Logback's `ConsoleAppender` has a `withJansi` option that loads `org.fusesource.jansi.AnsiConsole` by
+name to wrap the output stream. With Jansi gone from the dependency graph, an application that still
+enables it logs a warning on every startup and falls back to the plain stream:
+
+[source]
+----
+-WARN in ch.qos.logback.core.ConsoleAppender[STDOUT] - Failed to create AnsiPrintStream. Falling back
+on the default stream. java.lang.ClassNotFoundException: org.fusesource.jansi.AnsiConsole
+----
+
+Delete the element from `grails-app/conf/logback.xml` or `logback-spring.xml`:
+
+[source,xml]
+----
+<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+ <withJansi>true</withJansi> <!--1-->
+ <encoder>
+ ...
+ </encoder>
+</appender>
+----
+<1> remove this line
+
+Nothing is lost. Coloured log output comes from Spring Boot's `ColorConverter` - the `%clr(...)` tokens
+in the encoder pattern - which is independent of Jansi and honours `spring.output.ansi.enabled`. The
+`withJansi` option only wrapped the stream for legacy Windows consoles.
+
+Applications generated by recent versions of Grails already omit it: Jansi's global `System.out`
+replacement breaks console logging after a Spring Boot DevTools restart
+(https://github.com/apache/grails-core/issues/15663[issue #15663]), so it was removed from the
+generated configuration before Jansi itself was dropped. Only applications carrying older
+configuration forward need this change.
+
+===== `GrailsConsole` moved to a companion artifact
+
+The console classes are developer tooling, so they now ship as `grails-bootstrap`'s CLI companion
+rather than in the artifact applications depend on. These types moved out of
+`org.apache.grails.bootstrap:grails-bootstrap` and into
+`org.apache.grails.bootstrap:grails-bootstrap-cli`:
+
+* `grails.build.logging.GrailsConsole`
+* `grails.build.logging.ConsoleLogger`
+* `grails.build.logging.GrailsEclipseConsole`
+* `org.grails.build.logging.GrailsConsolePrintStream`
+* `org.grails.build.logging.GrailsConsoleErrorPrintStream`
+* `org.grails.build.logging.GrailsConsoleAntBuilder`
+* `org.grails.build.logging.GrailsConsoleBuildListener`
+* `org.grails.build.interactive.CandidateListCompletionHandler`
+
+The URL mappings report renderer moved the same way, out of `org.apache.grails:grails-url-mappings`
+and into `org.apache.grails:grails-url-mappings-cli`:
+
+* `org.grails.web.mapping.reporting.AnsiConsoleUrlMappingsRenderer`
+
+Their package names are unchanged - only the artifact that carries them is different.
+
+Command code needs no change: the CLI tier is auto-provisioned onto `grailsCli`, so commands in
+`grails-app/commands` and in a plugin's `src/cli` continue to see `GrailsConsole` as before.
+
+If application code (not command code) references any of these types, it was relying on developer
+tooling being present at runtime. Prefer a logger, or Spring Boot's
+`org.springframework.boot.ansi.AnsiOutput` for coloured output. If the dependency is genuinely
+required, declare the companion explicitly:
+
+[source,groovy]
+.build.gradle
+----
+implementation "org.apache.grails.bootstrap:grails-bootstrap-cli"
+----
+
+Test code that extended `GrailsConsolePrintStream` to capture output does not need it: that class
+routes output through the CLI console, which a test almost never wants. Extend `java.io.PrintStream`
+directly instead.
+
+==== 42. Plugin Authors: Separate Source Sets for the CLI Tier
+
+This affects plugins that apply `org.apache.grails.gradle.grails-plugin-cli` and therefore publish a
+companion `-cli` artifact.
+
+Previously the `cli` source set's output and its dependencies were added to the plugin's `test`
+classpath, so unit tests saw CLI classes and CLI-only libraries that an application never receives. A test
+could pass against something that was not actually there in production.
+
+The `cli` tier now has its own test source sets:
+
+[cols="1,2"]
+|===
+|Source set |Purpose
+
+|`src/test-cli`
+|Tests for CLI classes. Runs as the `testCli` task, wired into `check`.
+
+|`src/integration-test-cli`
+|CLI tests that need a booted application - a command starts one the same way the shell does. Runs as the
+`integrationTestCli` task.
+|===
+
+Both are created by `org.apache.grails.gradle.grails-plugin-cli`, so there is nothing to declare: create the
+folder, add a spec, and the task picks it up.
+
+`src/test` no longer sees the CLI tier at all. Move any existing spec that exercises a command or another
+CLI class into `src/test-cli`, or into `src/integration-test-cli` if it boots an application.
+
+Both CLI test source sets can read the module's `main` and `test` output, so shared fixtures stay where they
+are. `src/integration-test-cli` additionally reuses `src/integration-test/resources` when that folder exists,
+since both integration phases boot the same application and its configuration should not be duplicated.
+
+The relationship between the source sets is deliberately one-way: CLI tests may use test fixtures, but
+ordinary tests never see CLI classes, which is what keeps the `test` classpath a faithful stand-in for
+production.
+
+==== 43. `gspCompile` Configuration Removed
+
+The `org.apache.grails.gradle.grails-gsp` plugin no longer registers a `gspCompile` configuration.
+
+It dated back to the original Ant-based GSP compiler, where it carried the classpath that compiler ran
+against. Once GSP compilation moved to a forked compile task the configuration's only remaining content was
+a hardcoded servlet API dependency, and that dependency has itself been removed — the servlet API already
+reaches GSP compilation through the regular compile classpath, at the version the BOM manages.
+
+GSPs continue to compile against the project's `compileClasspath`, its compiled classes, and — for a WAR
+build — `providedCompile`. No application that leaves the configuration alone is affected.
+
+A build that declares dependencies on `gspCompile` fails with `Could not find method gspCompile()`. Move
+those declarations to `compileOnly`, which places them on the compile classpath that GSP compilation uses:
+
+[source,groovy]
+.build.gradle
+----
+dependencies {
+ // Grails 7
+ // gspCompile 'com.example:some-library:1.0'
+
+ // Grails 8
+ compileOnly 'com.example:some-library:1.0'
+}
+----
+
+==== 44. `grails.spring.bean.packages` Scanning Fixed Outside the Project Directory
+
+The component scan driven by `grails.spring.bean.packages` resolved its search root from a probe of the
+*working directory* — it looked for a `grails-app` directory or an `Application.groovy` beside it — and
+returned nothing when neither was there. An application started from anywhere other than its project root
+therefore registered none of the `@Component` classes in the configured packages, silently.
+
+That covers most production shapes: a systemd unit with its own `WorkingDirectory`, a container with a
+`WORKDIR`, an application server. `java -jar build/libs/app.jar` run from the project root was unaffected,
+which is why the gap survived. The scan now uses Spring's own resource resolution, so the packages are
+scanned wherever the process is started from.
+
+[source, yaml]
+.grails-app/conf/application.yml
+----
+grails:
+ spring:
+ bean:
+ packages:
+ - com.example.components
+----
+
+**Applications deployed this way will start getting beans they previously did not.** The scan registers
+every `@Component`, `@Service`, `@Repository` and `@Controller` in the listed packages. Two things to check
+before upgrading:
+
+* A class in one of those packages that was never actually reaching the context — because it duplicates a
+bean the application defines elsewhere, or because it was left behind — now registers. A duplicate under the
+same bean name will fail startup rather than pass silently.
+* Beans that were previously absent may now participate in autowiring by type, so an injection point that
+resolved unambiguously before can become ambiguous.
+
+Removing the packages from `grails.spring.bean.packages`, or the stray classes from those packages, restores
+the previous set of beans.
+
+==== 45. GORM API Resolution Moves to a Registry
+
+GORM no longer allocates an API object for every (entity, connection) pair up front. Per-entity, per-qualifier
+state now lives in a registry (`org.grails.datastore.gorm.GormRegistry`), and APIs are built on first use by a
+pluggable factory. For applications this is invisible — `Book.list()`, dynamic finders, and
+`Book.withNewSession { }` behave as before. It does change some extension points that out-of-tree GORM
+implementations subclass.
+
+===== GormEnhancer
+
+`org.grails.datastore.gorm.GormEnhancer`'s public constructors, `enhance()`/`enhance(PersistentEntity)`,
+`dynamicEnhance`, and the `transactionManager` field are all unchanged in behaviour and signature (the
+`transactionManager` field is now `@Deprecated` and immutable after construction — read it, don't assign it).
+
+The following members were removed:
+
+[cols="1,2", options="header"]
+|===
+| Removed
+| Migration note
+
+| `finders` field / `getFinders()`
+| Use `createDynamicFinders(Datastore)`, or read the finders from the API object you are working with.
+
+| `removeConstraints()`
+| Moved to `GormRegistry.removeConstraints()`, called automatically from `GormRegistry.removeDatastore(Datastore)`
+as part of tearing a datastore down. There is nothing to call directly - it runs when the enhancer's `close()`
+removes the datastore from the registry, same as before.
+
+| `addStaticMethods(PersistentEntity, boolean)` / `addInstanceMethods(PersistentEntity, boolean)`
+| The `onlyExtendedMethods` parameter is gone; both methods now take only the entity. Installation mechanism
+also changed from per-method reflective registration to a single `methodMissing`/`propertyMissing` handler pair.
+
+| `findTenantId`, `apiQualifiers`, `findDatastoreByType`, `findSingleDatastore`,
+`findSingleTransactionManager`, `findTransactionManager(Class, String)`, `appliesToDatastore`,
+`getInstanceMethodApiProviders`, `registerStaticMethod`, `registerInstanceMethod`, `doesRealMethodExist`,
+`isRealMethod`
+| Internal helpers of the old per-method reflective registration mechanism, replaced wholesale by the registry
+and its `methodMissing`/`propertyMissing` handlers. If you overrode one of these to customise dispatch, override
+`registerApiFactories()` (below) or a `GormApiFactory` instead.
+|===
+
+A new `registerApiFactories()` hook is called once, before any entity is registered. Adapters that build
+specialised API objects should override it:
+
+[source,groovy]
+----
+class MyGormEnhancer extends GormEnhancer {
+
+ @Override
+ protected void registerApiFactories() {
+ GormRegistry.instance.registerApiFactory(MyDatastore, new MyGormApiFactory())
+ }
+}
+----
+
+WARNING: Earlier snapshots of this work registered API factories from `registerConstraints(Datastore)`.
+Move that code to `registerApiFactories()`; factory registration must not depend on the constraints lifecycle step.
+
+===== CurrentTenantHolder.get()
+
+`grails.gorm.multitenancy.CurrentTenantHolder.get()` — the no-argument form — now throws `TenantException` when
+different datastores hold different tenants on the calling thread, rather than returning an arbitrary one of
+them. Pass the datastore you are operating on:
+
+[source,groovy]
+----
+CurrentTenantHolder.get(datastore)
+----
+
+See <<multiTenancy,Multi-Tenancy>> for the full multi-tenancy API.
+
+===== Tenants.withId(Class, Serializable, Closure)
+
+`grails.gorm.multitenancy.Tenants` had two distinct 3-argument `withId` overloads that both erased to
+`withId(Class, Serializable, Closure)` at the bytecode level:
+
+[source,groovy]
+----
+// removed - resolved a datastore by its own type
+static <T> T withId(Class<? extends Datastore> datastoreClass, Serializable tenantId, Closure<T> callable)
+
+// kept - resolves the datastore that maps a domain class
+static <T> T withId(Class domainClass, Serializable tenantId, Closure<T> callable)
+----
+
+The datastore-class overload relied on `GormEnhancer.findDatastoreByType(Class)`, which was one of the internal
+per-method-dispatch helpers removed as part of the registry migration (see <<_gormenhancer,GormEnhancer>>
+above), so it could not be carried forward under its own name. Only the domain-class overload remains.
+
+Because both overloads share one erased signature, a call site that used to pass a datastore class -
+`Tenants.withId(SomeDatastore, tenantId) { ... }` - still compiles unchanged against the domain-class overload.
+It no longer resolves the datastore you named: `getDatastoreForDomain(SomeDatastore)` looks `SomeDatastore` up as
+if it were a *domain class*, finds no entity registered under that name, and falls through to the application's
+`DEFAULT` datastore. On a single-datastore application this is indistinguishable from the old behaviour. On a
+multi-datastore application it silently binds the tenant against the wrong datastore - no exception, no log -
+which can surface much later as a cross-database read or write.
+
+If you have a call site that passes a `Datastore` subclass to this method, migrate it to look the datastore up
+explicitly and call the datastore-instance overload instead. `Tenants.datastoreLocator` still resolves a
+datastore by its type - only the `withId(Class, ..)` shortcut for it is gone:
+
+[source,groovy]
+----
+MultiTenantCapableDatastore datastore = Tenants.datastoreLocator.getDatastore(SomeDatastore) as MultiTenantCapableDatastore
+Tenants.withId(datastore, tenantId) { ... }
+----
+
+or pass an actual domain class if that is what you meant:
+
+[source,groovy]
+----
+Tenants.withId(SomeDomainClass, tenantId) { ... }
+----
+
+
+==== 46. Startup Banner Shows the Servlet Container and Spring Security
+
+The banner now reports the servlet container it is running on, and the version of Spring Security where the
+application has it, without being asked for either. Both were previously opt-in through
+`grails.banner.versions.include`.
+
+What made them opt-in was that a version which could not be determined was shown as `unknown`, so turning one
+on by default would have printed `Spring Security: unknown` for every application without it. A version shown
+by default that cannot be determined is now left out instead, which is what allows the two to be shown at all.
+A version the application asked for by name still reads `unknown` where it cannot be determined, since saying
+nothing about something that was asked for reads as the option having been ignored.
+
+The container is named as itself: an application on Tomcat shows `Tomcat`, one on Jetty shows `Jetty`. It is
+configured under the single key `container`, whichever container that turns out to be.
+
+To restore the previous banner, exclude them:
+
+[source, yaml]
+.grails-app/conf/application.yml
+----
+grails:
+ banner:
+ versions:
+ exclude:
+ - container
+ - spring-security
+----
+
+An application that already asked for `spring-security` under `grails.banner.versions.include` keeps working
+and needs no change — the option is still recognised, and the version is shown either way. The same is true
+of `tomcat`, `jetty` and `undertow`, which remain available for an application that wants to be told about a
+particular container whether or not it is the one serving; naming one as well as taking the default shows it
+once, not twice.
+
+A version option that names none of the known keys is now reported as a warning after the banner is printed,
+rather than being dropped in silence.
+==== 47. Message Bundles Resolved by Spring Boot
+
+Grails no longer registers a `messageSource` bean. Spring Boot's `MessageSourceAutoConfiguration`
+supplies a standard `ResourceBundleMessageSource`, and Grails contributes only the base-name list, which
+it records at build time rather than discovering by scanning the classpath at runtime.
+
+Most applications need no change. The rest of this section covers the cases that do.
+
+===== `spring.messages.*` is now the configuration surface
+
+`spring.messages.*` was previously ignored, because Grails' own message source claimed the bean name and
+Boot's auto-configuration backed off. It is now honoured in full — `encoding`, `cache-duration`,
+`fallback-to-system-locale`, `always-use-message-format`, `use-code-as-default-message` and
+`common-messages`.
+
+Two Grails settings give way to it:
+
+[cols="2,2,3"]
+|===
+|Setting |Replacement |Status
+
+|`grails.i18n.cache.seconds`
+|`spring.messages.cache-duration`
+|Deprecated, still honoured for now — see below
+
+|`grails.i18n.filecache.seconds`
+|None
+|Ignored
+|===
+
+`grails.i18n.cache.seconds` is still honoured as a temporary upgrade aid: it is translated into
+`spring.messages.cache-duration` and logs a deprecation warning. As before, it applies only when reload
+is enabled, so an application that set it for development keeps the timing it had. Setting
+`spring.messages.cache-duration` explicitly always wins. Migrate before it is removed.
+
+`grails.i18n.filecache.seconds` has no replacement and is ignored: it tuned the file-timestamp re-check
+of the message source Grails used to own, which Spring Boot's has no equivalent for.
+
+`grails.i18n.availableLocales.includePlugins` is replaced by `grails.i18n.include-plugin-bundles`, which
+now governs both message resolution and the locales offered by a language selector, so the two can no
+longer disagree.
+
+===== Plugin authors: base names must be namespaced
+
+A plugin's message bundle base names must be its plugin name, or that name followed by a hyphen and a
+suffix:
+
+[source]
+----
+grails-app/i18n/spring-security-core.properties <1>
+grails-app/i18n/spring-security-core_fr.properties
+grails-app/i18n/spring-security-core-validation.properties <2>
+----
+<1> the plugin's own name
+<2> further bundles inside its namespace
+
+The plugin build fails otherwise. A plugin shipping `messages.properties` used to contribute messages as
+a fallback behind the application's own bundle; Spring resolves a base name to the first matching
+resource on the classpath, so such a bundle would now silently shadow, or be shadowed by, the
+application's. Rename it into the plugin's namespace.
+
+Applications are unaffected — there is only one application, so its base names cannot collide.
+
+A namespaced bundle still works under Grails 7, so a plugin does not need a separate source branch to
+support both. Grails 7 discovers a plugin's bundles by scanning the plugin jar's root for
+`*.properties` and matching locale suffixes; it never inspects the base name, so
+`spring-security-core.properties` and `spring-security-core_fr.properties` are found exactly as
+`messages.properties` was. The `spring-security-core` plugin has shipped this layout for years. Rename
+once, and the same source builds for both: Grails 7 finds the bundles by scanning, Grails 8 through the
+generated descriptor.
+
+===== Every bundle needs a locale-independent file
+
+Spring Boot's auto-configuration only activates when a configured base name has a bundle without a
+locale suffix, and it contributes the whole `messageSource` bean. An application shipping only
+`messages_de.properties` would therefore have had no message source at all, so the build now rejects it.
+
+===== Ambiguous base names must be declared
+
+A base name ending in a valid locale identifier is ambiguous: `api_fr.properties` reads as base name
+`api` in French. Likewise `api_errors.properties` alongside `api.properties` reads as a mistyped locale
+variant of `api`. Both fail the build; declare the base name when the inference is wrong:
+
+[source,groovy]
+----
+grails {
+ i18n {
+ basenames = ['api', 'api_errors']
+ }
+}
+----
+
+===== `PluginAwareResourceBundleMessageSource` removed
+
+`org.grails.spring.context.support.PluginAwareResourceBundleMessageSource` and the Grails fork of
+`ReloadableResourceBundleMessageSource` beside it are removed. Code that injected `MessageSource` is
+unaffected. Code that cast the bean to either type, or called `getBundleCodes()`, must be updated —
+inject `MessageSource` and use its interface, or declare your own bean, which Boot's auto-configuration
+backs off from.
+
+===== Language selectors read the same plugin set as message resolution
+
+The locales offered by `g:localeSelect available="true"` now come from the recorded bundles rather than a
+classpath scan, and they follow exactly the plugin set that message resolution uses. A plugin that was
+evicted, excluded, or failed to load no longer contributes a language entry, so a selector can no longer
+offer a translation whose messages will not resolve.
+
+An application that declares its own `AvailableLocaleResolver` bean must supply the effective descriptors
+instead of a `ClassLoader`; most applications simply rely on the one Grails registers.
+
+===== Reloading during development
+
+Editing a value in an existing bundle still reloads without a restart: Grails contributes a short
+`spring.messages.cache-duration` when reload is enabled, in place of the `grails.i18n.cache.seconds` it
+used to apply to its own message source.
+
+Adding or removing a base name now needs a restart, because Spring Boot reads the configured base names
+once when it builds the message source.
+
+==== 48. CAS Single Sign-Out Is Opt-In
+
+`grails.plugin.springsecurity.cas.useSingleSignout` now defaults to `false`. It previously defaulted
+to `true`, so every CAS application registered the CAS client's `SingleSignOutFilter` whether or not
+it wanted single sign-out.
+
+The default changed because enabling single sign-out is a security trade-off rather than a free
+feature. CAS maps the service ticket to the HTTP session id, so single sign-out cannot work while
+session fixation prevention is replacing the session when the user authenticates. Enabling
+`cas.useSingleSignout` disables session fixation prevention, and an application should make that
+choice deliberately.
+
+If your application relies on CAS single sign-out, enable it explicitly:
+
+[source,groovy]
+.grails-app/conf/application.groovy
+----
+grails.plugin.springsecurity.cas.useSingleSignout = true
+----
+
+The plugin logs a warning at startup when it is enabled, noting that session fixation prevention has
+been disabled.
+
+**Single sign-out did not actually work before Grails 8**, so an application upgrading from an
+earlier version is unlikely to lose working behaviour. The plugin set
+`useSessionFixationPrevention = false` from `doWithSpring`, but it declares `loadAfter =
+['springSecurityCore']`, so the core plugin had already defined `sessionAuthenticationStrategy` from
+the original value. The filter was registered, the session was still replaced on login, and CAS
+logout requests silently matched nothing. Grails 8 also redefines `sessionAuthenticationStrategy`
+from the CAS plugin, so enabling `cas.useSingleSignout` now has the documented effect.
+
+The Spring Security CAS configuration reference in this guide documents the setting in full.
+
+==== 49. GSPs Record a Source Checksum Instead of a Modification Time
+
+A GSP used to carry the modification time of its `.gsp` source, precompiled pages baking it into the
+generated class as a `LAST_MODIFIED` constant. Git stores no modification times, so every fresh clone or CI
+checkout gave each source a new one, and the generated classes differed on every checkout even when the
+sources were byte-for-byte identical. Because `LAST_MODIFIED` was a compile-time constant it was part of the
+class's ABI, so the difference survived even Gradle's compile-classpath normalization and every task
+downstream of a jar containing precompiled GSPs missed the build cache.
+
+Grails 8 records a `SOURCE_CHECKSUM` of the page source instead, for pages compiled at build time and at
+runtime alike. Identical sources now compile to identical bytes on every machine.
+
+Runtime reloading, described in
+<<makingChangesToADeployedApplication,Making Changes to a Deployed Application>>, is unaffected: a page is
+reloaded when its source no longer matches the recorded checksum. Detection is more accurate than it was.
+An edit is caught whenever the source's modification time or length moves, which any ordinary save does;
+previously a save landing within the old granularity window went unnoticed until a later edit moved it
+clear. In the other direction, a page whose modification time moves without its content changing is no
+longer recompiled, so touching a file — or a build step copying views into place — no longer reloads pages
+that did not actually change. If you were using `touch` to force a page to recompile, edit the page instead.
+
+**Removed API.** `GroovyPageMetaInfo.getLastModified()`, `setLastModified(long)` and
+`applyLastModifiedFromResource(Resource)` are gone, as are `GroovyPageParser.getLastModified()` and
+`setLastModified(long)`. Use `GroovyPageMetaInfo.getSourceChecksum()` to identify the source a page was
+compiled from. Generated page classes no longer declare a `LAST_MODIFIED` constant.
+
+**Removed setting.** `grails.gsp.reload.granularity` is gone. It existed to absorb rounding differences
+between modification times, which comparing content does not need; setting it now has no effect.
+`grails.gsp.reload.interval` is unchanged.
+
+A GSP precompiled by Grails 7 and shipped inside a binary plugin carries no checksum. Such a page is served
+normally; it is simply never reload-checked, which was already the case for views resolved out of a plugin
+jar.
+
+==== 50. The Hidden HTTP Method Filter Is Disabled by Default
+
+Grails has always registered a servlet filter that rewrites a `POST` into a `PUT`, `PATCH` or `DELETE` when the
+request carries a `_method` parameter or an `X-HTTP-Method-Override` header. It runs ahead of the dispatcher --
+and ahead of the Spring Security filter chain. **As of Grails 8 it is no longer registered by default.**
+
+Browser forms keep working. The `_method` parameter is still honoured; it is resolved inside the dispatcher
+instead, after multipart handling and after the filter chain. `<g:form method="DELETE">`, the scaffolded views
+and existing GSP templates need no changes.
+
+===== 50.1 Why the default changed
+
+The filter reads a request parameter before the dispatcher runs. Because a `MultipartConfigElement` is attached
+to the dispatcher servlet registration, the servlet container resolves it at filter time, so reading `_method`
+on a `multipart/form-data` POST forces the container to parse the entire body -- writing its temporary files --
+**before the request has been routed or authenticated**. An unauthenticated request can therefore cause uploads
+to be written to disk.
+
+Spring Boot disabled its equivalent filter by default in 2.2 for the same reason: it "causes early consumption
+of a request body if the body may contain parameters".
+
+The filter is also wider than Spring's. Spring's `HiddenHttpMethodFilter` reads only the `_method` parameter and
+honours only `PUT`, `PATCH` and `DELETE`. The Grails filter additionally trusts the `X-HTTP-Method-Override`
+header -- which any client can set -- and applies **any** method name it is given, including `GET`. The
+in-dispatcher resolution that replaces it accepts the parameter only, and only those three methods.
+
+===== 50.2 What changes for an application
+
+* **`POST` to a member URL now reaches `update`.** A `resources` mapping generates `POST /books/$id` alongside
+`PUT /books/$id`. `RestfulController` has permitted `POST` for `update` since Grails 3 (issue #9926, raised
+because AngularJS `$resource` and the clients modelled on it POST to save an existing object) but no mapping
+was ever generated for it. That is now fixed, and it is what lets a client submit without a `_method` parameter.
++
+This is a route that did not exist before, so a `POST` an application previously rejected at the member URL now
+reaches `update`. An authorization rule written to permit `POST` to the collection -- `POST /books` to create --
+will permit `POST /books/1` too wherever it is expressed as a prefix. **Review any rule that grants `POST` on a
+`resources` path before upgrading**, or keep the route out entirely by enabling the filter as described below.
+* **`<g:form>` is unchanged.** A form asking for `PUT`, `PATCH` or `DELETE` still submits a `POST` carrying a
+`_method` field, and the dispatcher resolves it. The route above is a fallback for a request that arrives
+without the parameter — an AngularJS-style client, or a hand-written form — rather than a replacement for it:
+it reaches `update` alone, so it answers for neither a `PATCH` nor a `DELETE` form, it is not generated for a
+singular `resource` mapping, and it says nothing about a URL an application has mapped to `PUT` itself.
+* **Servlet filters see the real request method.** This is the one consequence that fails silently. A `POST`
+carrying `_method=DELETE` now reaches Spring Security and every servlet filter as a `POST`, because the rewrite
+happens inside the dispatcher. A security rule matching `DELETE /books/**` **will no longer fire for a browser
+form submit**, and since the URL is unchanged, `update` and `delete` cannot be told apart by path either.
+**Review any authorization rule keyed on the HTTP method before upgrading.**
+* **`X-HTTP-Method-Override` is no longer honoured**, and a `_method` value other than `PUT`, `PATCH` or
+`DELETE` is ignored rather than applied. This one fails silently for a non-browser client: a proxy or SDK
+that rewrites `DELETE` into `POST` plus the header now has its `POST /books/1` answered by `update` with a
+`200`, while the caller believes it issued a `DELETE`. **Enable the filter for an application any such client
+talks to**, which restores both the header and the unrestricted method names.
+
+* **A filter registered by the application does not by itself select filter mode.** The mode is read from
+`grails.web.hiddenmethod.filter.enabled` and `spring.mvc.hiddenmethod.filter.enabled` only. An application
+that registers its own `HiddenHttpMethodFilter` bean without setting either property gets that filter *and*
+the dispatcher-mode behaviour described here, including the generated `POST` member route. Set the property
+alongside the bean.
+
+* **A controller's `request.method` reports `POST`.** The servlet request reports the method the request
+arrived as -- the one Spring Security saw and the access log recorded. That is deliberate: with the rewrite
+moved out of the filter chain, a request object that reported anything else would put back the divergence
+between what an application sees and what the infrastructure saw.
++
+Everything Grails resolves *from* the request answers with the overridden method instead, so that an
+application behaves the same whichever mode is in force:
++
+[cols="1,1"]
+|===
+|Reports the overridden method |Reports the method on the wire
+
+|URL mapping resolution, including a method-keyed `controller`/`action` name
+|`request.method`, and the servlet request generally
+
+|`allowedMethods`
+|Spring Security and every other servlet filter
+
+|Link generation, when no `method` attribute is given
+|The container's access log
+
+|`RenderContext.getHttpMethod()`
+|
+
+|Command object initialization, and whether a request body is bound
+|
+|===
++
+Anything branching on `request.method` itself for a `PUT`, `PATCH` or `DELETE` form submit needs
+`allowedMethods`, separate actions, or its own read of the parameter. Enabling the filter restores the old
+reading, as described below.
+
+===== 50.3 Restoring the previous behaviour
+
+[source,yaml]
+.grails-app/conf/application.yml
+----
+grails:
+ web:
+ hiddenmethod:
+ filter:
+ enabled: true
+----
+
+That restores the filter exactly as it behaved in Grails 7, including the header and the unrestricted method
+names, and suppresses the `POST` member route so the mappings a `resources` block generates are unchanged.
+
+Spring Boot's `spring.mvc.hiddenmethod.filter.enabled` selects the same mode, registering Spring's filter
+rather than the Grails one. Either property is enough: whichever is set, a filter is on the chain, the
+dispatcher stops resolving `_method` itself, and the `POST` member route is not generated.
+
+NOTE: Spring's filter is contributed by `WebMvcAutoConfiguration`, which backs off entirely for an application
+declaring `@EnableWebMvc`. Grails contributes its own filter in that case, so asking for Boot's still leaves a
+filter on the chain rather than silently leaving none. Previously the two definitions could also collide on the
+shared `hiddenHttpMethodFilter` bean name and fail application startup; they no longer can.
+
+
+==== 51. Tag Libraries Are Described When Compiled
+
+Tag calls are resolved against a description each tag library contributes as it is compiled, and a
+resolved call is compiled into a direct invocation. The tag itself is still selected by name when the
+call runs, through the same lookup dynamic dispatch uses, so a tag library that overrides another and
+the order tag libraries are registered in behave as before. A call into a namespace no compiled tag
+library declares — a tag library from a plugin built against an earlier version of Grails, or one
+registered while the application runs — is left to dispatch exactly as it did.
+
+Three things are worth knowing when upgrading.
+
+A tag that no compiled tag library declares is left to resolve at runtime, and nothing is reported.
+Setting `grails { compileStatic { strictTags = true } }` makes it a compilation error instead, which
+is worth doing once to find misspelled tags, but is not the default because a namespace can
+legitimately hold tag libraries that carry no description. Where an application registers tag
+libraries while it runs, name their namespaces in
+`grails { compileStatic { dynamicTagNamespaces = [...] } }` so that they are never checked.
+
+Strict checking applies only where the source says a call is a tag: one naming its namespace, and one
+written as markup. A call written without a namespace is never checked, and a namespaced expression in
+a page is checked only when that page declares `compileStatic`.
+
+A call written without a namespace is not compiled at all unless the build asks for it with
+`grails { compileStatic { unqualifiedTagCalls = true } }`. Whether a bare name is a tag depends on what
+else answers to it, and not all of that is visible when compiling — a method Groovy gives every object,
+a delegate an enclosing closure is handed, an overload the tag library also declares — so by default
+such a call is dispatched exactly as it was before this release.
+
+Where it is turned on, a call written without a namespace reaches a tag only when nothing nearer
+answers to the name: not a method of the class, not one it inherits, not a field, property or local,
+not a method Groovy provides, and not a name inside a closure, whose delegate is only known when it
+runs. A method added to a controller or tag library *while the application runs*, through a plugin's
+`doWithDynamicMethods`, is not visible when the calling code is compiled, so a call that used to reach
+such a method and shares its name with a tag would reach the tag instead. Declare the method on the
+class, name the namespace in `dynamicTagNamespaces`, or call the tag with its namespace.
+
+Naming a namespace in `dynamicTagNamespaces` turns rewriting off for it entirely, not just the
+reporting: calls into it are dispatched exactly as they were before this release. That is the escape
+hatch for a namespace whose tags are decided while the application runs.
+
+Tags defined as closures now warn at compile time. They still work and are called the same way, but a
+closure carries no signature, so nothing about a call to such a tag can be checked. This covers the
+`def` form as well as the explicitly typed one, and the `def` form is the one most tag libraries are
+written in:
+
+[source,groovy]
+----
+// Before - both forms warn
+def hello = { attrs ->
+ out << "Hello ${attrs.name}"
+}
+
+Closure goodbye = { Map attrs ->
+ out << "Goodbye ${attrs.name}"
+}
+
+// After
+def hello(Map attrs) {
+ out << "Hello ${attrs.name}"
+}
+
+def goodbye(Map attrs) {
+ out << "Goodbye ${attrs.name}"
+}
+----
+
+A tag taking a body becomes a method with a second `Closure body` parameter:
+
+[source,groovy]
+----
+// Before
+def wrapped = { attrs, body ->
+ out << '<div>' << body() << '</div>'
+}
+
+// After
+def wrapped(Map attrs, Closure body) {
+ out << '<div>' << body() << '</div>'
+}
+----
+
+===== Tags Are No Longer Installed Onto Metaclasses
+
+Dispatching a tag no longer works by installing a method for every tag, and a property for every
+namespace, onto the metaclass of every tag library, controller and page. Tags are resolved through the
+tag library lookup instead. Calling a tag — from a page, a tag library or a controller, with or
+without its namespace — is unaffected.
+
+What changes is code that inspected the metaclass to find tags. A check such as
+
+[source,groovy]
+----
+tagLib.metaClass.respondsTo(tagLib, 'someTag')
+----
+
+answered `true` before because the tag had been installed there, and now answers `false`. Call the tag,
+or consult the tag library lookup, instead of asking the metaclass what it holds.
+
+The methods that performed the installation are deprecated or removed:
+
+[cols="2,3"]
+|===
+|Member |Replacement
+
+|`NamespacedTagDispatcher.initializeMetaClass()`
+|Removed. Nothing needs to be initialised.
+
+|`NamespacedTagDispatcher.registerTagMetaMethods(ExpandoMetaClass)`
+|Removed.
+
+|`TemplateNamespacedTagDispatcher.registerTagMetaMethods(ExpandoMetaClass)`
+|Removed.
+
+|`GroovyPagesMetaUtils.registerMethodMissingForGSP(...)`
+|Retained but does nothing. A page now declares `methodMissing` itself.
+
+|`TagLibraryMetaUtils.enhanceTagLibMetaClass`, `registerTagMetaMethods`, `registerMethodMissingForTags`, `registerNamespaceMetaProperties`, `registerPropertyMissingForTag`, `addTagLibMethodToMetaClass`
+|Deprecated. Unit test support still uses them so that a tag method can be called directly on a tag library under test.
+|===
+
+`TagLibraryMetaUtils.methodMissingForTagLib` is not deprecated — it is the dynamic dispatch path a call
+into an undescribed namespace still takes.
+
+===== A Method-Declared Tag Called Without a Namespace Returns Its Output
+
+A class that can call tags but is not a tag library — a controller — reaches a tag written without a
+namespace through `methodMissing` on the `TagLibraryInvoker` trait. That used to end in a direct call
+on the tag library bean. For a tag declared as a closure this made no difference, because the call
+landed on a generated wrapper that captured output anyway; for one declared as a method there was no
+wrapper, so the method ran with nothing captured and its own return value came back.
+
+Both forms now capture, so a method-declared tag returns what it wrote:
+
+[source,groovy]
+----
+class ReportTagLib {
+ static namespace = 'g'
+
+ def summary(Map attrs) {
+ out << 'the output'
+ 'the return value' // <1>
+ }
+}
+
+class ReportController {
+ def index() {
+ String result = summary(id: 1) // 'the output', previously 'the return value'
+ }
+}
+----
+<1> a tag's return value is not what a caller receives; what it writes is
+
+A tag called *with* its namespace, and any tag called from a GSP, already captured, so only an
+unqualified call from a controller to a method-declared tag changes.
+
+==== 52. Quartz Job Scheduling Behavior Changes
+
+Three behaviors of the Quartz plugin changed in this release. All three concern what happens when
+something about a schedule is wrong; none of them require a change to a job class.
+
+===== 52.1 A trigger that can never fire no longer stops startup
+
+A job whose trigger has no possible fire time — a cron expression whose last occurrence is in the past,
+or an end time that has already passed — used to make the application fail to start, because the
+scheduler rejects such a trigger:
+
+----
+org.quartz.SchedulerException: Based on configured schedule, the given trigger will never fire.
+----
+
+The plugin now reports the trigger as an error in the log and leaves it unscheduled, so the rest of the
+application's jobs and triggers are scheduled and the application starts. The job itself is still
+registered, so it can be triggered and rescheduled at runtime.
+
+To go back to a failing startup, set `quartz.failOnNeverFiringTriggers`:
+
+[source,yaml]
+.application.yml
+----
+quartz:
+ failOnNeverFiringTriggers: true
+----
+
+===== 52.2 An application only removes the jobs it registered itself
+
+When an application starts, the plugin removes the jobs in the job store which are no longer enabled job
+artefacts of the application. It used to consider *every* job in the store, which with a persistent job
+store deleted the jobs and triggers of anything else using it — another application, or code that
+schedules through the Quartz API.
+
+Every job the plugin registers now carries the name of the application that registered it, taken from
+`info.app.name` or from the application metadata when that is unset, and only jobs carrying that name are
+removed. Two consequences for an application with `quartz.jdbcStore` enabled:
+
+* **Two applications sharing a job store must not share an application name.** Instances of one
+application do share it — that is what makes a clustered deployment clean up after itself — but two
+different applications on the same Quartz tables each need their own `info.app.name`. An application which
+does not name itself registers its jobs under the default name, which every unnamed application shares;
+with `quartz.jdbcStore` enabled the plugin warns about that at startup.
+* **A job written to the store by Grails 7 or earlier carries no application name**, so it is never
+removed automatically. A job class you deleted while running an older version leaves a row behind; remove
+it with `jobManagerService.removeJob(group, name)` or from the Quartz tables.
+
+===== 52.3 Scheduling methods report what is wrong instead of failing with a null pointer
+
+The static scheduling methods every job class gets — `schedule`, `reschedule`, `unschedule`,
+`triggerNow`, `removeJob` — used to fail with a `NullPointerException` when called with a null argument,
+or on a job the scheduler does not know about. They now raise:
+
+* an `IllegalArgumentException` naming the argument that is null. Note that a null argument resolves to
+`schedule(Trigger)` whichever method the caller meant, because the runtime type of `null` carries no
+information, so the message points at the other arguments too.
+* an `IllegalStateException` when the job is not registered with a scheduler — the plugin is disabled, the
+job is disabled with `jobEnabled = false`, or the class is not a job artefact of the application.
+
+An application that caught `NullPointerException` around these calls has to catch those instead. See
+<<quartzDynamicScheduling,Dynamic Job Scheduling>>.
+
+==== 53. `request` Is No Longer a `MultipartHttpServletRequest`
+
+The `request` object Grails exposes to controllers, tag libraries and GSPs is now always the outermost
+servlet request. Previously, for a file upload, Grails replaced it with the resolved
+`MultipartHttpServletRequest`, which discarded the request wrappers contributed by other filters — the
+hidden HTTP method filter, Spring Security, and any application filter.
+
+All file upload methods work exactly as before:
+
+[source,groovy]
+----
+def upload() {
+ def file = request.getFile('myFile')
+ if (file.empty) {
+ flash.message = 'file cannot be empty'
+ render(view: 'uploadForm')
+ return
+ }
+ file.transferTo(new File('/some/local/dir/myfile.txt'))
+}
+----
+
+`request.getFiles(name)`, `request.getFileNames()`, `request.getFileMap()`, `request.getMultiFileMap()`
+and `request.getMultipartContentType(name)` are likewise unchanged, as is binding a file through
+`params`:
+
+[source,groovy]
+----
+def img = new Image(params)
+----
+
+What no longer works is treating `request` as a `MultipartHttpServletRequest` by type:
+
+[source,groovy]
+----
+// Before
+if (request instanceof MultipartHttpServletRequest) {
+ def file = ((MultipartHttpServletRequest) request).getFile('myFile')
+}
+
+// After
+def file = request.getFile('myFile')
+----
+
+Calling one of the file methods on a request that is not a file upload throws `IllegalStateException`
+with a diagnostic message, the same way it previously failed with `MissingMethodException`.
+
+===== 53.1 Oversized uploads now reach the application's error handling
+
+An upload larger than `spring.servlet.multipart.maxFileSize` or `spring.servlet.multipart.maxRequestSize`
+(1MB per file and 10MB per request by default, see <<multipart-upload-configuration,Multipart Upload
+Configuration>>) fails when the servlet container parses the request parts, and every parameter read on
+that request fails with it from then on. Because Grails reads request parameters on paths that run
+before, alongside and after the handler — to resolve the `_method` override, whenever a filter such as
+Spring Security builds `params`, in the locale-change interceptor, and in the exception resolver's
+request log — that failure used to abort the request inside the filter chain, where no exception
+handler could see it. The application was left with the container's own error page.
+
+Those reads now tolerate a multipart request the container refuses to parse, so the failure surfaces
+where Spring raises it, as a
+`org.springframework.web.multipart.MultipartException`/`MaxUploadSizeExceededException` during
+dispatch. The exception is available to `HandlerExceptionResolver` beans, and the response is a `413`
+rendered through the application's error dispatch instead of the container's own error page.
+
+A `"413"` response code URL mapping handles it, the same way a `"404"` or `"500"` mapping handles those
+statuses:
+
+[source,groovy]
+----
+"413"(controller: 'errors', action: 'tooLarge')
+----
+
+The mapped action runs on the container's error dispatch, so `request.dispatcherType` is `ERROR` and
+`params` is empty — the container never parsed the request. `request.getFile(..)` is unavailable there
+for the same reason. The upload itself is gone by then; the action's job is to render the response.
+
+The parameters of such a request are empty everywhere, not just in the error handler. The request
+cannot reach the originally requested controller either way — `DispatcherServlet` rejects it before
+handler resolution — so outside the error handler this is only observable in a filter that inspects
+`params` ahead of the dispatch.
+
+====== Servlet container differences
+
+Tomcat and Jetty both surface the failure to the application as described above. Undertow applies the
+limit while it reads the request entity and refuses the request at the HTTP layer, so no application
+code runs at all: the response is a bare `413` with an empty body, and a `"413"` mapping is not
+consulted. Raising `spring.servlet.multipart.maxRequestSize` raises the point at which Undertow
+refuses, but there is no way to render a body for a request the container never dispatches.
+
+===== 53.2 An error handler that fails is no longer forwarded to from inside itself
+
+A `"500"` (or exception-specific) URL mapping that names a controller is reached by forwarding to it.
+That forward re-enters the `DispatcherServlet`, and the forwarded dispatch resolves the same status
+code mapping again. An error handler that failed for a reason belonging to the request rather than to
+the moment — an unparseable multipart body, a missing collaborator — therefore failed again inside its
+own forward, and that failure forwarded to it once more, until the dispatch stack overflowed.
+
+The error handler is no longer forwarded to while a forward to it is already running. The repeat
+failure is logged and the exception is returned to the `DispatcherServlet`, which reports it through
+the container, so the response is a single container-level error rather than a dispatch that never
+terminates. Once the forward returns, a later error on the same request — from an enclosing request
+whose include failed, for instance — is forwarded to the error handler as before.
+
+==== 54. Request Processing Behaviour Changes
+
+Four changes fall out of Grails 8 delegating more of the request path to Spring.
+
+===== 54.1 API versioning headers are now emitted for Grails-mapped requests
+
+`UrlMappingsHandlerMapping` previously assembled its own handler execution chain rather than using
+Spring's. As a result, Grails-mapped requests skipped the interceptor Spring adds for API versioning,
+so the `Deprecation`, `Sunset` and `Link` headers configured through `spring.mvc.apiversion.*` were
+never sent. The chain is now assembled by Spring, and those headers are emitted as configured.
+
+If an application relied on those headers being absent, unset the corresponding
+`spring.mvc.apiversion.*` configuration.
+
+===== 54.2 The `LocaleContext` is restored rather than cleared
+
+At the end of a request Grails previously called `LocaleContextHolder.setLocale(null)`, which discarded
+any `LocaleContext` established earlier in the filter chain by non-Grails code. Grails now saves and
+restores the previous `LocaleContext`, matching Spring's own `RequestContextFilter`.
+
+===== 54.3 The application attributes object is shared per servlet context
+
+`GrailsApplicationAttributes` was constructed once per request. It is now created once per servlet
+context and reused, so the beans it caches are resolved once rather than on every request. It is
+rebuilt automatically if the `ApplicationContext` is replaced.
+
+Applications that implemented `GrailsApplicationAttributes` themselves must ensure their
+implementation holds no request-scoped state and is safe to use from multiple request threads.
+
+===== 54.4 `GrailsWebRequest.setMultipartRequest(..)` is deprecated
+
+`setMultipartRequest(HttpServletRequest)` installed the resolved multipart request on the web request. With
+the substitution gone the resolver publishes it as a request attribute instead, and Grails finds it there or
+by unwrapping. The method still works -- it publishes its argument and discards the cached params -- but a
+caller that has one should move to letting the resolver publish it, or set the attribute directly:
+
+[source,groovy]
+----
+// Before
+webRequest.setMultipartRequest(resolved)
+
+// After
+request.setAttribute(WebUtils.MULTIPART_HTTP_SERVLET_REQUEST_ATTRIBUTE, resolved)
+webRequest.multipartRequestResolved()
+----
+
+===== 54.5 `GrailsWebRequest.getCurrentRequest()` returns what `getRequest()` returns
+
+`getCurrentRequest()` existed to hand back the resolved multipart request in place of the request Grails was
+bound to. That substitution is gone (see _53. `request` Is No Longer a `MultipartHttpServletRequest`_), so
+the two accessors now answer with the same object. The method stays, and calling it is fine; there is simply
+nothing left that distinguishes the two.
+
+Code that reaches for the uploaded files of a multipart request should use the `request.getFile(..)` methods
+described in section 53.
+
+Tests that mock a `GrailsWebRequest` and stub `getCurrentRequest()` need updating. `getRequest()` is
+`final` on Spring's `ServletRequestAttributes`, so `getCurrentRequest()` was the only stubbable request
+accessor, and framework code now calls `getRequest()` directly. Drive a real `GrailsWebRequest` over a
+`MockHttpServletRequest` rather than stubbing the accessor:
+
+[source,groovy]
+----
+// Before
+def webRequest = Mock(GrailsWebRequest)
+webRequest.getCurrentRequest() >> request
+
+// After
+def webRequest = new GrailsWebRequest(request, response, servletContext)
+----
+
+
+==== 55. URL Mapping Names Come From the URI, Not From Request Parameters
+
+A mapping that captures its controller, action or namespace from the URL — `"/$controller/$action?/$id?"`,
+the default mapping every application starts with — used to resolve those names by reading the request's
+parameters during dispatch. The values were normally the ones the URI supplied, because the match wrote its
+captures over the request parameters first. But a token the URI did *not* supply left whatever the request
+carried under that name in place, and the request's own value decided the route.
+
+A request for `/article?action=gallery` therefore reached `ArticleController.gallery()` instead of the
+controller's default action: the optional `$action` token captured nothing, and the query string filled the
+gap. The same held for `controller` and `namespace`, and for a form body as well as a query string.
+
+Captured names now come from the match itself. A token the URI does not supply is simply absent, and a
+request parameter of the same name has no say in routing:
+
+[source,groovy]
+.grails-app/controllers/UrlMappings.groovy
+----
+static mappings = {
+ "/$controller/$action?/$id?"()
+}
+----
+
+[cols="1,1,1", options="header"]
+|===
+| Request
+| Grails 7
+| Grails 8
+
+| `/article/gallery`
+| `ArticleController.gallery()`
+| `ArticleController.gallery()`
+
+| `/article?action=gallery`
+| `ArticleController.gallery()`
+| the default action of `ArticleController`
+|===
+
+`params.action` still holds `gallery` in both versions — only the routing decision changed.
+
+Choosing an action from a request parameter is still supported, by asking for it explicitly with a closure:
+
+[source,groovy]
+.grails-app/controllers/UrlMappings.groovy
+----
+static mappings = {
+ "/$controller" {
+ action = { params.goHere }
+ }
+}
+----
+
+A closure supplied by the mapping keeps reading request state, exactly as before, and mappings that use one
+are unaffected by this change.
+
+Two consequences beyond the routing fix. Request parameters are now built once per request rather than once
+per candidate mapping, since candidates no longer have to be configured onto the request to be identified.
+And `grails.web.mapping.UrlMappingInfo` gains a
+`isNameResolutionRequestDependent()` method for callers that resolve names themselves; it is a default
+method that reports `true`, so an implementation outside the framework keeps its current behaviour without
+changes.
+
+==== 56. Coordinate Changes
+
+`grails-datamapping-async` provides the asynchronous programming model for Grails Data — the
+`AsyncEntity` trait and the `async` namespace — and is meant to be depended on directly by
+applications and libraries. Groups nested below `org.apache.grails` are reserved for implementation
+details of Grails, so the artifact moved from the `org.apache.grails.data` group to
+`org.apache.grails`. The artifact id is unchanged:
+
+[source,groovy]
+.build.gradle
+----
+implementation "org.apache.grails:grails-datamapping-async"
+----
+
+The https://github.com/apache/grails-core/blob/8.0.x/RENAME.md[RENAME.md] reference table in the
+grails-core repository maps previous coordinate names to new names. The `rename_gradle_artifacts.sh`
+script in the https://github.com/apache/grails-core/tree/8.0.x/etc/bin[etc/bin] directory of the
+grails-core repository rewrites both the Grails 6 (`org.grails:grails-datastore-gorm-async`) and the
+Grails 7 (`org.apache.grails.data:grails-datamapping-async`) coordinates in a project's Gradle files:
+
+[source,console]
+----
+./rename_gradle_artifacts.sh -l my/project/location
+----
+
+==== 57. `importJavaTime` Removed
+
+The `org.apache.grails.gradle.grails-app` plugin no longer accepts `importJavaTime`.
+
+The flag added `java.time` to the star imports of every Groovy compilation. Groovy 5, which Grails 8
+requires, imports that package by default, so on Grails 8 the flag added an import the compiler already
+had:
+
+[source,groovy]
+----
+// Grails 8, no configuration and no import statement
+class Book {
+ LocalDate published
+ Duration readingTime
+}
+----
+
+A build that sets it fails with `Could not set unknown property 'importJavaTime'`. Delete the line; there
+is no replacement:
+
+[source,groovy]
+.build.gradle
+----
+grails {
+ // Grails 7
+ // importJavaTime = true
+
+ // Grails 8 - java.time is a Groovy 5 default import
+}
+----
+
+`importGrailsCommonAnnotations` and `starImports` are unchanged, and both still default to off.
+
+`importGrailsCommonAnnotations` no longer probes the compile classpath before adding
+`grails.gorm.annotation` and `grails.plugin.scaffolding.annotation`. When the flag is set both packages are
+imported whether or not they are present — a star import of an absent package contributes no classes and is
+not an error in Groovy, so the probe changed nothing it could observe. An application that relied on the
+import being *omitted* when the package was absent sees no difference in compiled output.
+
+==== 58. Non-Public Bean Classes Are Marshalled, and Reported Once
+
+Groovy 4 stamped `ACC_PUBLIC` on anonymous inner classes; Groovy 5, which Grails 8 builds on, does not.
+Reflection cannot invoke a method on a class that is not `public` from another package, even when the method
+itself is public, so code that marshalled an anonymous class perfectly well under Grails 7 started failing on
+Grails 8 with `ConverterException` wrapping `IllegalAccessException`. Nothing in the application changed —
+only the class modifier the compiler emits.
+
+A second failure in the same code path is fixed alongside it: converting any `Serializable` bean threw
+`IllegalArgumentException`, because the marshaller asked whether a `private static final long
+serialVersionUID` field was accessible before checking that it was static, which the JDK rejects. Practically
+every serializable bean declares that field, so this affected a large share of objects passed to `as JSON`.
+
+Grails 8 adds compatibility handling for the non-public case, and reports each such class once so that the
+code can be corrected — see 58.2 below. The shape that hits it is an anonymous implementation of a public
+interface:
+
+[source,groovy]
+----
+def show() {
+ def user = new UserDetails() {
+ @Override Collection<? extends GrantedAuthority> getAuthorities() { [new SimpleGrantedAuthority('ROLE_ADMIN')] }
+ @Override String getPassword() { null }
+ @Override String getUsername() { 'user' }
+ }
+ render([user: user] as JSON)
+}
+----
+
+NOTE: Ordinary Groovy code is unaffected. Property access and method calls through the metaclass still work
+on such an object from any package, as does the JDK's `Introspector`; only raw reflection against the method
+as the non-public class declares it fails. That is what bean marshalling was doing.
+
+===== 58.1 Public Fields of Non-Public Classes Are Now Included
+
+Java and Groovy beans are now treated alike. A `public` instance field declared on a class that is not
+public was silently omitted from the JSON or XML body when the bean was a plain Java object; it is now
+included, as it always was for a Groovy bean. If a field was being dropped by accident and should stay out
+of the payload, exclude it explicitly or register an `ObjectMarshaller` for the class:
+
+[source,groovy]
+----
+def json = someObject as JSON
+json.excludes = ['nickname']
+render json
+----
+
+A `public` *field* that cannot be read at all — because its class is in a named module that does not open
+its package — is skipped, and the rest of the object still converts. A *getter* in that same situation is
+not skipped: the conversion fails, as it did before Grails 8.
+
+===== 58.2 The Warning
+
+Reading a bean whose class is not public is compatibility handling rather than a supported contract, so each
+such class is reported once:
+
+[source,text]
+----
+Class [com.example.DemoController$1] is not public. Grails reads its properties through compatibility
+handling that may be withdrawn in a future major release. Declare it as a named public class so that it
+reads as a standard JavaBean, or register an ObjectMarshaller for it if the class is not yours. To silence
+this, set the log level of [org.apache.grails.common.reflect.ReflectionUtils] above WARN. (warned once per class)
+----
+
+The fix is to declare the class `public` — as a named class where it is currently anonymous — or, for a class
+you do not own, to register an `ObjectMarshaller` for it. Classes from the JDK, Groovy, and Spring are never
+reported, since an application cannot declare those public.
+
+To silence the warning instead:
+
+[source,yaml]
+.application.yml
+----
+logging:
+ level:
+ org.apache.grails.common.reflect.ReflectionUtils: ERROR
+----
+
+==== 59. Interceptor URI Matching Uses the Dispatched Path
+
+Interceptors that match on `uri`, with `match(uri: ...)` or `excludes(uri: ...)`, now match the same path that URL
+mappings route on: percent escapes are decoded, matrix parameters (`;name=value`) are removed and the context path is
+stripped before the pattern is applied. Previously the raw request URI was matched, so an encoded (`/%61dmin/users`)
+or matrix-parameter (`/admin;x=1/users`) request could reach a controller without triggering an interceptor declared
+for `/admin/**`. Interceptors matched by controller, action or namespace are unaffected.
+
+Review interceptors that use `uri` matching for the following changes:
+
+* **Interceptors combining `match(uri:)` with an `excludes(...)` now run under a context path.**
+In earlier versions a matcher that paired a `uri` pattern with any exclusion (`excludes(uri:)`, `excludes(controller:)`,
+`excludes(action:)` or a closure) never matched when the application was deployed under a non-root context path (for
+example `server.servlet.context-path=/app`), because the exclusion check required the pattern to match both the
+context-prefixed and the context-relative request URI, which a pattern such as `/api/**` cannot do. Only that shape was
+affected: `matchAll()` with exclusions, `match(controller:)` and other name-based matchers, `match(uri:)` without an
+exclusion, and `uri` patterns that match both forms such as `/**` all ran as expected. The affected shape now behaves
+as configured, so an interceptor written that way starts executing under a context path.
+
+* **Patterns are matched against the path within the application only.**
+A pattern is no longer also compared with the context-prefixed request URI, so `+match(uri: '/*/*')+` no longer matches
+`/app/save` under the context path `/app`. Patterns that begin with the context path, such as
+`match(uri: '/app/admin/**')`, are still accepted for backwards compatibility.
+
+* **Includes are matched against the included path.**
+During a `<g:include>` or `RequestDispatcher` include, `uri` matchers see the included path rather than the URI of the
+outer request. This is consistent with the controller selected for the include and with `match(controller:)`
+matchers, which already matched the included controller.
+
+* **Custom `grails.interceptors.Matcher` implementations receive the canonical path.**
+The `uri` argument passed to `doesMatch` is now the decoded, application-relative path without matrix parameters. A new
+`doesMatch(String uri, UrlMappingInfo info, String method, String contextPath)` default method also supplies the
+context path; override it when a matcher needs the context-prefixed form.
+
+The Spring Security plugin applies the same canonicalization when matching `ipRestrictions` patterns and when the
+`AntPathRequestMatcher` compatibility class selects a filter chain, so an encoded or matrix-parameter variant of a
+restricted path is subject to the same restriction as the plain path.
+
+The canonical form follows the URI and Servlet specifications, with two deliberate exceptions. Path parameters are
+removed from each segment before percent-decoding, as Jakarta Servlet 6.0 section 3.5.2 requires of containers, so an
+encoded semicolon (`%3B`) is a literal character and not a parameter delimiter (RFC 3986 section 2.2). Percent-encoded
+unreserved characters such as `%61` are decoded (RFC 3986 section 2.3), and the path is decoded exactly once
+(RFC 3986 section 2.4). The exceptions are inherited from Spring's `UrlPathHelper`, which Grails URL mapping dispatch
+has used since Grails 3: the context path is compared case-insensitively although RFC 3986 section 6.2.2.1 and
+RFC 9110 section 4.2.3 define paths as case-sensitive, and during a `RequestDispatcher` include the included path is
+matched. Interceptors and the Spring Security matchers follow dispatch on both points because a matcher that
+disagrees with dispatch lets a request reach a controller without its interceptors or restrictions.
+
+==== 60. Sort and Order Query Arguments Are Validated
+
+Grails 8 checks the `sort` and `order` arguments of `list()`, dynamic finders, where queries, criteria queries and `listOrderBy*` before the query is built, on both Hibernate 5 and Hibernate 7. A client-supplied sort value used to be interpolated into the query, and the entry points did not agree on how a bad value was handled. They now fail the same way everywhere, with an `IllegalArgumentException` whose message deliberately does not echo the value.
+
+A `sort` key must be a property path made up of identifiers separated by dots, such as `"title"` or `"author.name"`, that resolves through the domain class mapping. A dotted key whose first segment is an alias created with `createAlias` or declared in a where query is still left to the query to resolve. Anything else is rejected with the message `Invalid sort property`:
+
+* A value carrying a second expression, a direction or a function call, for example `"title, id"`, `"title desc"` or `"upper(title)"`.
+* A bare name that is not a property of the domain class. Previously this reached Hibernate and failed with a Hibernate exception or a `NullPointerException`.
+* A path into an unknown property of an association, or into a property that is not an association, for example `"author.unknown"` or `"title.length"`.
+
+An `order` value must be `"asc"` or `"desc"`, compared case-insensitively with surrounding whitespace ignored. Any other value is rejected with the message `Invalid sort direction`. Previously most entry points treated anything other than `desc` as ascending, so a typo such as `order: "descending"` silently sorted ascending. The value is checked even when no `sort` argument is given.
+
+With Hibernate 7, `list()` additionally requires each `fetch` key to name a persistent property, and rejects anything else with the message `Invalid fetch property`.
+
+Applications that pass request parameters straight through to these methods no longer need their own checks. Code that relied on an invalid value being ignored must now pass `asc` or `desc` and a real property name. To return a different response for a bad value, catch `IllegalArgumentException` where the query is issued:
+
+[source,groovy]
+----
+def index(Integer max) {
+ try {
+ respond Book.list(max: max, sort: params.sort, order: params.order)
+ } catch (IllegalArgumentException ignored) {
+ render status: 400
+ }
+}
+----
+
+==== 61. XML Request Bodies That Declare a DOCTYPE Are Refused
+
+XML that Grails parses on an application's behalf is now read with external entity expansion, external DTD retrieval and
+DTD grammar loading disabled. Earlier releases set these parser features under identifiers the parser did not recognise,
+so the parser's own defaults applied instead.
+
+An `application/xml`, `text/xml` or `application/hal+xml` request body, or a string passed to `XML.parse`, that declares
+a `DOCTYPE` is additionally refused rather than bound, whether or not the declaration references anything external.
+Binding such a body fails with the `invalidRequestBody` error code. There is no setting that relaxes this; a client that
+sends a declaration needs to omit it.
+
+Descriptors that Grails reads from the classpath, such as JSP tag library descriptors and `web.xml`, and the
+`response.xml` accessor in controller unit tests are not affected. They may declare a `DOCTYPE`, though the DTD it names
+is never retrieved. The plugin descriptor `grails-plugin.xml` is not among them: Grails generates it and never writes a
+declaration, so it is read strictly at compile time and at runtime alike.
+
+See <<upgrading>> for the full description of the XML parsing defaults.
+
+[[groovy-compiler-config-scripts]]
+==== 62. Generated Groovy Compiler Configuration Scripts
+
+On Gradle 9.7+, configure `groovyOptions.configurationScriptFile` before task execution. Assigning
+`groovyOptions.configurationScript` from `compileGroovy.doFirst { ... }` fails because Gradle has
+already finalized the compiler options. Grails prepares the combined compiler script before compilation.
+
+If another task generates your compiler script, prefer passing that task's output provider to
+`configurationScriptFile`. The provider carries both the file location and its producing task, so
+Grails can prepare the combined script after your script is generated.
+
+Declare the generated script as an output and connect it through its provider:
+
+[source,groovy]
+.build.gradle
+----
+import org.gradle.api.DefaultTask
+import org.gradle.api.file.RegularFileProperty
+import org.gradle.api.tasks.OutputFile
+import org.gradle.api.tasks.TaskAction
+import org.gradle.api.tasks.compile.GroovyCompile
+import org.gradle.work.DisableCachingByDefault
+
+@DisableCachingByDefault(because = 'Writing a short compiler script is inexpensive')
+abstract class GenerateCompilerScript extends DefaultTask {
+ @OutputFile
+ abstract RegularFileProperty getOutputFile()
+
+ @TaskAction
+ void generate() {
+ def script = outputFile.get().asFile
+ script.parentFile.mkdirs()
+ script.text = "withConfig(configuration) { imports { star 'java.nio.file' } }"
+ }
+}
+
+def generateUserConfigScript = tasks.register('generateUserConfigScript', GenerateCompilerScript) {
+ outputFile.set(layout.buildDirectory.file('user-config.groovy'))
+}
+
+tasks.named('compileGroovy', GroovyCompile) {
+ groovyOptions.configurationScriptFile.set(generateUserConfigScript.flatMap { it.outputFile })
+}
+----
+
+No separate `dependsOn` is needed for this producer. If the script's content depends on task properties
+or other files, declare those as task inputs so changes regenerate the script.
+
+Existing builds can also keep the plain file assignment with an explicit compile dependency:
+
+[source,groovy]
+.build.gradle (alternative wiring for the producer above)
+----
+tasks.named('compileGroovy', GroovyCompile) {
+ dependsOn generateUserConfigScript
+ groovyOptions.configurationScript = file('build/user-config.groovy')
+}
+----
+
+Grails matches the configured file against the declared outputs of the compile task's direct
+dependencies and orders script preparation after the matching producer. This preserves the Grails 7
+pattern when the producer declares the exact script file as an output, whether through an `@OutputFile`
+property as `GenerateCompilerScript` does above or through `outputs.file(...)` on an ad-hoc task. A
+dependency that declares only a containing output directory, writes the file without declaring it as an
+output, or is reachable only through another task's `dependsOn` cannot be identified this way. Such a
+build fails from a clean checkout before compilation starts, with a validation error on the
+`generateCompileGroovyGrailsCompilerConfig` task that Grails registers:
+
+[source,text]
+----
+A problem was found with the configuration of task ':generateCompileGroovyGrailsCompilerConfig' (type 'GrailsCompilerConfigScriptTask').
+Input file does not exist
+ ... property 'configurationScript' specifies file '.../build/user-config.groovy' which doesn't exist
+----
+
+If you see this error, expose the script as an output file and use the provider wiring instead.
+
+An existing, checked-in compiler script can still use a plain file assignment without a producer.
+Tasks that only generate source or classpath entries do not need additional ordering against
+compiler-script preparation: Grails does not read the compile or runtime classpath to prepare its script.
+
+==== 63. `count()` Returns `Long`
+
+`count()` and the `count` property return `Long` instead of `Integer`:
+
+[source,groovy]
+----
+// Grails 7
+Integer total = Book.count()
+
+// Grails 8
+Long total = Book.count()
+----
+
+How wide the underlying value is depends on the datastore. Hibernate counts with SQL `COUNT(*)` and Neo4j
+with Cypher `count(*)`, both 64-bit. MongoDB aggregates with `{$sum: 1}`, which returns Int32 and promotes
+to Int64 once the total exceeds it, so the width depends on how many documents the collection holds. Only
+the in-memory datastore is fixed at 32 bits, and it returns a list size. `GormStaticApi.count()` narrowed the datastore
+result with `intValue()`, which truncates silently, so
+a table with more than `Integer.MAX_VALUE` rows reported a wrong and possibly negative count with no
+error. `Long` is the only type that holds every value a datastore can produce here, so it is what the API
+now declares.
+
+The change affects `GormStaticOperations.count()` and `getCount()`, the `count()` and `count` members
+generated on every domain class, and `RestfulController.countResources()`. Dynamic Groovy is unaffected:
+`Book.count() == 5`, `int n = Book.count()` and arithmetic on the result all continue to work, because
+Groovy converts between numeric types on assignment and compares them by value.
+
+Code that is statically compiled, or that overrides one of these methods, needs updating:
+
+[source,groovy]
+----
+@CompileStatic
+class ReportService {
+ // Grails 7
+ // Integer bookCount() { Book.count() }
+
+ // Grails 8
+ Long bookCount() { Book.count() }
+}
+
+class BookController extends RestfulController<Book> {
+ // Grails 7
+ // protected Integer countResources() { ... }
+
+ // Grails 8
+ protected Long countResources() { ... }
+}
+----
+
+Java callers assigning the result to an `Integer` or `int` need an explicit conversion, since `Long` does
+not unbox to `int`:
+
+[source,java]
+----
+long total = Book.count(); // auto-unboxes, no change needed
+int small = Book.count().intValue(); // only when the count is known to be small
+----
+
+A GSP that declares the count in a typed model directive should declare it as `Number`, which accepts
+whatever a controller supplies:
+
+[source,html]
+----
+@{ model="List<Book> bookList; Number bookCount" }
+----
+
+JSON views declare their model the same way, and bind it the same way, so a `model` block naming the count
+with a concrete numeric type needs the same treatment:
+
+[source,groovy]
+.grails-app/views/book/index.gson
+----
+model {
+ Iterable<Book> bookList
+ // Grails 7
+ // Integer bookCount
+ Long bookCount // or Number, to accept either width
+}
+----
+
+`HalViewHelper.paginate()` and `links()` now declare `total` as `Long`, and `paginate()` declares `offset`
+as `Long` with it. Callers are unaffected, because Groovy widens an `Integer` argument to `Long` in both
+dynamic and statically compiled code, but anyone implementing `HalViewHelper` has to update their
+signatures.
+
+The GraphQL count field changes type with it. `graphql-java` maps `Long` to
+`ExtendedScalars.GraphQLLong`, so a schema that exposed
+
+[source,graphql]
+----
+type Query {
+ personCount: Int
+}
+----
+
+now exposes
+
+[source,graphql]
+----
+type Query {
+ personCount: Long
+}
+----
+
+Queries that select the field are unchanged and the JSON value is unchanged, but generated clients and
+schema snapshots need regenerating. The count fetcher previously narrowed the datastore result to fit
+`Int`, so counts above `Integer.MAX_VALUE` were truncated there too.
+
+Paginated list responses already type `totalCount` as `Long` through the same type manager, in
+`DefaultGraphQLPaginationResponseHandler`, so this aligns the count field with a scalar the schema
+already used rather than introducing a new one.
+
+==== 64. Grails Plugins Run for a Grails Application Only
+
+In earlier Grails 8 milestones, the Grails plugin lifecycle ran for any Spring Boot application that had
+`grails-core` on its class path, whether or not it was a Grails application. An application that depended on
+a Grails library — GSP for its views, say — had Grails plugin beans registered alongside the library's own
+auto-configuration. This could prevent the context from starting because of duplicate beans or circular
+references. Grails 7 did not run the plugin lifecycle for a context that omitted the Grails application class.
+
+The lifecycle now runs only for a Grails application: one that `GrailsApp` launched, or one where a source of
+the context is a Grails application class, which is what `grails-app/init/Application.groovy` is. A Grails
+application is unaffected either way. A Spring Boot application using a Grails library gets that library's
+auto-configuration and nothing else.
+
+This matters if you deliberately put a Grails plugin on the class path of an application that is not a Grails
+application and relied on its `doWithSpring` or `beanRegistrar` beans being contributed. Those beans are no
+longer registered. A plugin that also publishes an auto-configuration — as the Grails modules do, and as
+`@GrailsBeans` generates for a plugin's `beans` block — continues to contribute through Spring Boot's own
+auto-configuration, which needs no lifecycle.
+
+Inside a Grails application, `@SpringBootTest(classes = SomeConfig)` uses the explicitly named configuration
+classes. If those sources do not include the Grails application class, the plugin lifecycle does not run.
+This matches Grails 7. Earlier Grails 8 milestones attempted to register plugin beans in this context; with
+Hibernate, that could fail during startup because a plain Spring Boot application disallows circular references.
+
+A bare `@SpringBootTest` can discover the application's `Application` class automatically, so it does not
+need an explicit `classes` attribute to select the Grails lifecycle. When specifying custom configuration
+classes, include `Application` only if the test needs the Grails plugin runtime:
+
+[source,groovy]
+----
+// A context using only this configuration, without the Grails plugin lifecycle
+@SpringBootTest(classes = SomeConfig)
+class ConfigurationSpec extends Specification { }
+
+// Include the application and start through its main method to apply GrailsApp's defaults
+@SpringBootTest(classes = [Application, SomeConfig], useMainMethod = SpringBootTest.UseMainMethod.ALWAYS)
+class ApplicationSpec extends Specification { }
+----
+
+Selecting the application class and applying the startup defaults from `GrailsApp` are separate concerns.
+By default, `@SpringBootTest` does not invoke the application's main method. In a Grails application with
+Hibernate, it can therefore fail on bean overriding or circular references even when the application class
+is selected. Use `useMainMethod = SpringBootTest.UseMainMethod.ALWAYS`, as above, or set both
+`spring.main.allow-bean-definition-overriding=true` and `spring.main.allow-circular-references=true` on the
+test. This startup limitation also existed before the lifecycle change.
+
+`@Integration` tests are unaffected: they name the application class and invoke its main method. So are
+tests using the `grails-testing-support` unit test mixins, which build their context without the lifecycle
+either way.
+
+==== 65. `sitemesh.decorator.default` Is Consulted for the Default Layout
+
+The SiteMesh 3 integration resolved the default layout from `grails.sitemesh.default.layout`, falling back to
+the legacy `grails.views.layout.default`. With neither set it used the implicit `application` layout.
+
+SiteMesh's own `sitemesh.decorator.default` is now consulted as a last fallback, after both Grails keys. It is
+the property a Spring Boot application rendering views with GSP configures, and a Grails application has it
+set from the Grails keys already, so it decides only where neither Grails key is set.
+
+This changes behaviour for a Grails application that set `sitemesh.decorator.default` and neither Grails key:
+it was decorated with the implicit `application` layout and is now decorated with the layout that property
+names. Set `grails.sitemesh.default.layout` to be explicit, or remove `sitemesh.decorator.default` to keep the
+implicit `application` layout. An application that sets either Grails key is unaffected — those still win.
+
+==== 66. Promise Execution and Async Request Migration
+
+The default `PromiseFactory` now uses JDK `CompletableFuture`; it is no longer an `ExecutorPromiseFactory` or an `ExecutorService`. Inject `PromiseFactory` for promise operations rather than casting it to the legacy executor implementation. Explicit GPars and RxJava providers remain available.
+
+In applications, promises and the default event bus share Boot's named `applicationTaskExecutor`. This changes the usual execution policy from an expanding cached pool to Boot's configured executor (normally eight core threads with an unbounded queue). Review blocking workloads and configure `spring.task.execution.pool` and shutdown settings accordingly, or enable `spring.threads.virtual.enabled` on Java 21+. Avoid waiting synchronously for nested tasks in the same saturated pool. If Bo [...]
+
+The FutureTask-based promise implementations, `PromiseFactoryBean`, `AsyncController.startAsync()`, and the Grails-specific Servlet async wrappers are deprecated for removal. Replace custom legacy factory wiring with the async plugin and Boot executor configuration; replace manual Servlet dispatch/completion with a returned `Promise`. Existing Groovy `task`, `tasks`, `then`, and `onError` entry points remain supported.
+
+Both eager web promises and returned promises now honor `spring.mvc.async.request-timeout`; the Servlet container default applies when unset (normally 30 seconds on Tomcat), rather than an infinite timeout for eager web promises. Timeouts return HTTP 503 and can use a `503` URL mapping. Set a timeout explicitly if your application requires long-running responses. With the default and virtual-thread factories, single and aggregate error callbacks receive the original failure, while both [...]
+
+The `grails.async.promiseFactory=virtual-thread` opt-in now uses the same CompletableFuture implementation with its own decorated executor; it no longer relies on the deprecated FutureTask classes. Its default event bus remains asynchronous and its web tasks propagate request context. Its aggregate `onComplete` resolves to the callback's result, and aggregate `onError` observes the original failure while leaving the returned promise failed, rather than recovering to an empty list.
+
+==== 67. GORM for Hibernate 7 Tracks Changes From Persist, Not From Insert
+
+GORM for Hibernate 7 now activates its dirty-check tracking when an entity is persisted or merged rather
+than after its row has been inserted. Two observable behaviours change for existing applications on
+Hibernate 7. Applications on Hibernate 5 are unaffected.
+
+===== 67.1 A New Entity Starts at Version 0
+
+An entity whose identifier is generated before the insert, for example one mapped with
+`id generator: 'increment'` or `'assigned'`, or any member of a `tablePerConcreteClass` hierarchy, was
+written with an `INSERT` immediately followed by an `UPDATE` of the same row, so it started at `version` 1.
+It now starts at `version` 0 and costs a single statement, as on Hibernate 5 and as entities using the
+default `identity` generator always did.
+
+Code that compared such a version against 1, or that counted statements or update events for a new entity,
+needs to expect the value it would have had on Hibernate 5:
+
+[source,groovy]
+----
+def book = new Book(title: 'Grails').save(flush: true) // id generator: 'increment'
+assert book.version == 0 // was 1 before Grails 8.0
+----
+
+===== 67.2 Persistence Listeners Receive Persist and Merge Events
+
+An `AbstractPersistenceEventListener` on Hibernate 7 now receives a `PersistEvent` (`eventType` `Persist`)
+for every explicit or flush-time cascaded persist, and a `MergeEvent` (`eventType` `Merge`) for every
+merge. Neither can be cancelled. Hibernate 5 publishes `SaveOrUpdateEvent` when an entity is saved and
+publishes no event for a merge.
+
+A listener that switches over `event.eventType` and throws in its default branch must handle the new
+values:
+
+[source,groovy]
+----
+@Override
+protected void onPersistenceEvent(AbstractPersistenceEvent event) {
+ switch (event.eventType) {
+ case Persist: // new on Hibernate 7
+ case Merge: // new on Hibernate 7
+ case PreInsert:
+ // ...
+ break
+ default:
+ throw new IllegalStateException("Unhandled ${event.eventType}")
+ }
+}
+----
+
+==== 68. `lock(id)` Applies the Multi-Tenancy Filter
+
+`DomainClass.lock(id)` loaded the row by identifier, and Hibernate's tenant filter does not apply to a load
+by identifier. A `MultiTenant` entity could therefore be locked, and returned, by a tenant that does not own
+it, even though `get(id)` correctly returned `null` for the same identifier.
+
+The lock now loads a multi-tenant entity through a query, as `get(id)` does, so it resolves within the bound
+tenant and returns `null` for a row that belongs to another one. Entities that are not multi-tenant are
+unaffected, and so is the statement issued for them.
+
+Code that relied on `lock(id)` reaching across tenants has to bind the owning tenant explicitly:
+
+[source,groovy]
+----
+Tenants.withId('tenant1') {
+ Book.lock(id)
+}
+----
+
+==== 69. Instance Operations on a Named-Connection Static API Use That Connection
+
+Reaching an instance operation through a named-connection static API - `Book.secondary.save(book)`,
+`Book.secondary.delete(book)` and so on - resolved the instance API for the *default* connection rather than
+for `secondary`. With only the named connection's session open, which is the normal arrangement, the call
+failed with `No Session found for current thread`:
+
+[source,groovy]
+----
+Book.secondary.withNewSession {
+ Book.secondary.withTransaction {
+ Book.secondary.save(book) // threw: resolved the default connection
+ }
+}
+----
+
+Every such operation now resolves the connection the handle was obtained for: `save`, `insert`, `merge`,
+`delete`, `attach`, `isAttached`, `discard`, `ident`, `lock`, `mutex`, `refresh` and `instanceOf`. The example
+above now saves to `secondary`.
+
+GORM for Hibernate 5 needed a second fix for this to take effect. Its static API discarded the connection
+qualifier it was created with and reported `DEFAULT` for every connection, so a named-connection handle could
+not resolve anything but the default one. It now records its own qualifier, as GORM for Hibernate 7 already
+did. Anything that reads the qualifier of a Hibernate 5 named-connection static API therefore sees the real
+connection name where it previously saw `default`.
+
+Applications using a single datasource are unaffected, and so is the instance form `book.secondary.save()`,
+which already resolved the named connection.
+
+==== 70. `mutex` Reloads the Instance Under the Lock
+
+`entity.mutex { }` took an exclusive lock on the instance's already-loaded state and ran the closure. Because
+that lock is version-checked, a transaction that committed to the row between the load and the `mutex` call
+made it fail with an optimistic locking failure - the closure never ran.
+
+Where the datastore supports it, GORM for Hibernate 5 and 7 included, `mutex` now acquires the lock without a
+version check and reloads the row under it, so it waits for a competing writer and the closure runs on the
+committed state. The lock stays exclusive; there is no argument to weaken it, since a shared or optimistic
+lock would not give the closure mutual exclusion.
+
+Three consequences for existing code:
+
+* **Unflushed changes to the instance are discarded**, as they are for `refresh`. Apply changes inside the
+closure, not before the `mutex` call:
++
+[source,groovy]
+----
+book.title = 'new title'
+book.mutex { book.save() } // the pending title is discarded by the reload
+
+book.mutex { // apply the change inside instead
+ book.title = 'new title'
+ book.save()
+}
+----
+* **An active transaction is required.** Without one the call now throws
+`jakarta.persistence.TransactionRequiredException`.
+* **The instance must be attached** to the current session; a detached one throws `IllegalArgumentException`.
+Re-attach it with `attach()` first.
+
+Code that relied on `mutex` failing fast on a stale version should check the version itself, or use
+`entity.lock()`, which is unchanged.
+
+Datastores that cannot reload under a lock keep their previous behaviour.
+
+==== 71. Sequence Names on Hibernate 7: `id generator: 'sequence'` and the Default Id Mapping
+
+On GORM for Hibernate 7, mapping an identifier with `id generator: 'sequence'` and no `params: [sequence:
+'...']` failed at session factory bootstrap:
+
+[source,groovy]
+----
+static mapping = {
+ id generator: 'sequence' // threw: Unable to determine implicit sequence name for target table 'null'
+}
+----
+
+Hibernate's own generator-creation path supplies the target table so it can derive an implicit sequence name
+when none is given; the Grails-specific path that constructs the generator directly did not. The table name
+is now supplied the same way, so the mapping above starts the application.
+
+The derived name is not the one Grails 7 used. Hibernate 7 names the sequence after the entity's table with
+its own `_SEQ` suffix, where Grails 7 on Hibernate 5 gave every such mapping the same `hibernate_sequence`:
+
+[cols="2,2",options="header"]
+|===
+| `id generator: 'sequence'` on table `book` | Sequence
+
+| Grails 7, on Hibernate 5
+| `hibernate_sequence`
+
+| Grails 8, on Hibernate 7
+| `book_SEQ`
+|===
+
+An application whose schema is created at startup is unaffected. One that upgrades against an existing
+database has to either add the new sequences to that schema or keep the old name explicitly:
+
+[source,groovy]
+----
+static mapping = {
+ id generator: 'sequence', params: [sequence: 'hibernate_sequence']
+}
+----
+
+Mappings that already name a sequence are unaffected, and so is GORM for Hibernate 5.
+
+The default id mapping, with no `id` entry in `mapping` at all, is affected the same way on a database whose
+dialect draws native ids from a sequence, such as PostgreSQL and Oracle. Grails 7 on Hibernate 5 took every
+default-mapped id from the single `hibernate_sequence`. Grails 8 on Hibernate 7 creates one sequence per
+domain class, named after its table with the `_SEQ` suffix (`book_SEQ` for `book`). Databases that generate
+native ids with IDENTITY or auto-increment columns, such as H2, MySQL and MariaDB, are unaffected.
+
+Because this is the mapping most domain classes use, an application that upgrades against an existing
+PostgreSQL or Oracle schema meets it on every domain class, and what happens depends on `dbCreate`:
+
+[cols="1,3",options="header"]
+|===
+| `dbCreate` | Result
+
+| `create`, `create-drop`
+| The sequences are created with the tables. Nothing to do.
+
+| `validate`
+| Startup fails with `Schema validation: missing sequence [book_SEQ]`.
+
+| `none`
+| The first save fails, because the sequence does not exist.
+
+| `update`
+| Hibernate creates `book_SEQ` starting at 1, which collides with the ids already in the table.
+|===
+
+To upgrade such a database, do one of the following:
+
+* Keep drawing ids from `hibernate_sequence` for every unnamed sequence, which is the drop-in choice for a
+ database that already has it:
++
+[source,yaml]
+----
+hibernate:
+ id:
+ db_structure_naming_strategy: legacy
+----
+
+* Add the new sequences to the schema, each starting above the highest id already in its table. The schema
+ snapshot of the database migration plugin includes them.
+
+==== 72. Calls on a Class Inside a Named Connection's Session or Transaction Use That Connection
+
+Inside a session or transaction opened through a named connection - `Book.secondary.withTransaction { }`,
+`Book.secondary.withNewSession { }` and the like - the calls on `Book` itself, such as `Book.get(id)` or
+`book.save()`, used the *default* connection. With only the named connection's session open, a save failed
+with `No Session found for current thread`, and a read went to the default database:
+
+[source,groovy]
+----
+Book.secondary.withTransaction {
+ def book = Book.get(42) // read from the default database
+ book.save() // threw: No Session found for current thread
+}
+----
+
+Whether the save threw depended on what else was open. With a default-connection session open further out,
+as the open-session-in-view interceptor or an outer `@Transactional` provides, it succeeded and wrote the
+instance to the default database, silently.
+
+They now use the connection whose session or transaction the block opened, as they do inside
+`withConnection`, and the example above reads and saves through `secondary`. Other domain classes are not
+affected, and an operation that names a connection keeps it. The same holds inside a method annotated
+`@Transactional(connection = 'secondary')`, for every domain class mapped to `secondary`; a class that is not
+mapped to it keeps its own connection, and a multi-tenant class is left to its tenant, as it was before. Code that relied on the old routing changes
+behaviour without failing, so look for it: a copy between connections written as
+
+[source,groovy]
+----
+Book.legacy.withTransaction {
+ Book.legacy.list().each { new Book(name: it.name).save() } // meant for the default database
+}
+----
+
+used to write the copies to the default database, and now writes them back into `legacy`. Code that reached
+the default connection from inside such a block by calling the class directly has to name it now:
+
+[source,groovy]
+----
+Book.secondary.withTransaction {
+ Book.'default'.withSession { Book.count() } // counts the default database
+}
+----
+
+A method annotated `@Transactional` without a connection, called from inside such a block, does not reset the
+routing. Its transaction is the default connection's, but the calls it makes on a class the block routes still
+reach the block's connection, so those writes join the transaction the block opened rather than the one the
+method began - including under `propagation = REQUIRES_NEW`, whose separate transaction then covers none of
+them. Name the connection, as in `@Transactional(connection = 'secondary')`, where the method's own transaction
+has to cover its writes.
+
+Applications using a single datasource are unaffected.
+
+==== 73. Default Security Response Headers
+
+Grails 8 registers a servlet filter that sends default browser hardening headers (`X-Content-Type-Options: nosniff`, `X-Frame-Options: SAMEORIGIN`, `Referrer-Policy: strict-origin-when-cross-origin`, `X-XSS-Protection: 0`) on the responses of every servlet web application, so an upgraded application sends these headers without any change on your part.
+The filter is registered at `GrailsFilters.FIRST`, ahead of the other Grails filters, and writes its headers when the response commits, only if nothing else has set them by then, so values set by your controllers, interceptors, custom filters, or Spring Security header writers at Spring Boot's default `spring.security.filter.order` are preserved.
+If you order the Spring Security chain ahead of `GrailsFilters.FIRST`, its header writers (other than the `X-Frame-Options` writer) find the Grails value already present and leave it; disable the corresponding `grails.security.headers.<header>` in that case.
+Filters ordered ahead of `GrailsFilters.FIRST`, such as Spring Boot's forwarded-header filter and, in a WAR deployment, its `ErrorPageFilter`, run outside the Grails filter, so a response one of them serves itself receives no default headers.
+If a reverse proxy in front of the application already sends these headers (for example through nginx's `add_header`), set `grails.security.headers.defaults: auto` so requests that arrive through the proxy (detected from forwarded request headers, `server.forward-headers-strategy`, or an active cloud platform) receive only the headers you configure explicitly, or strip the application's copies at the proxy.
+To disable or customize the Grails defaults, configure `grails.security.headers.*`; see the Security guide's HTTP Security Headers section for the full list and the reverse-proxy guidance.
+
+==== 74. Scaffolded Views Are Compiled With the Application
+
+In Grails 7 a scaffolded view was expanded from its template and compiled on the first request that asked
+for it. In Grails 8, the pages of every controller annotated `@Scaffold`, the application's or a plugin's, are
+expanded at build time by the `generateScaffoldedViews` task, into `build/generated/scaffolded-views`, and
+compiled by `compileGroovyPages` in the same compilation as `grails-app/views`, under a `grails-scaffolded`
+directory that no controller's views resolve from. The resolver still chooses the
+template for a request exactly as before, and serves the page compiled from that template when there is one,
+so a request gets the same page it did. Which pages are compiled, and what happens to the others, is
+described in the link:scaffolding.html[Scaffolding] guide.
+
+`compileGroovyPages` takes the pages as its `generatedViews`, beside its `source`, so a build that sets the
+`source` itself still compiles them. In a project that scaffolds nothing, `generateScaffoldedViews` writes
+nothing.
+
+A scaffolding template of the application's own, in `src/main/templates/scaffolding` or packaged under
+`META-INF/templates/scaffolding`, is now compiled at build time, so one that cannot be expanded, or whose page
+does not compile, fails the build as a view that does not compile does - where in Grails 7 it failed on the
+first request for the view. A page expanded from a template a dependency supplies that cannot be compiled
+does not fail the build: it is left out, the build output names it, and it is expanded when it is first
+rendered, as in Grails 7.
+
+The `generateScaffoldedViews` task of 8.0.0-RC1 wrote pages into the controllers' view directories and had
+`templateClasspath` and `applicationViews` properties. Both are gone: the templates are read from the
+`runtimeClasspath` the pages are expanded on, and a view the application declares needs no exclusion, since
+it takes precedence over any scaffolded page when a request is resolved. A build that configures either
+property fails with an unknown property; remove the setting.
+
+8.0.0-RC1 also compiled a scaffolding project's views from a copy made by a `stageGroovyPages` task, which
+it registered only when a controller source mentioned `@Scaffold` - decided by
+`GroovyPagePlugin.scaffoldsAnyController`. Both are gone: nothing is copied, and every project generates the
+pages its scaffolded controllers need, a plugin's among them. A build that refers to `stageGroovyPages`
+fails with an unknown task; remove the reference.
+
+==== 75. File Renders Default to Attachment Disposition
+
+Grails 8 makes `render(file: ...)` safer by default. File responses now set
+`Content-Disposition: attachment` unless you opt out. If a `fileName` is supplied
+(or derived from a `File`), unsafe characters in that name are escaped before the
+header is written.
+
+Use `inline: true` when the file should stay inline, or set the
+`Content-Disposition` header yourself before calling `render` — Grails leaves an
+existing header alone.
+
+[source,groovy]
+----
+render(file: new File(absolutePath), fileName: 'report.pdf')
+render(file: new File(absolutePath), inline: true)
+----
+
+==== 76. A List of Objects in Configuration Binds to Its Declared Type
+
+A list of objects in `application.yml` or `application.groovy`, such as:
+
+[source,yaml]
+.application.yml
+----
+springdoc:
+ group-configs:
+ - group: sales
+ paths-to-match: /api/v1/**
+----
+
+is now presented to Spring element by element, under the indexed names Spring Boot binds a list from,
+such as `springdoc.group-configs[0].group`, the way Spring Boot's own YAML loader presents it. A
+`@ConfigurationProperties` class declaring a `List` of objects is bound with instances of that type.
+Previously the whole list was also presented under its own name, so Spring Boot bound it as a list of
+maps, and code reading the declared type failed with a `ClassCastException`. springdoc failed that
+way on `springdoc.group-configs` before the application could start.
+
+`Environment.getProperty('springdoc.group-configs')` now returns `null` and
+`Environment.containsProperty` returns `false`, as they do in a Spring Boot application, so a
+`@Value('${springdoc.group-configs}')` without a default fails to resolve, as does a `${...}`
+placeholder naming the list anywhere else. Read such a list through `grailsApplication.config`,
+which is unchanged, or bind it. The same applies to a list holding lists of objects, such as
+`rows: [[{a: 1}], [{b: 2}]]`, whose objects are presented under names such as `rows[0][0].a`, and to
+a list mixing plain values and objects, such as `mixed: [a, {b: 1}]`, presented as `mixed[0]` and
+`mixed[1].b`. Within such a list, an empty object, an empty list or a `null` value is presented as an
+empty string under its own name, such as `empty[0]` for `empty: [{}]`, as Spring Boot presents it. A
+list of plain values only, such as `names: [a, b]`, is presented as before.
+
+What reads the names the configuration presents sees the change too:
+
+* The `config-report` command lists such a list as a row for each value, such as
+ `springdoc.group-configs[0].group`, rather than one row for the list.
+* GORM used outside a Grails application, given a `ConfigurableEnvironment` it copies the property
+ names of, no longer finds the list under its own name. In a Grails application a datastore is
+ given `grailsApplication.config`, and sees the list as before.
+
+==== 77. JSON Rendering of Dates and Times Matches Spring Boot
+
+JSON rendered by `grails.converters.JSON` (`render ... as JSON`, and `respond` for a JSON request) and by JSON views,
+including `g.render`, writes date and time values the same way as Spring Boot's default Jackson `JsonMapper`. The
+exceptions are listed in the notes at the end of this section.
+
+===== 77.1 What 8.0.0 Restores From Grails 7
+
+8.0.0-RC1 changed how `grails.converters.JSON` and `grails.converters.XML` render some dates. 8.0.0 renders them as
+Grails 7 did, so an application upgrading from Grails 7 needs no change for these:
+
+[cols="2,2,2", options="header"]
+|===
+| Value
+| 8.0.0-RC1
+| Grails 7 and 8.0.0
+
+| A `Date`, `Calendar` or `java.sql.Timestamp` whose milliseconds are zero
+| `"2026-09-25T03:00:00Z"`
+| `"2026-09-25T03:00:00.000Z"`
+
+| A `java.sql.Timestamp` with nanoseconds
+| `"2025-10-08T07:48:46.407254Z"`
+| `"2025-10-08T07:48:46.407Z"`
+
+| A `java.sql.Date` with `grails.converters.JSON` or `grails.converters.XML`, and a `java.sql.Time` with
+`grails.converters.XML`
+| a failure to render it
+| rendered as a `Date` is
+|===
+
+See https://github.com/apache/grails-core/issues/16406[#16406].
+
+===== 77.2 Values That Render Differently Than in Grails 7
+
+Review these where an application or its clients read them:
+
+[cols="2,2,2", options="header"]
+|===
+| Value
+| Grails 7
+| Grails 8
+
+| `java.sql.Time`
+| `"2025-10-08T07:48:46.407Z"`, the UTC instant, which does not bind back to a `java.sql.Time`
+| `"01:48:46"`, from `Time#toString()` in the JVM default time zone, which binds back to the same time of day, to the
+second, as with Spring Boot
+
+| A `Date`, `Calendar`, `java.sql` date type or `ZonedDateTime` map key
+| the key's `toString()`, such as `"Wed Oct 08 01:48:46 MDT 2025"`
+| a `Date` (a `java.sql.Time` too) or `Calendar` key as a `Date` value is written, such as
+`"2025-10-08T07:48:46.407Z"`; a `ZonedDateTime` key as `"2026-09-25T00:00:00-03:00"`
+
+| A `Date` or `Calendar` before 1 AD or after 9999 (`grails.converters.JSON`)
+| `"12345-01-01T00:00:00.000Z"`, `"0044-03-15T00:00:00.000Z"` (44 BC)
+| `"+12345-01-01T00:00:00.000Z"`, `"-0043-03-15T00:00:00.000Z"`, ISO 8601 expanded years
+
+| A `Date` inside a collection that `g.render` writes element by element, such as a `List<Object>`
+| `"2025-10-08T07:48:46+0000"`
+| `"2025-10-08T07:48:46.407Z"`, as any other `Date` value
+
+| A `Date` or `Calendar` in JSON views with a configured `grails.views.json.generator.timeZone` other than `GMT`
+| the offset in hours only, such as `"2025-10-08T03:48:46.407-04"`, and `"2025-10-08T13:18:46.407+05"` for
+`Asia/Kolkata`, which names an instant 30 minutes off
+| the offset in hours and minutes, such as `"2025-10-08T03:48:46.407-04:00"` and `"2025-10-08T13:18:46.407+05:30"`, as
+Spring Boot writes them; the default date format is now `yyyy-MM-dd'T'HH:mm:ss.SSSXXX`
+
+| A `Date` rendered by `grails.converters.XML`
+| `2025-10-08 01:48:46.407 MDT`
+| `2025-10-08T01:48:46.407-06:00`, an ISO-8601 date and time with the offset of the JVM default time zone
+|===
+
+Data binding binds a `Month` from its number as well as its name, as Spring Boot reads it: `9`, `"9"` and `"SEPTEMBER"`
+bind to `SEPTEMBER`. Grails 7 bound a number through Spring's conversion service by ordinal, so `9` bound to `OCTOBER`.
+
+JSON views write `Date` and `Calendar` map keys with `grails.views.json.generator.dateFormat`, in the configured
+`timeZone` and `locale`, as they write those values. As with Spring Boot's `spring.jackson.date-format`, the date format
+no longer applies to `java.sql.Time` values, which are written as `"01:48:46"`.
+
+===== 77.3 Values Grails 7 Did Not Render as Values
+
+These rendered as an object of their properties, as `{}`, or not at all, and now render as values:
+
+[cols="2,2,2", options="header"]
+|===
+| Type
+| Grails 7
+| Grails 8
+
+| `java.time.LocalTime` (`grails.converters.JSON`)
+| `{"hour":1,"minute":48,"nano":407254000,"second":46}`
+| `"01:48:46.407254"`, as JSON views already rendered it
+
+| `java.time.OffsetTime` (`grails.converters.JSON`)
+| an object of its properties
+| `"03:00:00-03:00"`, as JSON views already rendered it
+
+| `java.time.Period` (`grails.converters.JSON`)
+| an object of its properties
+| `"P1Y2M3D"`, as JSON views already rendered it
+
+| `java.time.Year`
+| an object of its properties, or `{}`
+| `2026`, a JSON number
+
+| `java.time.YearMonth`, `java.time.MonthDay`
+| an object of their properties, or `{}`
+| `"2026-09"`, `"--09-25"`
+
+| `java.time.Duration`
+| an object of its properties, or `{}`
+| `"PT1H30M"`, from `Duration#toString()`
+
+| `java.time.ZoneId`, `java.time.ZoneOffset`
+| an object of their properties, including the zone rules, or `{}`
+| `"America/Sao_Paulo"`, `"-03:00"`
+
+| `java.util.TimeZone`
+| an object of its properties, or a failure to render it
+| `"America/Sao_Paulo"`, its ID
+
+| `javax.xml.datatype.XMLGregorianCalendar`
+| an object of its properties
+| as a `Calendar` is, such as `"2025-10-08T07:48:46.407Z"`
+
+| `javax.xml.datatype.Duration`
+| a failure to render it
+| `"P1DT2H"`, from `Duration#toString()`
+|===
+
+===== 77.4 Keeping the Grails 7 Rendering
+
+To keep the Grails 7 rendering of a type, register an object marshaller for it with `grails.converters.JSON`, for
+example in `BootStrap.init`, and a `groovy.json.JsonGenerator.Converter` for it in JSON views, as described in
+section 24, Custom JSON View Converters:
+
+[source,groovy]
+----
+DateTimeFormatter utc = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC)
+JSON.registerObjectMarshaller(java.sql.Time) { java.sql.Time time ->
+ utc.format(Instant.ofEpochMilli(time.time))
+}
+----
+
+A JSON views converter that returns `new Date(time.time)` for a `java.sql.Time` writes it with the configured
+`dateFormat`, as Grails 7 did. Map keys are not rendered by marshallers or converters: to keep the `toString()` of a date
+key, convert the keys to strings before rendering the map, for example with
+`map.collectEntries { key, value -> [(key.toString()): value] }`.
+
+The default JSON marshallers have implicit priorities that follow their order (-1, -2, and so on), and the marshallers
+added in 8.0 shift those, so a marshaller registered with an explicit negative priority may now come before or after
+different defaults. Marshallers registered with the default priority of 0, or higher, still take precedence over all
+of the defaults. A marshaller registered for `Date` or `Calendar`, like `grails.converters.json.date` set to
+`javascript`, changes how those values render with `grails.converters.JSON`, but not map keys of those types, which
+keep the form in the table above. JSON views format date map keys with `dateFormat`, as described above.
+
+NOTE: Enums render by `name()`, as described in section 8, Enum Serialization Default Changed, while Jackson 3 writes an
+enum's `toString()`, and a `java.time.Month` as its number. The two differ for `Month` (`"SEPTEMBER"` in Grails, `9` in
+Spring Boot) and for enums that override `toString()`, such as `java.time.temporal.ChronoUnit` (`"SECONDS"` in Grails,
+`"Seconds"` in Spring Boot). To render a `Month` as its number, register
+`JSON.registerObjectMarshaller(Month) { Month month -> month.value }` and a JSON views converter that returns
+`month.value`.
+
+NOTE: An `OffsetTime` keeps its seconds and writes a fraction of a second with only the digits it needs, such as
+`"03:00:00-03:00"`, as JSON views have written it since Grails 7, where Spring Boot writes `"03:00-03:00"`. JSON views
+write a year before 1 AD or after 9999 as Grails 7 did.
+
+NOTE: The HAL renderer, `grails.rest.render.hal.HalJsonRenderer` for `application/hal+json`, writes values with Groovy's
+default JSON generator and is not changed.
+
+==== 78. A Date With an Offset Is Bound to the Instant It Names
+
+When controllers, command objects and `bindData` bind a request, a date and time in its ISO 8601
+form, with a `T` between the date and the time, which is how Grails renders a date in JSON, is now
+read first, before the formats that `grails.databinding.dateFormats` lists are tried. Previously:
+
+* `2024-05-01T10:00:00Z`, which 8.0.0-RC1 renders for a `Date` or a `Calendar` whose milliseconds are
+ zero, and which a client may send for any date, was read by the `yyyy-MM-dd'T'HH:mm:ss'Z'` format
+ as a time in the zone of the server, so it was bound off by the offset of that zone.
+* `2024-05-01T10:00:00+02:00` was read by `yyyy-MM-dd'T'HH:mm:ss`, which left the offset unread,
+ and was bound as a time in the zone of the server.
+* A fraction of a second of fewer than three digits, such as the `.5` of `10:00:00.5Z`, was read as
+ milliseconds, so as 5 rather than 500.
+* An `OffsetDateTime` or a `ZonedDateTime` could not be bound from `2024-05-01T10:00:00Z` or
+ `2024-05-01T10:00:00+02:00`, which is how Grails renders them, and a `LocalDateTime` or a
+ `LocalTime` could not be bound from a value with a fraction of a second.
+
+Each is now bound to what it names. A server running in UTC saw the first two bound correctly
+before, and sees no change.
+
+The formats in `grails.databinding.dateFormats` are then tried in order, and a format that reads all
+of the value is now used before an earlier one that reads only the start of it. A value that no format
+reads all of is bound as before, by the first format that reads the start of it: `2024-05-01 10:00`
+is still bound as midnight by `yyyy-MM-dd`, losing the time. Add a format that reads the whole value,
+such as `yyyy-MM-dd HH:mm`, to keep the time.
+
+The date scalars of GraphQL, which read `grails.databinding.dateFormats` too, are not changed.
+
+==== 79. Asset Pipeline Wildcards Stand for One Directory
+
+Grails 8 uses asset-pipeline 5.2, which resolves a `%` or `*` component of an asset path, in a `require`
+directive, an `<asset:...>` tag or a Sass import, the same way wherever the asset is found: as exactly one
+directory.
+
+In Grails 7, which used asset-pipeline 5.0, a `%` could stand for any number of directories when the asset
+was in a jar, as the files of every webjar are, and in the manifest that a packaged application serves its
+assets from. `webjars/%/dist/jquery.js` found `webjars/jquery/3.7.1/dist/jquery.js`, and now finds nothing,
+since one `%` cannot stand for both `jquery` and `3.7.1`.
+
+Write a `%` in place of each directory, as applications generated by `create-app` do for the version
+directory of each webjar, or use the new `%%` (or `**`), which stands for zero or more directories:
+
+[source,javascript]
+.grails-app/assets/javascripts/application.js
+----
+//= require webjars/jquery/%/dist/jquery.js
+//= require webjars/%%/dist/js/bootstrap.bundle.js
+----
+
+In a CSS `require` block, write `%` and `%%` rather than `+*+` and `+**+`, because `*/` ends the comment the
+block is written in. A path with one `%` for each directory, including every path `create-app` has
+generated, resolves as before, unless more than one directory matches (see below).
+
+When several directories match, the highest version is used: `5.1.2` over `4.3.0`, `10.0.0` over `9.0.0`,
+and a release over its own pre-releases. Before, the first match found was used, in the order of the file
+system, the jars on the classpath or the manifest. Where `%%` can match at more than one depth, the match with
+the fewest directories wins, so a copy of a library that another webjar bundles further down is not picked
+up. Hidden directories, whose names start with `.`, are never matched, and a wildcard inside a file name,
+such as `jquery-%.js`, no longer resolves in a packaged application, as it never resolved in development.
+
+A path that no longer resolves does not fail the build: `assetCompile` logs `Unable to Locate Asset: <path>`
+and leaves the file out, and an `<asset:...>` tag renders the path unchanged, which the browser then fails to
+load. Check the `assetCompile` output for that warning after upgrading.
+
+NOTE: The `includes` and `excludes` patterns of the `assets` block in `build.gradle`, which select the files
+`assetCompile` processes, are not changed.
+
+==== 80. Stricter Closure Typing for GORM Criteria Closures
+
+GORM's criteria closure methods (`where`, `whereLazy`, `build`, `buildLazy`, `projections`,
+`and`, `or`, `not`, `find`, `get`, `list`, `count`, `asBoolean` and the closure subquery forms
+of `in`, `inList`, `notIn`, `eqAll`, `gtAll`, `ltAll`, `geAll`, `leAll`, `gtSome`, `geSome`,
+`ltSome` and `leSome`) now declare
+`strategy = Closure.DELEGATE_FIRST` in their `@DelegatesTo` annotations. This matches the
+resolve strategy GORM already applies at runtime and fixes a `@CompileStatic` bug where the
+restrictions of a criteria closure nested inside another criteria closure were added to the
+enclosing criteria instead of the new one. Projection blocks resolved against the enclosing
+criteria for the same reason, silently dropping their projections. See
+https://github.com/apache/grails-core/issues/16425[Issue #16425].
+
+Statically compiled applications can be affected in two ways.
+
+**Forwarding a `Closure` parameter to one of these methods no longer compiles.** A method
+`Closure` parameter with the default `OWNER_FIRST` strategy cannot be passed to a
+`DELEGATE_FIRST` parameter:
+
+[source,groovy]
+----
+@CompileStatic
+static DetachedCriteria<Book> withExtra(Closure extra) {
+ new DetachedCriteria<Book>(Book).where(extra)
+ // [Static type checking] - Closure parameter with resolve strategy OWNER_FIRST
+ // passed to method with resolve strategy DELEGATE_FIRST
+}
+----
+
+Declare the same strategy on your parameter, or cast the argument:
+
+[source,groovy]
+----
+static DetachedCriteria<Book> withExtra(
+ @DelegatesTo(value = DetachedCriteria, strategy = Closure.DELEGATE_FIRST) Closure extra) {
+ new DetachedCriteria<Book>(Book).where(extra)
+}
+
+// or
+new DetachedCriteria<Book>(Book).where((Closure) extra)
+----
+
+**Name resolution inside a criteria closure now prefers the criteria delegate**, which is
+what dynamic code already did. A property or method that exists both on the enclosing class
+and on the criteria now resolves to the criteria:
+
+[source,groovy]
+----
+@CompileStatic
+class BookQueries {
+ List<Order> getOrders() { ... }
+
+ DetachedCriteria<Book> query() {
+ new DetachedCriteria<Book>(Book).where {
+ inList 'name', orders // now reads the criteria's orders, not getOrders()
+ }
+ }
+}
+----
+
+==== 81. XML-Safe HTML Escaping Is the Default
+
+When `grails.views.gsp.htmlcodec` is not set, the HTML codec, which GSP uses to escape `${}` expressions and
+which `encodeAsHTML()` applies, now uses the XML-safe escaping that applications generated by `create-app`
+and Grails Forge have selected with `htmlcodec: xml` since Grails 2.3. Before, it used HTML4 style escaping.
+New applications no longer have the setting, since it is now the default.
+
+Applications that set `htmlcodec: xml` are not affected, and can keep or remove the setting. Applications
+without the setting now get different escaped output:
+
+* Non-ASCII characters are written as they are instead of as named entities: `Gösta` is no longer escaped
+as `Gösta`.
+* `@`, the backslash and the backtick are escaped as `@`, `\` and ```, the non breaking space and
+the line and paragraph separators as numeric character references, and control characters other than tab,
+line feed and carriage return are dropped.
+
+Tests that compare escaped markup exactly may need to be updated. An application that serves pages in a
+character set that cannot represent every character, such as ISO-8859-1, and relies on the named entities,
+can restore HTML4 style escaping:
+
+[source,yaml]
+.application.yml
+----
+grails:
+ views:
+ gsp:
+ htmlcodec: html4
+----
+
+See link:security.html#codecs[Encoding and Decoding Objects].
+
+==== 82. Mail Plugin: `overrideAddress` Also Replaces an Explicit Sender
+
+`grails.mail.overrideAddress` now also replaces a `from` set in the `sendMail` closure. In Grails 7, it replaced every `to`, `cc` and `bcc` address and the default sender, and an explicit `from` was kept.
+
+To keep the sender your application sets, while still redirecting every recipient, use the new `grails.mail.overrideToAddress` in place of `overrideAddress`:
+
+[source,yaml]
+.application-development.yml
+----
+grails:
+ mail:
+ overrideToAddress: test-inbox@example.com # redirect all recipients (to, cc, bcc) only
+----
+
+To set a fixed sender without redirecting recipients, use the new `grails.mail.overrideFromAddress`. See link:mail.html#mailConfiguration[Mail Configuration] for how the three properties interact.
+
+==== 83. GORM Dynamic Finder Classes Replaced
+
+The dynamic finder implementations in the `org.grails.datastore.gorm.finders` package no longer form an inheritance hierarchy. The following public classes have been removed:
+
+* `AbstractFinder`
+* `AbstractFindByFinder`
+* `FindByFinder`
+* `FindByBooleanFinder`
+* `FindAllByFinder`
+* `FindAllByBooleanFinder`
+* `FindOrCreateByFinder`
+* `FindOrSaveByFinder`
+* `CountByFinder`
+
+`DynamicFinder` is now a concrete class that only parses a finder method name and builds its query criteria. It no longer implements `FinderMethod`, has no `invoke` or `doInvokeInternal` methods, and its constructor takes a method pattern, the junction operators, a `MappingContext` and a boolean-clause flag. Finder execution lives in three classes that compose a `DynamicFinder` instead of extending it and are created through static factory methods:
+
+[source,groovy]
+----
+import org.grails.datastore.gorm.finders.CountFinder
+import org.grails.datastore.gorm.finders.ListResultFinder
+import org.grails.datastore.gorm.finders.SingleResultFinder
+
+SingleResultFinder.findBy(datastoreResolver, mappingContext) // findBy*
+SingleResultFinder.findByBoolean(datastoreResolver, mappingContext) // find<Boolean>By*
+SingleResultFinder.findOrCreateBy(datastoreResolver, mappingContext) // findOrCreateBy*
+SingleResultFinder.findOrSaveBy(datastoreResolver, mappingContext) // findOrSaveBy*
+ListResultFinder.findAllBy(datastoreResolver, mappingContext) // findAllBy*
+ListResultFinder.findAllByBoolean(datastoreResolver, mappingContext) // findAll<Boolean>By*
+CountFinder.countBy(datastoreResolver, mappingContext) // countBy*
+----
+
+Each factory also accepts a `Datastore`, or only a `MappingContext` for a finder that parses method names without executing queries. `ListOrderByFinder` keeps its constructors but no longer extends `AbstractFinder`, and the list of finders a `DetachedCriteria` consults is now typed as `List<FinderMethod>`.
+
+Applications are unaffected: dynamic finders such as `Book.findByTitle('The Stand')` behave as before. A GORM datastore implementation or plugin outside the Grails repository that extends one of the removed classes, or that calls `new FindByFinder(...)` and its siblings when building its finder list, must switch to the factory methods above. Code that only holds finders as `FinderMethod` compiles unchanged.
+
+==== 84. Interceptors Can Read the Model of a Template Render
+
+The `model` property of an interceptor now returns the map that an action passed to
+`render(template: ..., model: ...)`. Before, it returned `null` for a template render, because a template render
+produces no `ModelAndView`. Responses rendered from a view are not affected.
+
+The template has already been rendered when `after()` runs, so the model can be inspected but not changed. Review
+interceptors that check `model != null`, or use `model?.`, before changing the model, since that code now also runs
+for template renders:
+
+* Changes to the map have no effect on the response, and they change the map that the action passed.
+* If the action passed an immutable map, such as one created with `Map.of(...)`, changing it throws an
+`UnsupportedOperationException`. Before, `model?.foo = 'bar'` did nothing.
+
+Objects passed with `bean` or `collection` are not part of `model`. See
+link:theWebLayer.html#definingInterceptors[Defining Interceptors].
+
+==== 85. Gradle Configuration Cache
+
+The Grails Gradle plugins of Grails 8.0, and the Asset Pipeline and Grails Publish plugins in the versions the Grails 8.0 BOM manages, support the https://docs.gradle.org/{gradleVersion}/userguide/configuration_cache.html[Gradle configuration cache].
+Applications and plugins created with Grails 8.0 enable it in `gradle.properties`.
+
+An application or plugin upgraded to Grails 8.0 can enable it by adding the same property, once it uses the Grails 8.0 Gradle plugins and BOM:
+
+[source,properties]
+.gradle.properties
+----
+org.gradle.configuration-cache=true
+----
+
+When upgrading from an earlier Grails 8 milestone or release candidate, update the Grails Gradle plugins and BOM before enabling the configuration cache.
+
+With the configuration cache, task actions such as `doFirst` and `doLast` closures may not use `project`, other tasks or build script properties while they run, and Gradle fails the build when a build script or another Gradle plugin does.
+See xref:commandLine#gradleConfigurationCache[Using the Gradle Configuration Cache] for how to adapt build scripts and what to do about plugins that do not support it.
+
+==== 86. Grails Data Plugins Leave the Buildscript Classpath
+
+Builds generated by earlier versions of Grails Forge placed the Grails Data plugin on the Gradle `buildscript` classpath, next to the Grails Gradle plugins, and in `buildSrc` when the build used one:
+
+[source,groovy]
+.build.gradle (before)
+----
+buildscript {
+ dependencies {
+ classpath "org.apache.grails:grails-gradle-plugins"
+ classpath "org.apache.grails:grails-data-hibernate5"
+ }
+}
+----
+
+Remove that `classpath` entry (and the matching `implementation` line in `buildSrc/build.gradle`), keeping only the `implementation` dependency of the application itself:
+
+[source,groovy]
+.build.gradle (after)
+----
+buildscript {
+ dependencies {
+ classpath "org.apache.grails:grails-gradle-plugins"
+ }
+}
+
+dependencies {
+ implementation "org.apache.grails:grails-data-hibernate5"
+}
+----
+
+The entry was a leftover from the days when the Grails CLI found a plugin's commands through the build classpath; commands now ship in companion `-cli` artifacts that the Grails Gradle plugin discovers from the application's dependencies (see <<cli-companion-artifacts,CLI Commands Move to Companion `-cli` Artifacts>>).
+Left in place, the plugin and its transitive Grails Data modules are loaded by the Groovy that Gradle embeds while it compiles `build.gradle`, and the global compile-time transformations those modules register run in that older Groovy.
+A build whose `buildscript` classpath still carries the plugin can fail at configuration time with an error such as `java.lang.NoSuchMethodError: 'java.lang.Number org.codehaus.groovy.runtime.typehandling.NumberMath.remainder(java.lang.Number, java.lang.Number)'` raised from `GlobalDetachedCriteriaASTTransformation`.
+The same applies to `grails-data-hibernate7` and to any other Grails module that registers a global transformation: none of them belong on the `buildscript` classpath.
+
+==== 87. Only Tenants.withoutId runs without a tenant with DISCRIMINATOR multi-tenancy
+
+With `DISCRIMINATOR` multi-tenancy, only `Tenants.withoutId` and `@WithoutTenant` run without a tenant. A tenant id of `default` is a tenant id like any other, whether a `TenantResolver` returns it or it is passed to `Tenants.withId`. Queries return the instances of the tenant `default`, and a saved instance gets the tenant id `default`.
+
+* Code that relied on a resolver returning `default` to work with every tenant has to run inside `Tenants.withoutId` or in a method annotated with `@WithoutTenant`. Examples are `SubDomainTenantResolver` on `localhost` during development, and `new FixedTenantResolver()`.
+* With GORM for MongoDB, GORM for Neo4j and GORM's in-memory datastore, queries inside `Tenants.withoutId` still return only the instances of the tenant `default`. There, `Tenants.withoutId` only lets a saved instance keep the tenant id that is set on it.
+* With a numeric tenant id, a resolver that returns `default` now fails, as it does with GORM for Hibernate. Inside `Tenants.withoutId`, GORM for MongoDB, GORM for Neo4j and GORM's in-memory datastore still use `0` for a numeric tenant id.
+* Inside `Tenants.withoutId`, `Tenants.currentId()` returns `default`, and `Tenants.withCurrent` and `@CurrentTenant` keep running without a tenant. `Tenants.isWithoutId(datastore)` tells whether the current code runs without a tenant id for a datastore, and `Tenants.isWithoutId()` does so for the default datastore. Unlike in Grails 7.0.x, `Tenants.isWithoutId()` looks up that datastore, as `Tenants.currentId()` does, so it throws an `IllegalStateException` when GORM isn't initialized o [...]
+* GORM for Hibernate also restricts a collection of a multi-tenant entity to the current tenant when it is loaded lazily or fetched by join, also when it is a many-to-many collection or a query fetches it by join through another association, and `load` and `proxy` of a multi-tenant entity run a query, as `get` does. Like `get`, they return `null` when no instance is found, instead of a proxy that fails when it is used. A collection of a multi-tenant entity that is mapped with `fetch: 'j [...]
+* Before a query on an entity that isn't multi-tenant but has a collection of a multi-tenant entity, directly or through its associations, GORM for Hibernate now calls the `TenantResolver` and activates the filter for the current tenant, so that a collection the query fetches by join is restricted. When there is no current tenant, because the resolver throws a `TenantNotFoundException` or returns `null`, such a query runs as before. Any other exception from the resolver fails the query. [...]
+* A `TenantResolver` that returns `null` now causes a `TenantNotFoundException`, as a resolver that finds no tenant does, in every multi-tenancy mode.
+* The `DATABASE` and `SCHEMA` modes are otherwise unchanged.
++
++==== 88. Lookups by id are restricted to the current tenant with DISCRIMINATOR multi-tenancy
++
++With `DISCRIMINATOR` multi-tenancy, GORM for MongoDB, GORM for Neo4j and GORM's in-memory datastore used by unit tests now restrict `get`, `read`, `exists`, `getAll`, `load` and `proxy` to the current tenant, as queries and dynamic finders already were. Previously these methods looked an instance up by its id alone, so they returned an instance that belongs to another tenant. GORM for Hibernate is unchanged: it already restricts `get`, `read`, `exists` and `getAll` to the current tenant [...]
++
++* The id of another tenant's instance is treated like an id that does not exist: `get` and `read` return `null`, `exists` returns `false`, `getAll` returns `null` in its place, and the proxy returned by `load` or `proxy` throws when it is initialized.
++* Without a current tenant, these methods throw `TenantNotFoundException`, as a query does. `getAll` without ids still returns an empty list.
++* Inside `Tenants.withoutId { }` a lookup by id is still not restricted to a tenant, and neither is a proxy returned by `load` or `proxy` that is initialized there. As the previous note says, only `withoutId` lifts the restriction: a tenant id of `default` restricts a lookup by id to that tenant as it restricts a query.
++* A lookup by id still finds an instance that the session holds for the current tenant, including one that has been saved but not flushed, and it does not flush the session.