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/07/08 03:25:36 UTC

(grails-core) branch hibernateProxyFix updated: Ensure toString() unwraps proxy like it did historically and allow opt in to not

This is an automated email from the ASF dual-hosted git repository.

jdaugherty pushed a commit to branch hibernateProxyFix
in repository https://gitbox.apache.org/repos/asf/grails-core.git


The following commit(s) were added to refs/heads/hibernateProxyFix by this push:
     new 96c0aedc35 Ensure toString() unwraps proxy like it did historically and allow opt in to not
96c0aedc35 is described below

commit 96c0aedc357012c864182adffe1e549c405c81cc
Author: James Daugherty <jd...@jdresources.net>
AuthorDate: Tue Jul 7 23:25:13 2026 -0400

    Ensure toString() unwraps proxy like it did historically and allow opt in to not
---
 .../proxy/ByteBuddyGroovyInterceptor.java          |  8 ++-
 .../proxy/ByteBuddyGroovyProxyFactory.java         |  9 ++-
 .../hibernate/proxy/GrailsProxyFactoryFactory.java |  8 ++-
 .../proxy/GroovyProxyInterceptorLogic.java         | 17 +++++-
 .../META-INF/spring-configuration-metadata.json    | 10 ++++
 .../gorm/tests/proxy/ByteBuddyProxySpec.groovy     | 19 ++++++
 .../proxy/LazyToStringByteBuddyProxySpec.groovy    | 67 ++++++++++++++++++++++
 .../proxy/GroovyProxyInterceptorLogicSpec.groovy   | 22 ++++++-
 .../configuration/configurationReference.adoc      | 19 ++++++
 .../proxy/ByteBuddyGroovyInterceptor.java          |  8 ++-
 .../proxy/ByteBuddyGroovyProxyFactory.java         |  9 ++-
 .../hibernate/proxy/GrailsProxyFactoryFactory.java |  8 ++-
 .../proxy/GroovyProxyInterceptorLogic.java         | 17 +++++-
 .../META-INF/spring-configuration-metadata.json    | 10 ++++
 .../gorm/tests/proxy/ByteBuddyProxySpec.groovy     | 19 ++++++
 .../proxy/LazyToStringByteBuddyProxySpec.groovy    | 65 +++++++++++++++++++++
 .../proxy/ByteBuddyGroovyInterceptorSpec.groovy    | 11 ++--
 .../proxy/GroovyProxyInterceptorLogicSpec.groovy   | 22 ++++++-
 .../configuration/configurationReference.adoc      | 19 ++++++
 .../src/test/groovy/example/ProxySpec.groovy       |  3 -
 .../src/test/groovy/example/ProxySpec.groovy       |  3 -
 21 files changed, 347 insertions(+), 26 deletions(-)

