Skip to content

Commit 72c9839

Browse files
committed
HHH-18008 add Session.getManagedEntities()
1 parent 67f4dde commit 72c9839

File tree

6 files changed

+184
-34
lines changed

6 files changed

+184
-34
lines changed

hibernate-core/src/main/java/org/hibernate/Session.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,12 @@
44
*/
55
package org.hibernate;
66

7+
import java.util.Collection;
78
import java.util.List;
89
import java.util.function.Consumer;
910

1011
import jakarta.persistence.FindOption;
12+
import jakarta.persistence.metamodel.EntityType;
1113
import org.hibernate.graph.RootGraph;
1214
import org.hibernate.jdbc.Work;
1315
import org.hibernate.query.Query;
@@ -1267,6 +1269,40 @@ public interface Session extends SharedSessionContract, EntityManager {
12671269
*/
12681270
LobHelper getLobHelper();
12691271

1272+
/**
1273+
* Obtain the collection of all managed entities which belong to this
1274+
* persistence context.
1275+
*
1276+
* @since 7.0
1277+
*/
1278+
Collection<?> getManagedEntities();
1279+
1280+
/**
1281+
* Obtain a collection of all managed instances of the entity type with the
1282+
* given entity name which belong to this persistence context.
1283+
*
1284+
* @since 7.0
1285+
*/
1286+
Collection<?> getManagedEntities(String entityName);
1287+
1288+
/**
1289+
* Obtain a collection of all managed entities of the given type which belong
1290+
* to this persistence context. This operation is not polymorphic, and does
1291+
* not return instances of subtypes of the given entity type.
1292+
*
1293+
* @since 7.0
1294+
*/
1295+
<E> Collection<E> getManagedEntities(Class<E> entityType);
1296+
1297+
/**
1298+
* Obtain a collection of all managed entities of the given type which belong
1299+
* to this persistence context. This operation is not polymorphic, and does
1300+
* not return instances of subtypes of the given entity type.
1301+
*
1302+
* @since 7.0
1303+
*/
1304+
<E> Collection<E> getManagedEntities(EntityType<E> entityType);
1305+
12701306
/**
12711307
* Obtain a {@link Session} builder with the ability to copy certain
12721308
* information from this session.

hibernate-core/src/main/java/org/hibernate/engine/internal/StatefulPersistenceContext.java

Lines changed: 26 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -72,10 +72,12 @@
7272

7373
import org.checkerframework.checker.nullness.qual.Nullable;
7474

75+
import static java.util.Collections.emptyMap;
7576
import static org.hibernate.engine.internal.ManagedTypeHelper.asHibernateProxy;
7677
import static org.hibernate.engine.internal.ManagedTypeHelper.asManagedEntity;
7778
import static org.hibernate.engine.internal.ManagedTypeHelper.asPersistentAttributeInterceptable;
7879
import static org.hibernate.engine.internal.ManagedTypeHelper.isPersistentAttributeInterceptable;
80+
import static org.hibernate.internal.util.collections.CollectionHelper.mapOfSize;
7981
import static org.hibernate.proxy.HibernateProxy.extractLazyInitializer;
8082

8183
/**
@@ -183,7 +185,7 @@ the following fields are used in all circumstances, and are not worth (or not su
183185

184186
private Map<EntityKey, EntityHolderImpl> getOrInitializeEntitiesByKey() {
185187
if ( entitiesByKey == null ) {
186-
entitiesByKey = CollectionHelper.mapOfSize( INIT_COLL_SIZE );
188+
entitiesByKey = mapOfSize( INIT_COLL_SIZE );
187189
}
188190
return entitiesByKey;
189191
}
@@ -484,17 +486,10 @@ private void processLoadedEntityHolder(
484486
postLoadEvent.setEntity( holder.getEntity() )
485487
.setId( holder.getEntityKey().getIdentifier() )
486488
.setPersister( holder.getDescriptor() );
487-
listenerGroup.fireEventOnEachListener(
488-
postLoadEvent,
489-
PostLoadEventListener::onPostLoad
490-
);
489+
listenerGroup.fireEventOnEachListener( postLoadEvent, PostLoadEventListener::onPostLoad );
491490
}
492491
if ( callback != null ) {
493-
callback.invokeAfterLoadActions(
494-
holder.getEntity(),
495-
holder.getDescriptor(),
496-
getSession()
497-
);
492+
callback.invokeAfterLoadActions( holder.getEntity(), holder.getDescriptor(), getSession() );
498493
}
499494
holder.resetEntityInitialier();
500495
}
@@ -599,7 +594,7 @@ public Object getEntity(EntityUniqueKey euk) {
599594
@Override
600595
public void addEntity(EntityUniqueKey euk, Object entity) {
601596
if ( entitiesByUniqueKey == null ) {
602-
entitiesByUniqueKey = CollectionHelper.mapOfSize( INIT_COLL_SIZE );
597+
entitiesByUniqueKey = mapOfSize( INIT_COLL_SIZE );
603598
}
604599
entitiesByUniqueKey.put( euk, entity );
605600
}
@@ -733,7 +728,8 @@ public EntityEntry addReferenceEntry(
733728

734729
@Override
735730
public boolean containsCollection(PersistentCollection<?> collection) {
736-
return collectionEntries != null && collectionEntries.containsKey( collection.$$_hibernate_getInstanceId(), collection );
731+
return collectionEntries != null
732+
&& collectionEntries.containsKey( collection.$$_hibernate_getInstanceId(), collection );
737733
}
738734

739735
@Override
@@ -818,9 +814,8 @@ public Object unproxy(Object maybeProxy) throws HibernateException {
818814
final LazyInitializer lazyInitializer = extractLazyInitializer( maybeProxy );
819815
if ( lazyInitializer != null ) {
820816
if ( lazyInitializer.isUninitialized() ) {
821-
throw new PersistentObjectException(
822-
"object was an uninitialized proxy for " + lazyInitializer.getEntityName()
823-
);
817+
throw new PersistentObjectException( "object was an uninitialized proxy for "
818+
+ lazyInitializer.getEntityName() );
824819
}
825820
//unwrap the object and return
826821
return lazyInitializer.getImplementation();
@@ -839,10 +834,11 @@ public Object unproxyAndReassociate(final Object maybeProxy) throws HibernateExc
839834
return lazyInitializer.getImplementation();
840835
}
841836
else if ( isPersistentAttributeInterceptable( maybeProxy ) ) {
842-
final PersistentAttributeInterceptable interceptable = asPersistentAttributeInterceptable( maybeProxy );
843-
final PersistentAttributeInterceptor interceptor = interceptable.$$_hibernate_getInterceptor();
844-
if ( interceptor instanceof EnhancementAsProxyLazinessInterceptor ) {
845-
( (EnhancementAsProxyLazinessInterceptor) interceptor ).forceInitialize( maybeProxy, null );
837+
final PersistentAttributeInterceptor interceptor =
838+
asPersistentAttributeInterceptable( maybeProxy )
839+
.$$_hibernate_getInterceptor();
840+
if ( interceptor instanceof EnhancementAsProxyLazinessInterceptor lazinessInterceptor ) {
841+
lazinessInterceptor.forceInitialize( maybeProxy, null );
846842
}
847843
return maybeProxy;
848844
}
@@ -893,7 +889,8 @@ public Object narrowProxy(Object proxy, EntityPersister persister, EntityKey key
893889

894890

895891
// Otherwise, create the narrowed proxy
896-
final HibernateProxy narrowedProxy = asHibernateProxy( persister.createProxy( key.getIdentifier(), session ) );
892+
final HibernateProxy narrowedProxy =
893+
asHibernateProxy( persister.createProxy( key.getIdentifier(), session ) );
897894
// set the read-only/modifiable mode in the new proxy to what it was in the original proxy
898895
narrowedProxy.getHibernateLazyInitializer().setReadOnly( lazyInitializer.isReadOnly() );
899896
return narrowedProxy;
@@ -1309,9 +1306,9 @@ public Object removeProxy(EntityKey key) {
13091306
@Override
13101307
public Map<EntityKey,Object> getEntitiesByKey() {
13111308
if ( entitiesByKey == null ) {
1312-
return Collections.emptyMap();
1309+
return emptyMap();
13131310
}
1314-
final HashMap<EntityKey, Object> result = CollectionHelper.mapOfSize( entitiesByKey.size() );
1311+
final HashMap<EntityKey, Object> result = mapOfSize( entitiesByKey.size() );
13151312
for ( Entry<EntityKey, EntityHolderImpl> entry : entitiesByKey.entrySet() ) {
13161313
if ( entry.getValue().entity != null ) {
13171314
result.put( entry.getKey(), entry.getValue().entity );
@@ -1330,7 +1327,7 @@ public Map<EntityKey, Object> getEntitySnapshotsByKey() {
13301327
@Override
13311328
public Map<EntityKey, Object> getOrInitializeEntitySnapshotsByKey() {
13321329
if ( entitySnapshotsByKey == null ) {
1333-
entitySnapshotsByKey = CollectionHelper.mapOfSize( INIT_COLL_SIZE );
1330+
entitySnapshotsByKey = mapOfSize( INIT_COLL_SIZE );
13341331
}
13351332
return entitySnapshotsByKey;
13361333
}
@@ -1384,11 +1381,6 @@ public int getNumberOfManagedEntities() {
13841381
return entityEntryContext.getNumberOfManagedEntities();
13851382
}
13861383

1387-
// @Override
1388-
// public Map getEntityEntries() {
1389-
// return null;
1390-
// }
1391-
13921384
/**
13931385
* @deprecated We should not expose this directly: the other accessors that have been created as a replacement
13941386
* have better chances of skipping initializing this map, which is a good performance improvement.
@@ -1420,7 +1412,7 @@ public void forEachCollectionEntry(BiConsumer<PersistentCollection<?>, Collectio
14201412

14211413
@Override
14221414
public Map<CollectionKey,PersistentCollection<?>> getCollectionsByKey() {
1423-
return collectionsByKey == null ? Collections.emptyMap() : collectionsByKey;
1415+
return collectionsByKey == null ? emptyMap() : collectionsByKey;
14241416
}
14251417

14261418
@Override
@@ -1997,7 +1989,7 @@ public static StatefulPersistenceContext deserialize(
19971989
LOG.trace( "Starting deserialization of [" + count + "] entitiesByUniqueKey entries" );
19981990
}
19991991
if ( count != 0 ) {
2000-
rtn.entitiesByUniqueKey = CollectionHelper.mapOfSize(Math.max(count, INIT_COLL_SIZE));
1992+
rtn.entitiesByUniqueKey = mapOfSize(Math.max(count, INIT_COLL_SIZE));
20011993
for ( int i = 0; i < count; i++ ) {
20021994
rtn.entitiesByUniqueKey.put( EntityUniqueKey.deserialize( ois, session ), ois.readObject() );
20031995
}
@@ -2007,7 +1999,7 @@ public static StatefulPersistenceContext deserialize(
20071999
if ( traceEnabled ) {
20082000
LOG.trace( "Starting deserialization of [" + count + "] entitySnapshotsByKey entries" );
20092001
}
2010-
rtn.entitySnapshotsByKey = CollectionHelper.mapOfSize(Math.max(count, INIT_COLL_SIZE));
2002+
rtn.entitySnapshotsByKey = mapOfSize(Math.max(count, INIT_COLL_SIZE));
20112003
for ( int i = 0; i < count; i++ ) {
20122004
rtn.entitySnapshotsByKey.put( EntityKey.deserialize( ois, sfi ), ois.readObject() );
20132005
}
@@ -2018,7 +2010,7 @@ public static StatefulPersistenceContext deserialize(
20182010
if ( traceEnabled ) {
20192011
LOG.trace( "Starting deserialization of [" + count + "] entitiesByKey entries" );
20202012
}
2021-
rtn.entitiesByKey = CollectionHelper.mapOfSize(Math.max(count, INIT_COLL_SIZE));
2013+
rtn.entitiesByKey = mapOfSize(Math.max(count, INIT_COLL_SIZE));
20222014
for ( int i = 0; i < count; i++ ) {
20232015
final EntityKey ek = EntityKey.deserialize( ois, sfi );
20242016
final EntityPersister persister = sfi.getMappingMetamodel().getEntityDescriptor( (String) ois.readObject() );
@@ -2048,7 +2040,7 @@ public static StatefulPersistenceContext deserialize(
20482040
if ( traceEnabled ) {
20492041
LOG.trace( "Starting deserialization of [" + count + "] collectionsByKey entries" );
20502042
}
2051-
rtn.collectionsByKey = CollectionHelper.mapOfSize(Math.max(count, INIT_COLL_SIZE));
2043+
rtn.collectionsByKey = mapOfSize(Math.max(count, INIT_COLL_SIZE));
20522044
for ( int i = 0; i < count; i++ ) {
20532045
rtn.collectionsByKey.put(
20542046
CollectionKey.deserialize( ois, session ),
@@ -2230,7 +2222,7 @@ public void clearCollectionsByKey() {
22302222
@Override
22312223
public PersistentCollection<?> addCollectionByKey(CollectionKey collectionKey, PersistentCollection<?> persistentCollection) {
22322224
if ( collectionsByKey == null ) {
2233-
collectionsByKey = CollectionHelper.mapOfSize( INIT_COLL_SIZE );
2225+
collectionsByKey = mapOfSize( INIT_COLL_SIZE );
22342226
}
22352227
return collectionsByKey.put( collectionKey, persistentCollection );
22362228
}

hibernate-core/src/main/java/org/hibernate/engine/spi/SessionDelegatorBaseImpl.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,14 @@
44
*/
55
package org.hibernate.engine.spi;
66

7+
import java.util.Collection;
78
import java.util.List;
89
import java.util.Map;
910
import java.util.Set;
1011
import java.util.TimeZone;
1112
import java.util.UUID;
1213

14+
import jakarta.persistence.metamodel.EntityType;
1315
import org.hibernate.CacheMode;
1416
import org.hibernate.Filter;
1517
import org.hibernate.FlushMode;
@@ -1115,6 +1117,26 @@ public LobHelper getLobHelper() {
11151117
return delegate.getLobHelper();
11161118
}
11171119

1120+
@Override
1121+
public Collection<?> getManagedEntities() {
1122+
return delegate.getManagedEntities();
1123+
}
1124+
1125+
@Override
1126+
public Collection<?> getManagedEntities(String entityName) {
1127+
return delegate.getManagedEntities( entityName );
1128+
}
1129+
1130+
@Override
1131+
public <E> Collection<E> getManagedEntities(Class<E> entityType) {
1132+
return delegate.getManagedEntities( entityType );
1133+
}
1134+
1135+
@Override
1136+
public <E> Collection<E> getManagedEntities(EntityType<E> entityType) {
1137+
return delegate.getManagedEntities( entityType );
1138+
}
1139+
11181140
@Override
11191141
public void addEventListeners(SessionEventListener... listeners) {
11201142
delegate.addEventListeners( listeners );

hibernate-core/src/main/java/org/hibernate/engine/spi/SessionLazyDelegator.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,14 @@
44
*/
55
package org.hibernate.engine.spi;
66

7+
import java.util.Collection;
78
import java.util.List;
89
import java.util.Map;
910
import java.util.function.Supplier;
1011

1112
import jakarta.persistence.CacheRetrieveMode;
1213
import jakarta.persistence.CacheStoreMode;
14+
import jakarta.persistence.metamodel.EntityType;
1315
import org.hibernate.CacheMode;
1416
import org.hibernate.Filter;
1517
import org.hibernate.FlushMode;
@@ -420,6 +422,26 @@ public LobHelper getLobHelper() {
420422
return this.lazySession.get().getLobHelper();
421423
}
422424

425+
@Override
426+
public Collection<?> getManagedEntities() {
427+
return this.lazySession.get().getManagedEntities();
428+
}
429+
430+
@Override
431+
public Collection<?> getManagedEntities(String entityName) {
432+
return this.lazySession.get().getManagedEntities( entityName );
433+
}
434+
435+
@Override
436+
public <E> Collection<E> getManagedEntities(Class<E> entityType) {
437+
return this.lazySession.get().getManagedEntities( entityType );
438+
}
439+
440+
@Override
441+
public <E> Collection<E> getManagedEntities(EntityType<E> entityType) {
442+
return this.lazySession.get().getManagedEntities( entityType );
443+
}
444+
423445
@Override
424446
public SharedSessionBuilder sessionWithOptions() {
425447
return this.lazySession.get().sessionWithOptions();

hibernate-core/src/main/java/org/hibernate/internal/SessionImpl.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import java.sql.Connection;
1717
import java.sql.NClob;
1818
import java.sql.SQLException;
19+
import java.util.Collection;
1920
import java.util.HashMap;
2021
import java.util.List;
2122
import java.util.Map;
@@ -24,6 +25,7 @@
2425

2526
import jakarta.persistence.PessimisticLockScope;
2627
import jakarta.persistence.Timeout;
28+
import jakarta.persistence.metamodel.EntityType;
2729
import org.hibernate.BatchSize;
2830
import org.hibernate.CacheMode;
2931
import org.hibernate.ConnectionAcquisitionMode;
@@ -64,6 +66,7 @@
6466
import org.hibernate.engine.spi.ActionQueue.TransactionCompletionProcesses;
6567
import org.hibernate.engine.spi.EffectiveEntityGraph;
6668
import org.hibernate.engine.spi.EntityEntry;
69+
import org.hibernate.engine.spi.EntityHolder;
6770
import org.hibernate.engine.spi.EntityKey;
6871
import org.hibernate.engine.spi.LoadQueryInfluencers;
6972
import org.hibernate.engine.spi.PersistenceContext;
@@ -106,6 +109,7 @@
106109
import org.hibernate.event.spi.ReplicateEvent;
107110
import org.hibernate.event.spi.ReplicateEventListener;
108111
import org.hibernate.loader.internal.CacheLoadHelper;
112+
import org.hibernate.metamodel.model.domain.EntityDomainType;
109113
import org.hibernate.metamodel.model.domain.ManagedDomainType;
110114
import org.hibernate.resource.transaction.spi.TransactionObserver;
111115
import org.hibernate.event.monitor.spi.EventMonitor;
@@ -2983,6 +2987,38 @@ public Metamodel getMetamodel() {
29832987
return getFactory().getJpaMetamodel();
29842988
}
29852989

2990+
@Override
2991+
public Collection<?> getManagedEntities() {
2992+
return persistenceContext.getEntityHoldersByKey()
2993+
.values().stream().map( EntityHolder::getManagedObject )
2994+
.toList();
2995+
}
2996+
2997+
@Override
2998+
public Collection<?> getManagedEntities(String entityName) {
2999+
return persistenceContext.getEntityHoldersByKey().entrySet().stream()
3000+
.filter( entry -> entry.getKey().getEntityName().equals( entityName ) )
3001+
.map( entry -> entry.getValue().getManagedObject() )
3002+
.toList();
3003+
}
3004+
3005+
@Override
3006+
public <E> Collection<E> getManagedEntities(Class<E> entityType) {
3007+
return persistenceContext.getEntityHoldersByKey().entrySet().stream()
3008+
.filter( entry -> entry.getKey().getPersister().getMappedClass().equals( entityType ) )
3009+
.map( entry -> (E) entry.getValue().getManagedObject() )
3010+
.toList();
3011+
}
3012+
3013+
@Override
3014+
public <E> Collection<E> getManagedEntities(EntityType<E> entityType) {
3015+
final String entityName = ( (EntityDomainType<E>) entityType ).getHibernateEntityName();
3016+
return persistenceContext.getEntityHoldersByKey().entrySet().stream()
3017+
.filter( entry -> entry.getKey().getEntityName().equals( entityName ) )
3018+
.map( entry -> (E) entry.getValue().getManagedObject() )
3019+
.toList();
3020+
}
3021+
29863022
/**
29873023
* Used by JDK serialization...
29883024
*

0 commit comments

Comments
 (0)