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/09 13:14:03 UTC

(grails-core) branch fix/multi-tenant-get-by-id updated: Return held instances of the current tenant from lookups by id

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

jdaugherty pushed a commit to branch fix/multi-tenant-get-by-id
in repository https://gitbox.apache.org/repos/asf/grails-core.git


The following commit(s) were added to refs/heads/fix/multi-tenant-get-by-id by this push:
     new 34c879e803 Return held instances of the current tenant from lookups by id
34c879e803 is described below

commit 34c879e803f516497809555d8cee157d3fbdbbde
Author: James Daugherty <jd...@jdresources.net>
AuthorDate: Fri Oct 9 09:13:51 2026 -0400

    Return held instances of the current tenant from lookups by id
    
    A lookup by id of a multi-tenant entity now returns the instance the
    session already holds when it belongs to the current tenant, including
    one saved but not yet flushed, and queries the others without flushing
    the session. GORM for MongoDB does not flush before a query inside a
    transaction, so an instance saved earlier in that transaction was not
    found, and outside one every lookup by id flushed the whole session.
    load returns the held instance again instead of a proxy.
    
    Tenants.withoutId is detected from the tenant bound to the thread, so a
    tenant resolver that resolves DEFAULT no longer lifts the restriction
    for lookups by id while queries still apply it. getAll without ids
    returns an empty list without needing a current tenant.
---
 .../MongoLookupByIdMultiTenancySpec.groovy         |  99 +++++++++++++
 .../partitioned/PartitionedLookupByIdSpec.groovy   | 114 ++++++++++++++
 .../groovy/grails/gorm/multitenancy/Tenants.groovy |  12 ++
 .../org/grails/datastore/gorm/GormStaticApi.groovy | 164 ++++++++++++++++-----
 .../src/en/guide/upgrading/upgrading60x.adoc       |   6 +-
 5 files changed, 353 insertions(+), 42 deletions(-)

diff --git a/grails-data-mongodb/core/src/test/groovy/org/grails/datastore/gorm/mongo/multitenancy/MongoLookupByIdMultiTenancySpec.groovy b/grails-data-mongodb/core/src/test/groovy/org/grails/datastore/gorm/mongo/multitenancy/MongoLookupByIdMultiTenancySpec.groovy
index 6c132095c8..a4aa0b4967 100644
--- a/grails-data-mongodb/core/src/test/groovy/org/grails/datastore/gorm/mongo/multitenancy/MongoLookupByIdMultiTenancySpec.groovy
+++ b/grails-data-mongodb/core/src/test/groovy/org/grails/datastore/gorm/mongo/multitenancy/MongoLookupByIdMultiTenancySpec.groovy
@@ -30,6 +30,7 @@ import grails.gorm.multitenancy.Tenants
 import grails.mongodb.MongoEntity
 import grails.persistence.Entity
 import org.apache.grails.testing.mongo.AutoStartedMongoSpec
+import org.grails.datastore.mapping.core.connections.ConnectionSource
 import org.grails.datastore.mapping.mongo.MongoDatastore
 import org.grails.datastore.mapping.mongo.config.MongoSettings
 import org.grails.datastore.mapping.multitenancy.exceptions.TenantNotFoundException
@@ -155,6 +156,96 @@ class MongoLookupByIdMultiTenancySpec extends AutoStartedMongoSpec {
         thrown(DataIntegrityViolationException)
     }
 