diff --git a/grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/proxy/ByteBuddyGroovyInterceptor.java b/grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/proxy/ByteBuddyGroovyInterceptor.java
index 00224acb78..73a2b6e1ed 100644
--- a/grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/proxy/ByteBuddyGroovyInterceptor.java
+++ b/grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/proxy/ByteBuddyGroovyInterceptor.java
@@ -36,6 +36,8 @@ public class ByteBuddyGroovyInterceptor extends ByteBuddyInterceptor {
     private static final String GET_ID_METHOD = "getId";
     private static final String GET_IDENTIFIER_METHOD = "getIdentifier";
 
+    private final boolean lazyToString;
+
     @SuppressWarnings({ "unchecked", "rawtypes" })
     public ByteBuddyGroovyInterceptor(
             String entityName,
@@ -46,7 +48,8 @@ public class ByteBuddyGroovyInterceptor extends ByteBuddyInterceptor {
             Method setIdentifierMethod,
             CompositeType componentIdType,
             SharedSessionContractImplementor session,
-            boolean overridesEquals) {
+            boolean overridesEquals,
+            boolean lazyToString) {
         super(
                 entityName,
                 (Class) persistentClass,
@@ -57,6 +60,7 @@ public class ByteBuddyGroovyInterceptor extends ByteBuddyInterceptor {
                 componentIdType,
                 session,
                 overridesEquals);
+        this.lazyToString = lazyToString;
     }
 
     @Override
@@ -72,7 +76,7 @@ public class ByteBuddyGroovyInterceptor extends ByteBuddyInterceptor {
 
         if (isUninitialized()) {
             GroovyProxyInterceptorLogic.InterceptorState state = new GroovyProxyInterceptorLogic.InterceptorState(
-                    getEntityName(), persistentClass, getIdentifier());
+                    getEntityName(), persistentClass, getIdentifier(), lazyToString);
             Object result = GroovyProxyInterceptorLogic.handleUninitialized(state, methodName, args);
             if (result != GroovyProxyInterceptorLogic.INVOKE_IMPLEMENTATION) { // NOPMD: sentinel comparison
                 return result;
diff --git a/grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/proxy/ByteBuddyGroovyProxyFactory.java b/grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/proxy/ByteBuddyGroovyProxyFactory.java
index 1b4fbdace3..861ae2ad3f 100644
--- a/grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/proxy/ByteBuddyGroovyProxyFactory.java
+++ b/grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/proxy/ByteBuddyGroovyProxyFactory.java
@@ -54,10 +54,16 @@ public class ByteBuddyGroovyProxyFactory extends ByteBuddyProxyFactory {
     private transient CompositeType componentIdType;
     private boolean overridesEquals;
     private Class<?> proxyClass;
+    private final boolean lazyToString;
 
     public ByteBuddyGroovyProxyFactory(ByteBuddyProxyHelper byteBuddyProxyHelper) {
+        this(byteBuddyProxyHelper, false);
+    }
+
+    public ByteBuddyGroovyProxyFactory(ByteBuddyProxyHelper byteBuddyProxyHelper, boolean lazyToString) {
         super(byteBuddyProxyHelper);
         this.byteBuddyProxyHelper = byteBuddyProxyHelper;
+        this.lazyToString = lazyToString;
     }
 
     @Override
@@ -96,7 +102,8 @@ public class ByteBuddyGroovyProxyFactory extends ByteBuddyProxyFactory {
                     setIdentifierMethod,
                     componentIdType,
                     session,
-                    overridesEquals);
+                    overridesEquals,
+                    lazyToString);
 
             final HibernateProxy hibernateProxy =
                     (HibernateProxy) proxyClass.getDeclaredConstructor().newInstance();
diff --git a/grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/proxy/GrailsProxyFactoryFactory.java b/grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/proxy/GrailsProxyFactoryFactory.java
index 0cb77ba71a..48e0a1cdd5 100644
--- a/grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/proxy/GrailsProxyFactoryFactory.java
+++ b/grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/proxy/GrailsProxyFactoryFactory.java
@@ -47,7 +47,13 @@ public class GrailsProxyFactoryFactory implements ProxyFactoryFactory, java.io.S
 
     @Override
     public ProxyFactory buildProxyFactory(SessionFactoryImplementor sessionFactory) {
-        return new ByteBuddyGroovyProxyFactory(grailsBytecodeProvider.getByteBuddyProxyHelper());
+        return new ByteBuddyGroovyProxyFactory(grailsBytecodeProvider.getByteBuddyProxyHelper(),
+                isLazyToString(sessionFactory));
+    }
+
+    private static boolean isLazyToString(SessionFactoryImplementor sessionFactory) {
+        Object value = sessionFactory.getProperties().get(GroovyProxyInterceptorLogic.PROPERTY_LAZY_TO_STRING);
+        return value != null && Boolean.parseBoolean(value.toString());
     }
 
     @Override
diff --git a/grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/proxy/GroovyProxyInterceptorLogic.java b/grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/proxy/GroovyProxyInterceptorLogic.java
index 056f3c4cf9..781f1aea0b 100644
--- a/grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/proxy/GroovyProxyInterceptorLogic.java
+++ b/grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/proxy/GroovyProxyInterceptorLogic.java
@@ -36,6 +36,14 @@ public class GroovyProxyInterceptorLogic {
 
     public static final Object INVOKE_IMPLEMENTATION = new Object();
 
+    /**
+     * Setting that controls {@code toString()} on an uninitialized proxy. When {@code false}
+     * (the default, matching Grails 7 and earlier), {@code toString()} initializes the proxy
+     * and delegates to the entity's own implementation. When {@code true}, the proxy answers
+     * {@code entityName:id} without initializing.
+     */
+    public static final String PROPERTY_LAZY_TO_STRING = "hibernate.grails.proxy.lazy_to_string";
+
     private static final String GET_META_CLASS = "getMetaClass";
     private static final String SET_META_CLASS = "setMetaClass";
     private static final String META_CLASS_PROPERTY = "metaClass";
@@ -65,7 +73,7 @@ public class GroovyProxyInterceptorLogic {
         if ((IS_DIRTY.equals(methodName) || HAS_CHANGED.equals(methodName)) && (args == null || args.length == 0)) {
             return false;
         }
-        if (TO_STRING.equals(methodName) && (args == null || args.length == 0)) {
+        if (state.lazyToString() && TO_STRING.equals(methodName) && (args == null || args.length == 0)) {
             return state.entityName() + ":" + state.identifier();
         }
         return INVOKE_IMPLEMENTATION;
@@ -120,5 +128,10 @@ public class GroovyProxyInterceptorLogic {
         return null;
     }
 
-    public record InterceptorState(String entityName, Class<?> persistentClass, Object identifier) {}
+    public record InterceptorState(String entityName, Class<?> persistentClass, Object identifier, boolean lazyToString) {
+
+        public InterceptorState(String entityName, Class<?> persistentClass, Object identifier) {
+            this(entityName, persistentClass, identifier, false);
+        }
+    }
 }
diff --git a/grails-data-hibernate5/core/src/main/resources/META-INF/spring-configuration-metadata.json b/grails-data-hibernate5/core/src/main/resources/META-INF/spring-configuration-metadata.json
index 7a51260417..3f7709ecd5 100644
--- a/grails-data-hibernate5/core/src/main/resources/META-INF/spring-configuration-metadata.json
+++ b/grails-data-hibernate5/core/src/main/resources/META-INF/spring-configuration-metadata.json
@@ -3,6 +3,10 @@
         {
             "name": "hibernate.cache",
             "description": "Hibernate"
+        },
+        {
+            "name": "hibernate.grails.proxy",
+            "description": "Grails entity proxy behavior"
         }
     ],
     "properties": [
@@ -23,6 +27,12 @@
             "type": "java.lang.Boolean",
             "description": "Whether to enable Hibernate's query cache.",
             "defaultValue": false
+        },
+        {
+            "name": "hibernate.grails.proxy.lazy_to_string",
+            "type": "java.lang.Boolean",
+            "description": "Whether toString() on an uninitialized entity proxy returns entityName:id without initializing it. When false (the default, matching Grails 7 and earlier), toString() initializes the proxy and delegates to the domain class's own implementation.",
+            "defaultValue": false
         }
     ]
 }
diff --git a/grails-data-hibernate5/core/src/test/groovy/grails/gorm/tests/proxy/ByteBuddyProxySpec.groovy b/grails-data-hibernate5/core/src/test/groovy/grails/gorm/tests/proxy/ByteBuddyProxySpec.groovy
index 81c3ea3751..d1c4bbb831 100644
--- a/grails-data-hibernate5/core/src/test/groovy/grails/gorm/tests/proxy/ByteBuddyProxySpec.groovy
+++ b/grails-data-hibernate5/core/src/test/groovy/grails/gorm/tests/proxy/ByteBuddyProxySpec.groovy
@@ -151,6 +151,25 @@ needs the identifier must use id/ident()/getIdentifier() instead of unwrapping"
         !proxyHandler.isInitialized(team.club)
     }
 
+    void "toString initializes the proxy and delegates to the entity implementation by default"() {
+        when:"load proxy"
+        Team team = createATeam()
+        def clubId = team.club.id
+        manager.session.clear()
+        Club club = Club.load(clubId)
+
+        then:"the proxy starts uninitialized"
+        proxyHandler.isProxy(club)
+        !proxyHandler.isInitialized(club)
+
+        when:"toString is called"
+        String value = club.toString()
+
+        then:"the entity's own toString runs, which requires initialization"
+        value == "DOOM Club"
+        proxyHandler.isInitialized(club)
+    }
+
     void "isDirty should not intialize the association proxy"() {
         when:"load instance"
         Team team = createATeam()
diff --git a/grails-data-hibernate5/core/src/test/groovy/grails/gorm/tests/proxy/LazyToStringByteBuddyProxySpec.groovy b/grails-data-hibernate5/core/src/test/groovy/grails/gorm/tests/proxy/LazyToStringByteBuddyProxySpec.groovy
new file mode 100644
index 0000000000..e835497a2a
--- /dev/null
+++ b/grails-data-hibernate5/core/src/test/groovy/grails/gorm/tests/proxy/LazyToStringByteBuddyProxySpec.groovy
@@ -0,0 +1,67 @@
+/*
+ *  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.proxy
+
+import grails.gorm.tests.entities.Club
+import grails.gorm.tests.entities.Team
+import org.apache.grails.data.hibernate5.core.GrailsDataHibernate5TckManager
+import org.apache.grails.data.testing.tck.base.GrailsDataTckSpec
+import org.grails.orm.hibernate.proxy.HibernateProxyHandler
+import spock.lang.Shared
+
+/**
+ * Verifies proxy toString behavior when the {@code hibernate.grails.proxy.lazy_to_string}
+ * setting is enabled: toString on an uninitialized proxy answers {@code entityName:id}
+ * without initializing it, while an initialized proxy delegates to the entity implementation.
+ */
+class LazyToStringByteBuddyProxySpec extends GrailsDataTckSpec<GrailsDataHibernate5TckManager> {
+
+    void setupSpec() {
+        // nested map: only nested config reaches the arbitrary hibernate settings map,
+        // producing the flattened hibernate.grails.proxy.lazy_to_string property
+        manager.grailsConfig = [
+                hibernate: [grails: [proxy: [lazy_to_string: 'true']]]
+        ]
+        manager.registerDomainClasses(Team, Club)
+    }
+
+    @Shared
+    HibernateProxyHandler proxyHandler = new HibernateProxyHandler()
+
+    void "toString does not initialize the proxy when lazy toString is enabled"() {
+        when: "a proxy is loaded"
+        Club c = new Club(name: "DOOM Club").save(failOnError: true, flush: true)
+        def id = c.id
+        manager.session.clear()
+        Club club = Club.load(id)
+
+        then: "toString answers entityName:id without initializing the proxy"
+        proxyHandler.isProxy(club)
+        !proxyHandler.isInitialized(club)
+        club.toString() == "${Club.name}:${id}"
+        !proxyHandler.isInitialized(club)
+
+        when: "the proxy is initialized by accessing a regular property"
+        club.name
+
+        then: "toString delegates to the entity implementation"
+        proxyHandler.isInitialized(club)
+        club.toString() == "DOOM Club"
+    }
+}
diff --git a/grails-data-hibernate5/core/src/test/groovy/org/grails/orm/hibernate/proxy/GroovyProxyInterceptorLogicSpec.groovy b/grails-data-hibernate5/core/src/test/groovy/org/grails/orm/hibernate/proxy/GroovyProxyInterceptorLogicSpec.groovy
index e2e4b29881..1ee3cee924 100644
--- a/grails-data-hibernate5/core/src/test/groovy/org/grails/orm/hibernate/proxy/GroovyProxyInterceptorLogicSpec.groovy
+++ b/grails-data-hibernate5/core/src/test/groovy/org/grails/orm/hibernate/proxy/GroovyProxyInterceptorLogicSpec.groovy
@@ -60,14 +60,32 @@ class GroovyProxyInterceptorLogicSpec extends Specification {
         "ident"        | [] as Object[]
     }
 
-    def "handleUninitialized handles toString"() {
-        given:
+    def "handleUninitialized delegates toString to the implementation by default"() {
+        given: "state without lazy toString enabled, matching pre-Grails 8 behavior"
         def state = new InterceptorState("Book", Object, 1L)
 
+        expect: "the proxy implementation is invoked so the entity's own toString runs"
+        GroovyProxyInterceptorLogic.handleUninitialized(state, "toString", [] as Object[]) ==
+                GroovyProxyInterceptorLogic.INVOKE_IMPLEMENTATION
+    }
+
+    def "handleUninitialized answers toString without initialization when lazy toString is enabled"() {
+        given:
+        def state = new InterceptorState("Book", Object, 1L, true)
+
         expect:
         GroovyProxyInterceptorLogic.handleUninitialized(state, "toString", [] as Object[]) == "Book:1"
     }
 
+    def "handleUninitialized delegates toString with arguments even when lazy toString is enabled"() {
+        given:
+        def state = new InterceptorState("Book", Object, 1L, true)
+
+        expect:
+        GroovyProxyInterceptorLogic.handleUninitialized(state, "toString", ["arg"] as Object[]) ==
+                GroovyProxyInterceptorLogic.INVOKE_IMPLEMENTATION
+    }
+
     def "handleUninitialized handles dirty checking methods"() {
         given:
         def state = new InterceptorState("TestEntity", Object, 1L)
diff --git a/grails-data-hibernate5/docs/src/docs/asciidoc/configuration/configurationReference.adoc b/grails-data-hibernate5/docs/src/docs/asciidoc/configuration/configurationReference.adoc
index 2eed1a2245..b6083621f4 100644
--- a/grails-data-hibernate5/docs/src/docs/asciidoc/configuration/configurationReference.adoc
+++ b/grails-data-hibernate5/docs/src/docs/asciidoc/configuration/configurationReference.adoc
@@ -60,8 +60,27 @@ name,description,default value
 `hibernate.cache.use_query_cache`, Enables the query cache, `false`
 `hibernate.configLocations`, Location of additional Hibernate XML configuration files
 `hibernate.packagesToScan`, Specify packages to search for autodetection of your entity classes in the classpath
+`hibernate.grails.proxy.lazy_to_string`, Whether `toString()` on an uninitialized proxy avoids initializing it (see Proxies and toString()), `false`
 |===
 
 In addition, any additional settings that start with `hibernate.` are passed through to Hibernate, so if there is any specific feature of Hibernate you wish to configure that is possible.
 
+
+==== Proxies and toString()
+
+
+Grails proxies answer identifier access (`id`, `getId()`, `ident()`) and `metaClass` access without initializing the proxy. By default, calling `toString()` on an uninitialized proxy initializes it and delegates to the domain class's own `toString()` implementation.
+
+If you prefer `toString()` to also avoid initialization — for example to keep log statements from triggering database access — enable lazy `toString()` in `application.yml`:
+
+[source,yaml]
+----
+hibernate:
+    grails:
+        proxy:
+            lazy_to_string: true
+----
+
+With this setting enabled, `toString()` on an uninitialized proxy returns `entityName:id` (for example `com.example.Author:1`) without initializing it. Once the proxy has been initialized, `toString()` always delegates to the domain class's implementation.
+
 TIP: The above table covers the common configuration options. For all configuration refer to properties of the link:../api/org/grails/orm/hibernate/connections/HibernateConnectionSourceSettings.html[HibernateConnectionSourceSettings] class.
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/proxy/ByteBuddyGroovyInterceptor.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/proxy/ByteBuddyGroovyInterceptor.java
index 8d913d745f..bab4ac1fd5 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/proxy/ByteBuddyGroovyInterceptor.java
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/proxy/ByteBuddyGroovyInterceptor.java
@@ -37,6 +37,8 @@ public class ByteBuddyGroovyInterceptor extends ByteBuddyInterceptor {
 
     protected final Method getIdentifierMethod;
 
+    private final boolean lazyToString;
+
     public ByteBuddyGroovyInterceptor(
             String entityName,
             Class<?> persistentClass,
@@ -46,7 +48,8 @@ public class ByteBuddyGroovyInterceptor extends ByteBuddyInterceptor {
             Method setIdentifierMethod,
             CompositeType componentIdType,
             SharedSessionContractImplementor session,
-            boolean overridesEquals) {
+            boolean overridesEquals,
+            boolean lazyToString) {
         super(
                 entityName,
                 persistentClass,
@@ -58,6 +61,7 @@ public class ByteBuddyGroovyInterceptor extends ByteBuddyInterceptor {
                 session,
                 overridesEquals);
         this.getIdentifierMethod = getIdentifierMethod;
+        this.lazyToString = lazyToString;
     }
 
     @Override
@@ -72,7 +76,7 @@ public class ByteBuddyGroovyInterceptor extends ByteBuddyInterceptor {
         }
 
         GroovyProxyInterceptorLogic.InterceptorState state = new GroovyProxyInterceptorLogic.InterceptorState(
-                getEntityName(), getPersistentClass(), getIdentifier());
+                getEntityName(), getPersistentClass(), getIdentifier(), lazyToString);
 
         if (isUninitialized()) {
             Object result = GroovyProxyInterceptorLogic.handleUninitialized(state, methodName, args);
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/proxy/ByteBuddyGroovyProxyFactory.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/proxy/ByteBuddyGroovyProxyFactory.java
index 77b30fd78c..0c6d4a7e3c 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/proxy/ByteBuddyGroovyProxyFactory.java
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/proxy/ByteBuddyGroovyProxyFactory.java
@@ -52,10 +52,16 @@ public class ByteBuddyGroovyProxyFactory extends ByteBuddyProxyFactory {
     private transient CompositeType componentIdType;
     private boolean overridesEquals;
     private Class<?> proxyClass;
+    private final boolean lazyToString;
 
     public ByteBuddyGroovyProxyFactory(ByteBuddyProxyHelper byteBuddyProxyHelper) {
+        this(byteBuddyProxyHelper, false);
+    }
+
+    public ByteBuddyGroovyProxyFactory(ByteBuddyProxyHelper byteBuddyProxyHelper, boolean lazyToString) {
         super(byteBuddyProxyHelper);
         this.byteBuddyProxyHelper = byteBuddyProxyHelper;
+        this.lazyToString = lazyToString;
     }
 
     @Override
@@ -95,7 +101,8 @@ public class ByteBuddyGroovyProxyFactory extends ByteBuddyProxyFactory {
                     setIdentifierMethod,
                     componentIdType,
                     session,
-                    overridesEquals);
+                    overridesEquals,
+                    lazyToString);
 
             // 1. Create the instance
             final HibernateProxy hibernateProxy =
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/proxy/GrailsProxyFactoryFactory.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/proxy/GrailsProxyFactoryFactory.java
index 2d85f7e20d..371c18a6bf 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/proxy/GrailsProxyFactoryFactory.java
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/proxy/GrailsProxyFactoryFactory.java
@@ -44,7 +44,13 @@ public class GrailsProxyFactoryFactory implements ProxyFactoryFactory, java.io.S
 
     @Override
     public ProxyFactory buildProxyFactory(SessionFactoryImplementor sessionFactory) {
-        return new ByteBuddyGroovyProxyFactory(grailsBytecodeProvider.getProxyHelper());
+        return new ByteBuddyGroovyProxyFactory(grailsBytecodeProvider.getProxyHelper(),
+                isLazyToString(sessionFactory));
+    }
+
+    private static boolean isLazyToString(SessionFactoryImplementor sessionFactory) {
+        Object value = sessionFactory.getProperties().get(GroovyProxyInterceptorLogic.PROPERTY_LAZY_TO_STRING);
+        return value != null && Boolean.parseBoolean(value.toString());
     }
 
     @Override
diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/proxy/GroovyProxyInterceptorLogic.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/proxy/GroovyProxyInterceptorLogic.java
index af593e0c85..46354f007b 100644
--- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/proxy/GroovyProxyInterceptorLogic.java
+++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/proxy/GroovyProxyInterceptorLogic.java
@@ -37,6 +37,14 @@ public class GroovyProxyInterceptorLogic {
 
     public static final Object INVOKE_IMPLEMENTATION = new Object();
 
+    /**
+     * Setting that controls {@code toString()} on an uninitialized proxy. When {@code false}
+     * (the default, matching Grails 7 and earlier), {@code toString()} initializes the proxy
+     * and delegates to the entity's own implementation. When {@code true}, the proxy answers
+     * {@code entityName:id} without initializing.
+     */
+    public static final String PROPERTY_LAZY_TO_STRING = "hibernate.grails.proxy.lazy_to_string";
+
     private static final String GET_META_CLASS = "getMetaClass";
     private static final String SET_META_CLASS = "setMetaClass";
     private static final String META_CLASS_PROPERTY = "metaClass";
@@ -66,7 +74,7 @@ public class GroovyProxyInterceptorLogic {
         if ((IS_DIRTY.equals(methodName) || HAS_CHANGED.equals(methodName)) && (args == null || args.length == 0)) {
             return false;
         }
-        if (TO_STRING.equals(methodName) && (args == null || args.length == 0)) {
+        if (state.lazyToString() && TO_STRING.equals(methodName) && (args == null || args.length == 0)) {
             return state.entityName() + ":" + state.identifier();
         }
         return INVOKE_IMPLEMENTATION;
@@ -121,5 +129,10 @@ public class GroovyProxyInterceptorLogic {
         return null;
     }
 
-    public record InterceptorState(String entityName, Class<?> persistentClass, Object identifier) {}
+    public record InterceptorState(String entityName, Class<?> persistentClass, Object identifier, boolean lazyToString) {
+
+        public InterceptorState(String entityName, Class<?> persistentClass, Object identifier) {
+            this(entityName, persistentClass, identifier, false);
+        }
+    }
 }
diff --git a/grails-data-hibernate7/core/src/main/resources/META-INF/spring-configuration-metadata.json b/grails-data-hibernate7/core/src/main/resources/META-INF/spring-configuration-metadata.json
index 7a51260417..3f7709ecd5 100644
--- a/grails-data-hibernate7/core/src/main/resources/META-INF/spring-configuration-metadata.json
+++ b/grails-data-hibernate7/core/src/main/resources/META-INF/spring-configuration-metadata.json
@@ -3,6 +3,10 @@
         {
             "name": "hibernate.cache",
             "description": "Hibernate"
+        },
+        {
+            "name": "hibernate.grails.proxy",
+            "description": "Grails entity proxy behavior"
         }
     ],
     "properties": [
@@ -23,6 +27,12 @@
             "type": "java.lang.Boolean",
             "description": "Whether to enable Hibernate's query cache.",
             "defaultValue": false
+        },
+        {
+            "name": "hibernate.grails.proxy.lazy_to_string",
+            "type": "java.lang.Boolean",
+            "description": "Whether toString() on an uninitialized entity proxy returns entityName:id without initializing it. When false (the default, matching Grails 7 and earlier), toString() initializes the proxy and delegates to the domain class's own implementation.",
+            "defaultValue": false
         }
     ]
 }
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/proxy/ByteBuddyProxySpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/proxy/ByteBuddyProxySpec.groovy
index cb2d6605b8..4f0ac5f394 100644
--- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/proxy/ByteBuddyProxySpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/proxy/ByteBuddyProxySpec.groovy
@@ -151,6 +151,25 @@ needs the identifier must use id/ident()/getIdentifier() instead of unwrapping"
         !proxyHandler.isInitialized(team.club)
     }
 
+    void "toString initializes the proxy and delegates to the entity implementation by default"() {
+        when:"load proxy"
+        Team team = createATeam()
+        def clubId = team.club.id
+        manager.session.clear()
+        Club club = Club.load(clubId)
+
+        then:"the proxy starts uninitialized"
+        proxyHandler.isProxy(club)
+        !proxyHandler.isInitialized(club)
+
+        when:"toString is called"
+        String value = club.toString()
+
+        then:"the entity's own toString runs, which requires initialization"
+        value == "DOOM Club"
+        proxyHandler.isInitialized(club)
+    }
+
     void "isDirty should not intialize the association proxy"() {
         when:"load instance"
         Team team = createATeam()
diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/proxy/LazyToStringByteBuddyProxySpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/proxy/LazyToStringByteBuddyProxySpec.groovy
new file mode 100644
index 0000000000..8aa0455232
--- /dev/null
+++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/proxy/LazyToStringByteBuddyProxySpec.groovy
@@ -0,0 +1,65 @@
+/*
+ *  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.proxy
+
+import grails.gorm.tests.entities.Club
+import grails.gorm.tests.entities.Team
+import org.apache.grails.data.hibernate7.core.GrailsDataHibernate7TckManager
+import org.apache.grails.data.testing.tck.base.GrailsDataTckSpec
+import org.grails.orm.hibernate.proxy.HibernateProxyHandler
+import spock.lang.Shared
+
+/**
+ * Verifies proxy toString behavior when the {@code hibernate.grails.proxy.lazy_to_string}
+ * setting is enabled: toString on an uninitialized proxy answers {@code entityName:id}
+ * without initializing it, while an initialized proxy delegates to the entity implementation.
+ */
+class LazyToStringByteBuddyProxySpec extends GrailsDataTckSpec<GrailsDataHibernate7TckManager> {
+
+    void setupSpec() {
+        // nested ConfigObject path: only nested config reaches the arbitrary hibernate settings
+        // map, producing the flattened hibernate.grails.proxy.lazy_to_string property
+        manager.grailsConfig.hibernate.grails.proxy.lazy_to_string = 'true'
+        manager.registerDomainClasses(Team, Club)
+    }
+
+    @Shared
+    HibernateProxyHandler proxyHandler = new HibernateProxyHandler()
+
+    void "toString does not initialize the proxy when lazy toString is enabled"() {
+        when: "a proxy is loaded"
+        Club c = new Club(name: "DOOM Club").save(failOnError: true, flush: true)
+        def id = c.id
+        manager.session.clear()
+        Club club = Club.load(id)
+
+        then: "toString answers entityName:id without initializing the proxy"
+        proxyHandler.isProxy(club)
+        !proxyHandler.isInitialized(club)
+        club.toString() == "${Club.name}:${id}"
+        !proxyHandler.isInitialized(club)
+
+        when: "the proxy is initialized by accessing a regular property"
+        club.name
+
+        then: "toString delegates to the entity implementation"
+        proxyHandler.isInitialized(club)
+        club.toString() == "DOOM Club"
+    }
+}
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/proxy/ByteBuddyGroovyInterceptorSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/proxy/ByteBuddyGroovyInterceptorSpec.groovy
index 9282abcf6b..a57906724f 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/proxy/ByteBuddyGroovyInterceptorSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/proxy/ByteBuddyGroovyInterceptorSpec.groovy
@@ -57,16 +57,19 @@ class ByteBuddyGroovyInterceptorSpec extends HibernateGormDatastoreSpec {
         !Hibernate.isInitialized(proxy)
     }
 
-    void "toString() on uninitialized proxy returns entityName:id without initialization"() {
+    void "toString() on uninitialized proxy initializes it and delegates to the entity by default"() {
         given:
         def proxy = manager.hibernateSession.getReference(Location, savedId)
 
+        expect:
+        !Hibernate.isInitialized(proxy)
+
         when:
         String s = proxy.toString()
 
-        then:
-        !Hibernate.isInitialized(proxy)
-        s.contains(savedId.toString())
+        then: "matching pre-Grails 8 behavior, toString initializes the proxy"
+        Hibernate.isInitialized(proxy)
+        s != null
     }
 
     void "isDirty() on uninitialized proxy returns false without initialization"() {
diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/proxy/GroovyProxyInterceptorLogicSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/proxy/GroovyProxyInterceptorLogicSpec.groovy
index 7f2982ecd1..4dc81bef55 100644
--- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/proxy/GroovyProxyInterceptorLogicSpec.groovy
+++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/proxy/GroovyProxyInterceptorLogicSpec.groovy
@@ -60,14 +60,32 @@ class GroovyProxyInterceptorLogicSpec extends Specification {
         "ident"        | [] as Object[]
     }
 
-    def "handleUninitialized handles toString"() {
-        given:
+    def "handleUninitialized delegates toString to the implementation by default"() {
+        given: "state without lazy toString enabled, matching pre-Grails 8 behavior"
         def state = new InterceptorState("Book", Object, 1L)
 
+        expect: "the proxy implementation is invoked so the entity's own toString runs"
+        GroovyProxyInterceptorLogic.handleUninitialized(state, "toString", [] as Object[]) ==
+                GroovyProxyInterceptorLogic.INVOKE_IMPLEMENTATION
+    }
+
+    def "handleUninitialized answers toString without initialization when lazy toString is enabled"() {
+        given:
+        def state = new InterceptorState("Book", Object, 1L, true)
+
         expect:
         GroovyProxyInterceptorLogic.handleUninitialized(state, "toString", [] as Object[]) == "Book:1"
     }
 
+    def "handleUninitialized delegates toString with arguments even when lazy toString is enabled"() {
+        given:
+        def state = new InterceptorState("Book", Object, 1L, true)
+
+        expect:
+        GroovyProxyInterceptorLogic.handleUninitialized(state, "toString", ["arg"] as Object[]) ==
+                GroovyProxyInterceptorLogic.INVOKE_IMPLEMENTATION
+    }
+
     def "handleUninitialized handles dirty checking methods"() {
         given:
         def state = new InterceptorState("TestEntity", Object, 1L)
diff --git a/grails-data-hibernate7/docs/src/docs/asciidoc/configuration/configurationReference.adoc b/grails-data-hibernate7/docs/src/docs/asciidoc/configuration/configurationReference.adoc
index 2eed1a2245..b6083621f4 100644
--- a/grails-data-hibernate7/docs/src/docs/asciidoc/configuration/configurationReference.adoc
+++ b/grails-data-hibernate7/docs/src/docs/asciidoc/configuration/configurationReference.adoc
@@ -60,8 +60,27 @@ name,description,default value
 `hibernate.cache.use_query_cache`, Enables the query cache, `false`
 `hibernate.configLocations`, Location of additional Hibernate XML configuration files
 `hibernate.packagesToScan`, Specify packages to search for autodetection of your entity classes in the classpath
+`hibernate.grails.proxy.lazy_to_string`, Whether `toString()` on an uninitialized proxy avoids initializing it (see Proxies and toString()), `false`
 |===
 
 In addition, any additional settings that start with `hibernate.` are passed through to Hibernate, so if there is any specific feature of Hibernate you wish to configure that is possible.
 
+
+==== Proxies and toString()
+
+
+Grails proxies answer identifier access (`id`, `getId()`, `ident()`) and `metaClass` access without initializing the proxy. By default, calling `toString()` on an uninitialized proxy initializes it and delegates to the domain class's own `toString()` implementation.
+
+If you prefer `toString()` to also avoid initialization — for example to keep log statements from triggering database access — enable lazy `toString()` in `application.yml`:
+
+[source,yaml]
+----
+hibernate:
+    grails:
+        proxy:
+            lazy_to_string: true
+----
+
+With this setting enabled, `toString()` on an uninitialized proxy returns `entityName:id` (for example `com.example.Author:1`) without initializing it. Once the proxy has been initialized, `toString()` always delegates to the domain class's implementation.
+
 TIP: The above table covers the common configuration options. For all configuration refer to properties of the link:../api/org/grails/orm/hibernate/connections/HibernateConnectionSourceSettings.html[HibernateConnectionSourceSettings] class.
diff --git a/grails-test-examples/hibernate5/grails-hibernate-groovy-proxy/src/test/groovy/example/ProxySpec.groovy b/grails-test-examples/hibernate5/grails-hibernate-groovy-proxy/src/test/groovy/example/ProxySpec.groovy
index ed9d28de1a..eec7ee7770 100644
--- a/grails-test-examples/hibernate5/grails-hibernate-groovy-proxy/src/test/groovy/example/ProxySpec.groovy
+++ b/grails-test-examples/hibernate5/grails-hibernate-groovy-proxy/src/test/groovy/example/ProxySpec.groovy
@@ -51,9 +51,6 @@ class ProxySpec extends HibernateSpec {
         proxy.getId() == 1
         proxy["id"] == 1
         !Hibernate.isInitialized(proxy)
-        // gorms trait implements in the class so no way to tell
-        // proxy.toString() == "Customer : 1 (proxy)"
-        // !Hibernate.isInitialized(proxy)
     }
 
 }
diff --git a/grails-test-examples/hibernate7/grails-hibernate-groovy-proxy/src/test/groovy/example/ProxySpec.groovy b/grails-test-examples/hibernate7/grails-hibernate-groovy-proxy/src/test/groovy/example/ProxySpec.groovy
index 2371da556e..2280673895 100644
--- a/grails-test-examples/hibernate7/grails-hibernate-groovy-proxy/src/test/groovy/example/ProxySpec.groovy
+++ b/grails-test-examples/hibernate7/grails-hibernate-groovy-proxy/src/test/groovy/example/ProxySpec.groovy
@@ -54,9 +54,6 @@ class ProxySpec extends HibernateSpec {
         proxy.getId() == 1
         proxy["id"] == 1
         !Hibernate.isInitialized(proxy)
-        // gorms trait implements in the class so no way to tell
-        // proxy.toString() == "Customer : 1 (proxy)"
-        // !Hibernate.isInitialized(proxy)
     }
 
 }