+    void 'a lookup by id inside a transaction finds an instance saved earlier in that transaction'() {
+        when: 'instances are saved inside a transaction, which GORM for MongoDB does not flush before a query'
+        Map<String, Object> lookups = Memo.withNewSession {
+            Memo.withTransaction {
+                Memo saved = new Memo(title: 'New').save()
+                Memo unvalidated = new Memo(title: 'Unvalidated').save(validate: false)
+                List<Memo> all = Memo.getAll(saved.id, unvalidated.id)
+                [unvalidatedTenantId: unvalidated.tenantId,
+                 get                : Memo.get(saved.id).is(saved),
+                 exists             : Memo.exists(saved.id),
+                 getAll             : all[0].is(saved) && all[1].is(unvalidated),
+                 load               : Memo.load(saved.id).is(saved),
+                 getUnvalidated     : Memo.get(unvalidated.id).is(unvalidated)]
+            }
+        }
+
+        then: 'the session returns them, including one that gets its tenant id only when it is inserted'
+        lookups == [unvalidatedTenantId: null, get: true, exists: true, getAll: true, load: true, getUnvalidated: true]
+
+        and: 'the transaction inserts both for the current tenant'
+        Memo.withNewSession { Memo.countByTitleInList(['New', 'Unvalidated']) } == 2
+        Memo.withTenant('other') { Memo.withNewSession { Memo.countByTitleInList(['New', 'Unvalidated']) } } == 0
+    }
+
+    void 'a lookup by id does not flush the session'() {
+        when: 'an instance is changed and the session is used for lookups by id before it is flushed'
+        String stored = Memo.withNewSession {
+            Memo own = Memo.get(ownId)
+            own.title = 'Changed'
+            own.save()
+            Memo.get(otherId)
+            Memo.exists(new ObjectId())
+            Memo.getAll(otherId, new ObjectId())
+            Memo.withNewSession { Memo.get(ownId).title }
+        }
+
+        then: 'the change has not been written'
+        stored == 'Own'
+    }
+
+    void 'an instance of another tenant that the session already holds is not returned'() {
+        when: 'the session holds an instance of another tenant'
+        Map<String, Object> lookups = Memo.withNewSession {
+            Memo other = Memo.withTenant('other') { Memo.get(otherId) }
+            [held  : other?.title,
+             get   : Memo.get(otherId),
+             read  : Memo.read(otherId),
+             exists: Memo.exists(otherId),
+             getAll: Memo.getAll(otherId, ownId)*.title]
+        }
+
+        then: 'a lookup by id for the current tenant does not find it'
+        lookups == [held: 'Other', get: null, read: null, exists: false, getAll: [null, 'Own']]
+
+        when: 'a proxy for it is used'
+        Memo.withNewSession {
+            Memo.withTenant('other') { Memo.get(otherId) }
+            Memo.load(otherId).title
+        }
+
+        then:
+        thrown(DataIntegrityViolationException)
+    }
+
+    void 'load returns the instance the session already holds for the current tenant'() {
+        expect:
+        Memo.withNewSession {
+            Memo own = Memo.get(ownId)
+            Memo.load(ownId).is(own)
+        }
+    }
+
+    void 'a tenant resolver that resolves the default connection source does not lift the restriction'() {
+        given:
+        System.setProperty(SystemPropertyTenantResolver.PROPERTY_NAME, ConnectionSource.DEFAULT)
+
+        expect: 'a lookup by id agrees with a query'
+        Memo.withNewSession { Memo.findById(ownId) } == null
+        Memo.withNewSession { Memo.get(ownId) } == null
+        Memo.withNewSession { Memo.read(otherId) } == null
+        !Memo.withNewSession { Memo.exists(ownId) }
+        Memo.withNewSession { Memo.getAll(ownId, otherId) } == [null, null]
+
+        when:
+        Memo.withNewSession { Memo.load(ownId).title }
+
+        then:
+        thrown(DataIntegrityViolationException)
+    }
+
     void 'a lookup by id inside withTenant is restricted to that tenant'() {
         expect:
         Memo.withTenant('other') { Memo.withNewSession { Memo.get(otherId)?.title } } == 'Other'
@@ -188,6 +279,14 @@ class MongoLookupByIdMultiTenancySpec extends AutoStartedMongoSpec {
         thrown(TenantNotFoundException)
     }
 
+    void 'getAll without ids needs no current tenant'() {
+        given:
+        System.clearProperty(SystemPropertyTenantResolver.PROPERTY_NAME)
+
+        expect:
+        Memo.withNewSession { Memo.getAll([]) } == []
+    }
+
     private static ObjectId saveMemo(String tenantId, String title) {
         Memo.withTenant(tenantId) {
             Memo.withNewSession { new Memo(title: title).save(flush: true).id }
diff --git a/grails-datamapping-core-test/src/test/groovy/grails/gorm/multitenancy/partitioned/PartitionedLookupByIdSpec.groovy b/grails-datamapping-core-test/src/test/groovy/grails/gorm/multitenancy/partitioned/PartitionedLookupByIdSpec.groovy
index 8cae6e6cc1..f6725181fe 100644
--- a/grails-datamapping-core-test/src/test/groovy/grails/gorm/multitenancy/partitioned/PartitionedLookupByIdSpec.groovy
+++ b/grails-datamapping-core-test/src/test/groovy/grails/gorm/multitenancy/partitioned/PartitionedLookupByIdSpec.groovy
@@ -30,6 +30,7 @@ import grails.gorm.annotation.Entity
 import grails.gorm.multitenancy.Tenants
 import org.grails.datastore.gorm.proxy.GroovyProxyFactory
 import org.grails.datastore.mapping.config.Settings
+import org.grails.datastore.mapping.core.connections.ConnectionSource
 import org.grails.datastore.mapping.multitenancy.MultiTenancySettings
 import org.grails.datastore.mapping.multitenancy.exceptions.TenantNotFoundException
 import org.grails.datastore.mapping.multitenancy.resolvers.SystemPropertyTenantResolver
@@ -165,6 +166,96 @@ class PartitionedLookupByIdSpec extends Specification {
         thrown(DataIntegrityViolationException)
     }
 
+    void 'a lookup by id inside a transaction finds an instance saved earlier in that transaction'() {
+        when: 'instances are saved inside a transaction and looked up by id before it commits'
+        Map<String, Object> lookups = Note.withNewSession {
+            Note.withTransaction {
+                Note saved = new Note(title: 'New').save()
+                Note unvalidated = new Note(title: 'Unvalidated').save(validate: false)
+                List<Note> all = Note.getAll(saved.id, unvalidated.id)
+                [unvalidatedTenantId: unvalidated.tenantId,
+                 get                : Note.get(saved.id).is(saved),
+                 exists             : Note.exists(saved.id),
+                 getAll             : all[0].is(saved) && all[1].is(unvalidated),
+                 load               : Note.load(saved.id).is(saved),
+                 getUnvalidated     : Note.get(unvalidated.id).is(unvalidated)]
+            }
+        }
+
+        then: 'the session returns them, including one that gets its tenant id only when it is inserted'
+        lookups == [unvalidatedTenantId: null, get: true, exists: true, getAll: true, load: true, getUnvalidated: true]
+
+        and: 'the transaction inserts both for the current tenant'
+        Note.withNewSession { Note.countByTitleInList(['New', 'Unvalidated']) } == 2
+        Note.withTenant('other') { Note.withNewSession { Note.countByTitleInList(['New', 'Unvalidated']) } } == 0
+    }
+
+    void 'a lookup by id does not flush the session'() {
+        when: 'an instance is changed and the session is used for lookups by id before it is flushed'
+        String stored = Note.withNewSession {
+            Note own = Note.get(ownId)
+            own.title = 'Changed'
+            own.save()
+            Note.get(otherId)
+            Note.exists(999L)
+            Note.getAll(otherId, 999L)
+            Note.withNewSession { Note.get(ownId).title }
+        }
+
+        then: 'the change has not been written'
+        stored == 'Own'
+    }
+
+    void 'an instance of another tenant that the session already holds is not returned'() {
+        when: 'the session holds an instance of another tenant'
+        Map<String, Object> lookups = Note.withNewSession {
+            Note other = Note.withTenant('other') { Note.get(otherId) }
+            [held  : other?.title,
+             get   : Note.get(otherId),
+             read  : Note.read(otherId),
+             exists: Note.exists(otherId),
+             getAll: Note.getAll(otherId, ownId)*.title]
+        }
+
+        then: 'a lookup by id for the current tenant does not find it'
+        lookups == [held: 'Other', get: null, read: null, exists: false, getAll: [null, 'Own']]
+
+        when: 'a proxy for it is used'
+        Note.withNewSession {
+            Note.withTenant('other') { Note.get(otherId) }
+            Note.load(otherId).title
+        }
+
+        then:
+        thrown(DataIntegrityViolationException)
+    }
+
+    void 'load returns the instance the session already holds for the current tenant'() {
+        expect: 'an instance saved in the session'
+        Note.withNewSession {
+            Note saved = new Note(title: 'Saved').save(flush: true)
+            Note.load(saved.id).is(saved)
+        }
+    }
+
+    void 'a tenant resolver that resolves the default connection source does not lift the restriction'() {
+        given:
+        System.setProperty(SystemPropertyTenantResolver.PROPERTY_NAME, ConnectionSource.DEFAULT)
+
+        expect: 'a lookup by id agrees with a query'
+        Note.withNewSession { Note.findById(ownId) } == null
+        Note.withNewSession { Note.get(ownId) } == null
+        Note.withNewSession { Note.read(otherId) } == null
+        !Note.withNewSession { Note.exists(ownId) }
+        Note.withNewSession { Note.getAll(ownId, otherId) } == [null, null]
+
+        when:
+        Note.withNewSession { Note.load(ownId).title }
+
+        then:
+        thrown(DataIntegrityViolationException)
+    }
+
     void 'a lookup by id inside withTenant is restricted to that tenant'() {
         expect:
         Note.withTenant('other') { Note.withNewSession { Note.get(otherId)?.title } } == 'Other'
@@ -179,6 +270,21 @@ class PartitionedLookupByIdSpec extends Specification {
         } == ['Own', 'Other']
     }
 
+    void 'Tenants.isWithoutId is true inside withoutId only'() {
+        expect:
+        !Tenants.isWithoutId()
+        Tenants.withoutId(datastore) { Tenants.isWithoutId() }
+        !Tenants.withoutId(datastore) { Note.withTenant('own') { Tenants.isWithoutId() } }
+        !Note.withTenant('own') { Tenants.isWithoutId() }
+
+        when: 'the tenant resolver resolves the default connection source'
+        System.setProperty(SystemPropertyTenantResolver.PROPERTY_NAME, ConnectionSource.DEFAULT)
+
+        then:
+        Tenants.currentId(datastore) == ConnectionSource.DEFAULT
+        !Tenants.isWithoutId()
+    }
+
     void 'a proxy created under a tenant is not restricted to a tenant when it is initialized inside withoutId'() {
         expect:
         Note.withNewSession {
@@ -199,6 +305,14 @@ class PartitionedLookupByIdSpec extends Specification {
         thrown(TenantNotFoundException)
     }
 
+    void 'getAll without ids needs no current tenant'() {
+        given:
+        System.setProperty(SystemPropertyTenantResolver.PROPERTY_NAME, '')
+
+        expect:
+        Note.withNewSession { Note.getAll([]) } == []
+    }
+
     void 'a lookup by id of an entity that is not multi-tenant needs no tenant'() {
         given:
         Long id = Label.withNewSession { new Label(name: 'Shared').save(flush: true).id }
diff --git a/grails-datamapping-core/src/main/groovy/grails/gorm/multitenancy/Tenants.groovy b/grails-datamapping-core/src/main/groovy/grails/gorm/multitenancy/Tenants.groovy
index abbfb17ce9..bd84823536 100644
--- a/grails-datamapping-core/src/main/groovy/grails/gorm/multitenancy/Tenants.groovy
+++ b/grails-datamapping-core/src/main/groovy/grails/gorm/multitenancy/Tenants.groovy
@@ -123,6 +123,18 @@ class Tenants {
         }
     }
 
+    /**
+     * Whether the current thread runs without a tenant id, as it does inside {@link #withoutId(Closure)}. Unlike
+     * {@link #currentId()}, this does not consult the tenant resolver, so a resolver that resolves the name of the
+     * default connection source as the tenant id does not count.
+     *
+     * @return Whether the default connection source is bound to the current thread as the current tenant
+     * @since 7.0.18
+     */
+    static boolean isWithoutId() {
+        ConnectionSource.DEFAULT == CurrentTenant.get()
+    }
+
     /**
      * Execute the given closure without any tenant id. In Multi tenancy mode SINGLE this will execute against the default data source. If multi tenancy mode
      * MULTI this will execute without including the "tenantId" on any query. Use with caution.
diff --git 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
index ae388423da..5e9cdeedf5 100644
--- 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
@@ -23,6 +23,8 @@ import groovy.transform.CompileStatic
 import groovy.transform.TypeCheckingMode
 import org.codehaus.groovy.runtime.InvokerHelper
 
+import jakarta.persistence.FlushModeType
+
 import org.springframework.beans.PropertyAccessorFactory
 import org.springframework.beans.factory.config.AutowireCapableBeanFactory
 import org.springframework.core.convert.ConversionFailedException
@@ -47,11 +49,13 @@ import org.grails.datastore.mapping.core.Datastore
 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.PersistentEntity
 import org.grails.datastore.mapping.model.PersistentProperty
@@ -397,11 +401,12 @@ class GormStaticApi<D> extends AbstractGormApi<D> implements GormAllOperations<D
      * @return A list of identifiers
      */
     List<D> getAll(Serializable... ids) {
-        if (isRetrievedByQuery()) {
-            return retrieveAllByQuery((Collection<Serializable>) ids.flatten(), true)
+        List<Serializable> keys = (List<Serializable>) ids.flatten()
+        if (keys && isRetrievedByQuery()) {
+            return retrieveAllByQuery(keys, true)
         }
         (List<D>) execute({ Session session ->
-            session.retrieveAll(persistentClass, ids.flatten())
+            session.retrieveAll(persistentClass, keys)
         } as SessionCallback)
     }
 
@@ -409,33 +414,29 @@ class GormStaticApi<D> extends AbstractGormApi<D> implements GormAllOperations<D
      * 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)}, where the current id is the default connection source, a lookup
-     * by id is not restricted to a tenant and stays a lookup by key.
+     * {@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
-     * @throws org.grails.datastore.mapping.multitenancy.exceptions.TenantNotFoundException if there is no current tenant
      */
     private boolean isRetrievedByQuery() {
         if (multiTenancyMode != MultiTenancyMode.DISCRIMINATOR
                 || persistentEntity?.isMultiTenant() != true
-                || persistentEntity.identity == null) {
+                || persistentEntity.identity == null
+                || persistentEntity.tenantId == null) {
             return false
         }
-        return !isWithoutTenant()
+        return !Tenants.isWithoutId()
     }
 
     /**
-     * Whether the current id is the default connection source, as it is inside
-     * {@link Tenants#withoutId(groovy.lang.Closure)}.
-     *
-     * @return Whether the current id is the default connection source
+     * @return The current tenant id
      * @throws org.grails.datastore.mapping.multitenancy.exceptions.TenantNotFoundException if there is no current tenant
      */
-    private boolean isWithoutTenant() {
-        Serializable currentId = datastore instanceof MultiTenantCapableDatastore
+    private Serializable currentTenantId() {
+        datastore instanceof MultiTenantCapableDatastore
                 ? Tenants.currentId((MultiTenantCapableDatastore) datastore)
                 : Tenants.currentId(datastore.getClass())
-        return ConnectionSource.DEFAULT.equals(currentId)
     }
 
     /**
@@ -448,43 +449,131 @@ class GormStaticApi<D> extends AbstractGormApi<D> implements GormAllOperations<D
      */
     private List<D> retrieveAllByQuery(Collection<Serializable> ids, boolean strict) {
         (List<D>) execute({ Session session ->
-            List<Serializable> keys = ids.collect { Serializable id -> convertIdentifier(session, id, strict) }
-            List<Serializable> present = keys.findAll { Serializable key -> key != null }
-            Map<Object, Object> found = [:]
-            if (present) {
+            findAllByKeys(session, ids.collect { Serializable id -> convertIdentifier(session, id, strict) })
+        } as SessionCallback)
+    }
+
+    /**
+     * 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.
+     *
+     * @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) {
+        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) {
+            FlushModeType flushMode = session.flushMode
+            session.flushMode = FlushModeType.COMMIT
+            try {
                 Query query = session.createQuery(persistentClass)
-                if (present.size() == 1) {
-                    query.idEq(present[0])
+                if (missing.size() == 1) {
+                    query.idEq(missing.first())
                 }
                 else {
-                    query.in(persistentEntity.identity.name, present)
+                    query.in(persistentEntity.identity.name, missing.toList())
                 }
                 for (Object instance in query.list()) {
                     found.put(persistentEntity.reflector.getIdentifier(instance), instance)
                 }
             }
-            keys.collect { Serializable key -> key == null ? null : found.get(key) }
-        } as SessionCallback)
+            finally {
+                session.flushMode = flushMode
+            }
+        }
+        keys.collect { Serializable key -> key == null ? null : found.get(key) }
     }
 
     /**
-     * Creates 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
+     * 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.
+     *
+     * @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) {
+        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)
+        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 proxy
+     * @return The instance or the proxy
      */
     private D proxyByQuery(Serializable id) {
         (D) 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 retrieveAllByQuery([key], true)[0]
+                return findAllByKeys(session, [key])[0]
             }
         } as SessionCallback)
     }
@@ -1337,9 +1426,9 @@ class GormStaticApi<D> extends AbstractGormApi<D> implements GormAllOperations<D
     }
 
     /**
-     * Queries an instance by id for a proxy created by {@link GormStaticApi#load(Serializable)}. Inside
-     * {@link Tenants#withoutId(groovy.lang.Closure)} the instance is looked up by key instead, as {@code load} looks it
-     * up there.
+     * 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> {
 
@@ -1353,13 +1442,10 @@ class GormStaticApi<D> extends AbstractGormApi<D> implements GormAllOperations<D
 
         @Override
         List<Object> query(Serializable id) {
-            if (api.isWithoutTenant()) {
-                Object instance = session.retrieve(api.persistentClass, id)
-                return instance == null ? [] : [instance]
-            }
-            Query query = session.createQuery(api.persistentClass)
-            query.idEq(id)
-            query.list()
+            Object instance = Tenants.isWithoutId()
+                    ? session.retrieve(api.persistentClass, id)
+                    : api.findAllByKeys(session, [id])[0]
+            instance == null ? [] : [instance]
         }
 
         @Override
diff --git a/grails-doc/src/en/guide/upgrading/upgrading60x.adoc b/grails-doc/src/en/guide/upgrading/upgrading60x.adoc
index daea99ed88..f26ab68618 100644
--- a/grails-doc/src/en/guide/upgrading/upgrading60x.adoc
+++ b/grails-doc/src/en/guide/upgrading/upgrading60x.adoc
@@ -1172,9 +1172,9 @@ with dispatch lets a request reach a controller without its interceptors or rest
 
 ==== 19. Lookups by id are restricted to the current tenant with DISCRIMINATOR multi-tenancy
 
-With `DISCRIMINATOR` multi-tenancy, GORM for MongoDB 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 already restricts `get`, `read`, `exists` and `getAll` to the current tenant and is unchanged.
+With `DISCRIMINATOR` multi-tenancy, GORM for MongoDB 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, but not `load`  [...]
 
 * 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.
+* 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.
-* A lookup by id of a multi-tenant entity runs as a query, so with the `AUTO` flush mode it flushes the session first. With the `COMMIT` flush mode, an instance that has been saved but not flushed is no longer found by `get`.
+* 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.