-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
StatefulPersistenceContext.java
2040 lines (1779 loc) · 66.9 KB
/
StatefulPersistenceContext.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.engine.internal;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentMap;
import org.hibernate.AssertionFailure;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.MappingException;
import org.hibernate.NonUniqueObjectException;
import org.hibernate.PersistentObjectException;
import org.hibernate.TransientObjectException;
import org.hibernate.action.spi.AfterTransactionCompletionProcess;
import org.hibernate.bytecode.enhance.spi.interceptor.LazyAttributeLoader;
import org.hibernate.cache.spi.access.NaturalIdRegionAccessStrategy;
import org.hibernate.cache.spi.access.SoftLock;
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.loading.internal.LoadContexts;
import org.hibernate.engine.spi.AssociationKey;
import org.hibernate.engine.spi.BatchFetchQueue;
import org.hibernate.engine.spi.CachedNaturalIdValueSource;
import org.hibernate.engine.spi.CollectionEntry;
import org.hibernate.engine.spi.CollectionKey;
import org.hibernate.engine.spi.EntityEntry;
import org.hibernate.engine.spi.EntityKey;
import org.hibernate.engine.spi.EntityUniqueKey;
import org.hibernate.engine.spi.ManagedEntity;
import org.hibernate.engine.spi.PersistenceContext;
import org.hibernate.engine.spi.PersistentAttributeInterceptable;
import org.hibernate.engine.spi.PersistentAttributeInterceptor;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.engine.spi.Status;
import org.hibernate.event.spi.EventSource;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.collections.ConcurrentReferenceHashMap;
import org.hibernate.internal.util.collections.IdentityMap;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.proxy.LazyInitializer;
import org.hibernate.type.CollectionType;
import org.jboss.logging.Logger;
/**
* A <strong>stateful</strong> implementation of the {@link PersistenceContext} contract meaning that we maintain this
* state throughout the life of the persistence context.
* <p/>
* IMPL NOTE: There is meant to be a one-to-one correspondence between a {@link org.hibernate.internal.SessionImpl}
* and a PersistentContext. Event listeners and other Session collaborators then use the PersistentContext to drive
* their processing.
*
* @author Steve Ebersole
*/
public class StatefulPersistenceContext implements PersistenceContext {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(
CoreMessageLogger.class,
StatefulPersistenceContext.class.getName()
);
private static final boolean TRACE_ENABLED = LOG.isTraceEnabled();
private static final int INIT_COLL_SIZE = 8;
private SessionImplementor session;
// Loaded entity instances, by EntityKey
private Map<EntityKey, Object> entitiesByKey;
// Loaded entity instances, by EntityUniqueKey
private Map<EntityUniqueKey, Object> entitiesByUniqueKey;
private EntityEntryContext entityEntryContext;
// private Map<Object,EntityEntry> entityEntries;
// Entity proxies, by EntityKey
private ConcurrentMap<EntityKey, Object> proxiesByKey;
// Snapshots of current database state for entities
// that have *not* been loaded
private Map<EntityKey, Object> entitySnapshotsByKey;
// Identity map of array holder ArrayHolder instances, by the array instance
private Map<Object, PersistentCollection> arrayHolders;
// Identity map of CollectionEntry instances, by the collection wrapper
private IdentityMap<PersistentCollection, CollectionEntry> collectionEntries;
// Collection wrappers, by the CollectionKey
private Map<CollectionKey, PersistentCollection> collectionsByKey;
// Set of EntityKeys of deleted objects
private HashSet<EntityKey> nullifiableEntityKeys;
// properties that we have tried to load, and not found in the database
private HashSet<AssociationKey> nullAssociations;
// A list of collection wrappers that were instantiating during result set
// processing, that we will need to initialize at the end of the query
private List<PersistentCollection> nonlazyCollections;
// A container for collections we load up when the owning entity is not
// yet loaded ... for now, this is purely transient!
private Map<CollectionKey,PersistentCollection> unownedCollections;
// Parent entities cache by their child for cascading
// May be empty or not contains all relation
private Map<Object,Object> parentsByChild;
private int cascading;
private int loadCounter;
private int removeOrphanBeforeUpdatesCounter;
private boolean flushing;
private boolean defaultReadOnly;
private boolean hasNonReadOnlyEntities;
private LoadContexts loadContexts;
private BatchFetchQueue batchFetchQueue;
/**
* Constructs a PersistentContext, bound to the given session.
*
* @param session The session "owning" this context.
*/
public StatefulPersistenceContext(SessionImplementor session) {
this.session = session;
entitiesByKey = new HashMap<EntityKey, Object>( INIT_COLL_SIZE );
entitiesByUniqueKey = new HashMap<EntityUniqueKey, Object>( INIT_COLL_SIZE );
//noinspection unchecked
proxiesByKey = new ConcurrentReferenceHashMap<EntityKey, Object>( INIT_COLL_SIZE, .75f, 1, ConcurrentReferenceHashMap.ReferenceType.STRONG, ConcurrentReferenceHashMap.ReferenceType.WEAK, null );
entitySnapshotsByKey = new HashMap<EntityKey, Object>( INIT_COLL_SIZE );
entityEntryContext = new EntityEntryContext();
// entityEntries = IdentityMap.instantiateSequenced( INIT_COLL_SIZE );
collectionEntries = IdentityMap.instantiateSequenced( INIT_COLL_SIZE );
parentsByChild = new IdentityHashMap<Object,Object>( INIT_COLL_SIZE );
collectionsByKey = new HashMap<CollectionKey, PersistentCollection>( INIT_COLL_SIZE );
arrayHolders = new IdentityHashMap<Object, PersistentCollection>( INIT_COLL_SIZE );
nullifiableEntityKeys = new HashSet<EntityKey>();
initTransientState();
}
private void initTransientState() {
nullAssociations = new HashSet<AssociationKey>( INIT_COLL_SIZE );
nonlazyCollections = new ArrayList<PersistentCollection>( INIT_COLL_SIZE );
}
@Override
public boolean isStateless() {
return false;
}
@Override
public SessionImplementor getSession() {
return session;
}
@Override
public LoadContexts getLoadContexts() {
if ( loadContexts == null ) {
loadContexts = new LoadContexts( this );
}
return loadContexts;
}
@Override
public void addUnownedCollection(CollectionKey key, PersistentCollection collection) {
if (unownedCollections==null) {
unownedCollections = new HashMap<CollectionKey,PersistentCollection>(INIT_COLL_SIZE);
}
unownedCollections.put( key, collection );
}
@Override
public PersistentCollection useUnownedCollection(CollectionKey key) {
return ( unownedCollections == null ) ? null : unownedCollections.remove( key );
}
@Override
public BatchFetchQueue getBatchFetchQueue() {
if (batchFetchQueue==null) {
batchFetchQueue = new BatchFetchQueue(this);
}
return batchFetchQueue;
}
@Override
public void clear() {
for ( Object o : proxiesByKey.values() ) {
if ( o == null ) {
//entry may be GCd
continue;
}
((HibernateProxy) o).getHibernateLazyInitializer().unsetSession();
}
for ( Entry<Object, EntityEntry> objectEntityEntryEntry : entityEntryContext.reentrantSafeEntityEntries() ) {
// todo : I dont think this need be reentrant safe
if ( objectEntityEntryEntry.getKey() instanceof PersistentAttributeInterceptable ) {
final PersistentAttributeInterceptor interceptor = ( (PersistentAttributeInterceptable) objectEntityEntryEntry.getKey() ).$$_hibernate_getInterceptor();
if ( interceptor instanceof LazyAttributeLoader ) {
( (LazyAttributeLoader) interceptor ).unsetSession();
}
}
}
for ( Map.Entry<PersistentCollection, CollectionEntry> aCollectionEntryArray : IdentityMap.concurrentEntries( collectionEntries ) ) {
aCollectionEntryArray.getKey().unsetSession( getSession() );
}
arrayHolders.clear();
entitiesByKey.clear();
entitiesByUniqueKey.clear();
entityEntryContext.clear();
// entityEntries.clear();
parentsByChild.clear();
entitySnapshotsByKey.clear();
collectionsByKey.clear();
collectionEntries.clear();
if ( unownedCollections != null ) {
unownedCollections.clear();
}
proxiesByKey.clear();
nullifiableEntityKeys.clear();
if ( batchFetchQueue != null ) {
batchFetchQueue.clear();
}
// defaultReadOnly is unaffected by clear()
hasNonReadOnlyEntities = false;
if ( loadContexts != null ) {
loadContexts.cleanup();
}
naturalIdXrefDelegate.clear();
}
@Override
public boolean isDefaultReadOnly() {
return defaultReadOnly;
}
@Override
public void setDefaultReadOnly(boolean defaultReadOnly) {
this.defaultReadOnly = defaultReadOnly;
}
@Override
public boolean hasNonReadOnlyEntities() {
return hasNonReadOnlyEntities;
}
@Override
public void setEntryStatus(EntityEntry entry, Status status) {
entry.setStatus( status );
setHasNonReadOnlyEnties( status );
}
private void setHasNonReadOnlyEnties(Status status) {
if ( status==Status.DELETED || status==Status.MANAGED || status==Status.SAVING ) {
hasNonReadOnlyEntities = true;
}
}
@Override
public void afterTransactionCompletion() {
cleanUpInsertedKeysAfterTransaction();
entityEntryContext.downgradeLocks();
// // Downgrade locks
// for ( EntityEntry o : entityEntries.values() ) {
// o.setLockMode( LockMode.NONE );
// }
}
/**
* Get the current state of the entity as known to the underlying
* database, or null if there is no corresponding row
* <p/>
* {@inheritDoc}
*/
@Override
public Object[] getDatabaseSnapshot(Serializable id, EntityPersister persister) throws HibernateException {
final EntityKey key = session.generateEntityKey( id, persister );
final Object cached = entitySnapshotsByKey.get( key );
if ( cached != null ) {
return cached == NO_ROW ? null : (Object[]) cached;
}
else {
final Object[] snapshot = persister.getDatabaseSnapshot( id, session );
entitySnapshotsByKey.put( key, snapshot == null ? NO_ROW : snapshot );
return snapshot;
}
}
@Override
public Object[] getNaturalIdSnapshot(Serializable id, EntityPersister persister) throws HibernateException {
if ( !persister.hasNaturalIdentifier() ) {
return null;
}
persister = locateProperPersister( persister );
// let's first see if it is part of the natural id cache...
final Object[] cachedValue = naturalIdHelper.findCachedNaturalId( persister, id );
if ( cachedValue != null ) {
return cachedValue;
}
// check to see if the natural id is mutable/immutable
if ( persister.getEntityMetamodel().hasImmutableNaturalId() ) {
// an immutable natural-id is not retrieved during a normal database-snapshot operation...
final Object[] dbValue = persister.getNaturalIdentifierSnapshot( id, session );
naturalIdHelper.cacheNaturalIdCrossReferenceFromLoad(
persister,
id,
dbValue
);
return dbValue;
}
else {
// for a mutable natural there is a likelihood that the the information will already be
// snapshot-cached.
final int[] props = persister.getNaturalIdentifierProperties();
final Object[] entitySnapshot = getDatabaseSnapshot( id, persister );
if ( entitySnapshot == NO_ROW || entitySnapshot == null ) {
return null;
}
final Object[] naturalIdSnapshotSubSet = new Object[ props.length ];
for ( int i = 0; i < props.length; i++ ) {
naturalIdSnapshotSubSet[i] = entitySnapshot[ props[i] ];
}
naturalIdHelper.cacheNaturalIdCrossReferenceFromLoad(
persister,
id,
naturalIdSnapshotSubSet
);
return naturalIdSnapshotSubSet;
}
}
private EntityPersister locateProperPersister(EntityPersister persister) {
return session.getFactory().getEntityPersister( persister.getRootEntityName() );
}
@Override
public Object[] getCachedDatabaseSnapshot(EntityKey key) {
final Object snapshot = entitySnapshotsByKey.get( key );
if ( snapshot == NO_ROW ) {
throw new IllegalStateException(
"persistence context reported no row snapshot for "
+ MessageHelper.infoString( key.getEntityName(), key.getIdentifier() )
);
}
return (Object[]) snapshot;
}
@Override
public void addEntity(EntityKey key, Object entity) {
entitiesByKey.put( key, entity );
getBatchFetchQueue().removeBatchLoadableEntityKey( key );
}
@Override
public Object getEntity(EntityKey key) {
return entitiesByKey.get( key );
}
@Override
public boolean containsEntity(EntityKey key) {
return entitiesByKey.containsKey( key );
}
@Override
public Object removeEntity(EntityKey key) {
final Object entity = entitiesByKey.remove( key );
final Iterator itr = entitiesByUniqueKey.values().iterator();
while ( itr.hasNext() ) {
if ( itr.next() == entity ) {
itr.remove();
}
}
// Clear all parent cache
parentsByChild.clear();
entitySnapshotsByKey.remove( key );
nullifiableEntityKeys.remove( key );
getBatchFetchQueue().removeBatchLoadableEntityKey( key );
getBatchFetchQueue().removeSubselect( key );
return entity;
}
@Override
public Object getEntity(EntityUniqueKey euk) {
return entitiesByUniqueKey.get( euk );
}
@Override
public void addEntity(EntityUniqueKey euk, Object entity) {
entitiesByUniqueKey.put( euk, entity );
}
@Override
public EntityEntry getEntry(Object entity) {
return entityEntryContext.getEntityEntry( entity );
}
@Override
public EntityEntry removeEntry(Object entity) {
return entityEntryContext.removeEntityEntry( entity );
}
@Override
public boolean isEntryFor(Object entity) {
return entityEntryContext.hasEntityEntry( entity );
}
@Override
public CollectionEntry getCollectionEntry(PersistentCollection coll) {
return collectionEntries.get( coll );
}
@Override
public EntityEntry addEntity(
final Object entity,
final Status status,
final Object[] loadedState,
final EntityKey entityKey,
final Object version,
final LockMode lockMode,
final boolean existsInDatabase,
final EntityPersister persister,
final boolean disableVersionIncrement,
boolean lazyPropertiesAreUnfetched) {
addEntity( entityKey, entity );
return addEntry(
entity,
status,
loadedState,
null,
entityKey.getIdentifier(),
version,
lockMode,
existsInDatabase,
persister,
disableVersionIncrement,
lazyPropertiesAreUnfetched
);
}
@Override
public EntityEntry addEntry(
final Object entity,
final Status status,
final Object[] loadedState,
final Object rowId,
final Serializable id,
final Object version,
final LockMode lockMode,
final boolean existsInDatabase,
final EntityPersister persister,
final boolean disableVersionIncrement,
boolean lazyPropertiesAreUnfetched) {
final EntityEntry e;
/*
IMPORTANT!!!
The following instanceof checks and castings are intentional.
DO NOT REFACTOR to make calls through the EntityEntryFactory interface, which would result
in polymorphic call sites which will severely impact performance.
When a virtual method is called via an interface the JVM needs to resolve which concrete
implementation to call. This takes CPU cycles and is a performance penalty. It also prevents method
in-ling which further degrades performance. Casting to an implementation and making a direct method call
removes the virtual call, and allows the methods to be in-lined. In this critical code path, it has a very
large impact on performance to make virtual method calls.
*/
if (persister.getEntityEntryFactory() instanceof MutableEntityEntryFactory) {
//noinspection RedundantCast
e = ( (MutableEntityEntryFactory) persister.getEntityEntryFactory() ).createEntityEntry(
status,
loadedState,
rowId,
id,
version,
lockMode,
existsInDatabase,
persister,
disableVersionIncrement,
lazyPropertiesAreUnfetched,
this
);
}
else {
//noinspection RedundantCast
e = ( (ImmutableEntityEntryFactory) persister.getEntityEntryFactory() ).createEntityEntry(
status,
loadedState,
rowId,
id,
version,
lockMode,
existsInDatabase,
persister,
disableVersionIncrement,
lazyPropertiesAreUnfetched,
this
);
}
entityEntryContext.addEntityEntry( entity, e );
setHasNonReadOnlyEnties( status );
return e;
}
public EntityEntry addReferenceEntry(
final Object entity,
final Status status) {
((ManagedEntity)entity).$$_hibernate_getEntityEntry().setStatus( status );
entityEntryContext.addEntityEntry( entity, ((ManagedEntity)entity).$$_hibernate_getEntityEntry() );
setHasNonReadOnlyEnties( status );
return ((ManagedEntity)entity).$$_hibernate_getEntityEntry();
}
@Override
public boolean containsCollection(PersistentCollection collection) {
return collectionEntries.containsKey( collection );
}
@Override
public boolean containsProxy(Object entity) {
return proxiesByKey.containsValue( entity );
}
@Override
public boolean reassociateIfUninitializedProxy(Object value) throws MappingException {
if ( !Hibernate.isInitialized( value ) ) {
final HibernateProxy proxy = (HibernateProxy) value;
final LazyInitializer li = proxy.getHibernateLazyInitializer();
reassociateProxy( li, proxy );
return true;
}
else {
return false;
}
}
@Override
public void reassociateProxy(Object value, Serializable id) throws MappingException {
if ( value instanceof HibernateProxy ) {
LOG.debugf( "Setting proxy identifier: %s", id );
final HibernateProxy proxy = (HibernateProxy) value;
final LazyInitializer li = proxy.getHibernateLazyInitializer();
li.setIdentifier( id );
reassociateProxy( li, proxy );
}
}
/**
* Associate a proxy that was instantiated by another session with this session
*
* @param li The proxy initializer.
* @param proxy The proxy to reassociate.
*/
private void reassociateProxy(LazyInitializer li, HibernateProxy proxy) {
if ( li.getSession() != this.getSession() ) {
final EntityPersister persister = session.getFactory().getEntityPersister( li.getEntityName() );
final EntityKey key = session.generateEntityKey( li.getIdentifier(), persister );
// any earlier proxy takes precedence
proxiesByKey.putIfAbsent( key, proxy );
proxy.getHibernateLazyInitializer().setSession( session );
}
}
@Override
public Object unproxy(Object maybeProxy) throws HibernateException {
if ( maybeProxy instanceof HibernateProxy ) {
final HibernateProxy proxy = (HibernateProxy) maybeProxy;
final LazyInitializer li = proxy.getHibernateLazyInitializer();
if ( li.isUninitialized() ) {
throw new PersistentObjectException(
"object was an uninitialized proxy for " + li.getEntityName()
);
}
//unwrap the object and return
return li.getImplementation();
}
else {
return maybeProxy;
}
}
@Override
public Object unproxyAndReassociate(Object maybeProxy) throws HibernateException {
if ( maybeProxy instanceof HibernateProxy ) {
final HibernateProxy proxy = (HibernateProxy) maybeProxy;
final LazyInitializer li = proxy.getHibernateLazyInitializer();
reassociateProxy( li, proxy );
//initialize + unwrap the object and return it
return li.getImplementation();
}
else {
return maybeProxy;
}
}
@Override
public void checkUniqueness(EntityKey key, Object object) throws HibernateException {
final Object entity = getEntity( key );
if ( entity == object ) {
throw new AssertionFailure( "object already associated, but no entry was found" );
}
if ( entity != null ) {
throw new NonUniqueObjectException( key.getIdentifier(), key.getEntityName() );
}
}
@Override
@SuppressWarnings("unchecked")
public Object narrowProxy(Object proxy, EntityPersister persister, EntityKey key, Object object)
throws HibernateException {
final Class concreteProxyClass = persister.getConcreteProxyClass();
final boolean alreadyNarrow = concreteProxyClass.isInstance( proxy );
if ( !alreadyNarrow ) {
LOG.narrowingProxy( concreteProxyClass );
// If an impl is passed, there is really no point in creating a proxy.
// It would just be extra processing. Just return the impl
if ( object != null ) {
proxiesByKey.remove( key );
return object;
}
// Similarly, if the original HibernateProxy is initialized, there
// is again no point in creating a proxy. Just return the impl
final HibernateProxy originalHibernateProxy = (HibernateProxy) proxy;
if ( !originalHibernateProxy.getHibernateLazyInitializer().isUninitialized() ) {
final Object impl = originalHibernateProxy.getHibernateLazyInitializer().getImplementation();
// can we return it?
if ( concreteProxyClass.isInstance( impl ) ) {
proxiesByKey.remove( key );
return impl;
}
}
// Otherwise, create the narrowed proxy
final HibernateProxy narrowedProxy = (HibernateProxy) persister.createProxy( key.getIdentifier(), session );
// set the read-only/modifiable mode in the new proxy to what it was in the original proxy
final boolean readOnlyOrig = originalHibernateProxy.getHibernateLazyInitializer().isReadOnly();
narrowedProxy.getHibernateLazyInitializer().setReadOnly( readOnlyOrig );
return narrowedProxy;
}
else {
if ( object != null ) {
final LazyInitializer li = ( (HibernateProxy) proxy ).getHibernateLazyInitializer();
li.setImplementation( object );
}
return proxy;
}
}
@Override
public Object proxyFor(EntityPersister persister, EntityKey key, Object impl) throws HibernateException {
if ( !persister.hasProxy() ) {
return impl;
}
final Object proxy = proxiesByKey.get( key );
return ( proxy != null ) ? narrowProxy( proxy, persister, key, impl ) : impl;
}
@Override
public Object proxyFor(Object impl) throws HibernateException {
final EntityEntry e = getEntry( impl );
if ( e == null ) {
return impl;
}
return proxyFor( e.getPersister(), e.getEntityKey(), impl );
}
@Override
public Object getCollectionOwner(Serializable key, CollectionPersister collectionPersister) throws MappingException {
// todo : we really just need to add a split in the notions of:
// 1) collection key
// 2) collection owner key
// these 2 are not always the same. Same is true in the case of ToOne associations with property-ref...
final EntityPersister ownerPersister = collectionPersister.getOwnerEntityPersister();
if ( ownerPersister.getIdentifierType().getReturnedClass().isInstance( key ) ) {
return getEntity( session.generateEntityKey( key, collectionPersister.getOwnerEntityPersister() ) );
}
// we have a property-ref type mapping for the collection key. But that could show up a few ways here...
//
// 1) The incoming key could be the entity itself...
if ( ownerPersister.isInstance( key ) ) {
final Serializable owenerId = ownerPersister.getIdentifier( key, session );
if ( owenerId == null ) {
return null;
}
return getEntity( session.generateEntityKey( owenerId, ownerPersister ) );
}
final CollectionType collectionType = collectionPersister.getCollectionType();
// 2) The incoming key is most likely the collection key which we need to resolve to the owner key
// find the corresponding owner instance
// a) try by EntityUniqueKey
if ( collectionType.getLHSPropertyName() != null ) {
final Object owner = getEntity(
new EntityUniqueKey(
ownerPersister.getEntityName(),
collectionType.getLHSPropertyName(),
key,
collectionPersister.getKeyType(),
ownerPersister.getEntityMode(),
session.getFactory()
)
);
if ( owner != null ) {
return owner;
}
// b) try by EntityKey, which means we need to resolve owner-key -> collection-key
// IMPL NOTE : yes if we get here this impl is very non-performant, but PersistenceContext
// was never designed to handle this case; adding that capability for real means splitting
// the notions of:
// 1) collection key
// 2) collection owner key
// these 2 are not always the same (same is true in the case of ToOne associations with
// property-ref). That would require changes to (at least) CollectionEntry and quite
// probably changes to how the sql for collection initializers are generated
//
// We could also possibly see if the referenced property is a natural id since we already have caching
// in place of natural id snapshots. BUt really its better to just do it the right way ^^ if we start
// going that route
final Serializable ownerId = ownerPersister.getIdByUniqueKey( key, collectionType.getLHSPropertyName(), session );
return getEntity( session.generateEntityKey( ownerId, ownerPersister ) );
}
// as a last resort this is what the old code did...
return getEntity( session.generateEntityKey( key, collectionPersister.getOwnerEntityPersister() ) );
}
@Override
public Object getLoadedCollectionOwnerOrNull(PersistentCollection collection) {
final CollectionEntry ce = getCollectionEntry( collection );
if ( ce.getLoadedPersister() == null ) {
return null;
}
Object loadedOwner = null;
// TODO: an alternative is to check if the owner has changed; if it hasn't then
// return collection.getOwner()
final Serializable entityId = getLoadedCollectionOwnerIdOrNull( ce );
if ( entityId != null ) {
loadedOwner = getCollectionOwner( entityId, ce.getLoadedPersister() );
}
return loadedOwner;
}
@Override
public Serializable getLoadedCollectionOwnerIdOrNull(PersistentCollection collection) {
return getLoadedCollectionOwnerIdOrNull( getCollectionEntry( collection ) );
}
/**
* Get the ID for the entity that owned this persistent collection when it was loaded
*
* @param ce The collection entry
* @return the owner ID if available from the collection's loaded key; otherwise, returns null
*/
private Serializable getLoadedCollectionOwnerIdOrNull(CollectionEntry ce) {
if ( ce == null || ce.getLoadedKey() == null || ce.getLoadedPersister() == null ) {
return null;
}
// TODO: an alternative is to check if the owner has changed; if it hasn't then
// get the ID from collection.getOwner()
return ce.getLoadedPersister().getCollectionType().getIdOfOwnerOrNull( ce.getLoadedKey(), session );
}
@Override
public void addUninitializedCollection(CollectionPersister persister, PersistentCollection collection, Serializable id) {
final CollectionEntry ce = new CollectionEntry( collection, persister, id, flushing );
addCollection( collection, ce, id );
if ( persister.getBatchSize() > 1 ) {
getBatchFetchQueue().addBatchLoadableCollection( collection, ce );
}
}
@Override
public void addUninitializedDetachedCollection(CollectionPersister persister, PersistentCollection collection) {
final CollectionEntry ce = new CollectionEntry( persister, collection.getKey() );
addCollection( collection, ce, collection.getKey() );
if ( persister.getBatchSize() > 1 ) {
getBatchFetchQueue().addBatchLoadableCollection( collection, ce );
}
}
@Override
public void addNewCollection(CollectionPersister persister, PersistentCollection collection)
throws HibernateException {
addCollection( collection, persister );
}
/**
* Add an collection to the cache, with a given collection entry.
*
* @param coll The collection for which we are adding an entry.
* @param entry The entry representing the collection.
* @param key The key of the collection's entry.
*/
private void addCollection(PersistentCollection coll, CollectionEntry entry, Serializable key) {
collectionEntries.put( coll, entry );
final CollectionKey collectionKey = new CollectionKey( entry.getLoadedPersister(), key );
final PersistentCollection old = collectionsByKey.put( collectionKey, coll );
if ( old != null ) {
if ( old == coll ) {
throw new AssertionFailure( "bug adding collection twice" );
}
// or should it actually throw an exception?
old.unsetSession( session );
collectionEntries.remove( old );
// watch out for a case where old is still referenced
// somewhere in the object graph! (which is a user error)
}
}
/**
* Add a collection to the cache, creating a new collection entry for it
*
* @param collection The collection for which we are adding an entry.
* @param persister The collection persister
*/
private void addCollection(PersistentCollection collection, CollectionPersister persister) {
final CollectionEntry ce = new CollectionEntry( persister, collection );
collectionEntries.put( collection, ce );
}
@Override
public void addInitializedDetachedCollection(CollectionPersister collectionPersister, PersistentCollection collection)
throws HibernateException {
if ( collection.isUnreferenced() ) {
//treat it just like a new collection
addCollection( collection, collectionPersister );
}
else {
final CollectionEntry ce = new CollectionEntry( collection, session.getFactory() );
addCollection( collection, ce, collection.getKey() );
}
}
@Override
public CollectionEntry addInitializedCollection(CollectionPersister persister, PersistentCollection collection, Serializable id)
throws HibernateException {
final CollectionEntry ce = new CollectionEntry( collection, persister, id, flushing );
ce.postInitialize( collection );
addCollection( collection, ce, id );
return ce;
}
@Override
public PersistentCollection getCollection(CollectionKey collectionKey) {
return collectionsByKey.get( collectionKey );
}
@Override
public void addNonLazyCollection(PersistentCollection collection) {
nonlazyCollections.add( collection );
}
@Override
public void initializeNonLazyCollections() throws HibernateException {
if ( loadCounter == 0 ) {
if ( TRACE_ENABLED ) {
LOG.trace( "Initializing non-lazy collections" );
}
//do this work only at the very highest level of the load
//don't let this method be called recursively
loadCounter++;
try {
int size;
while ( ( size = nonlazyCollections.size() ) > 0 ) {
//note that each iteration of the loop may add new elements
nonlazyCollections.remove( size - 1 ).forceInitialization();
}
}
finally {
loadCounter--;
clearNullProperties();
}
}
}
@Override
public PersistentCollection getCollectionHolder(Object array) {
return arrayHolders.get( array );
}
@Override
public void addCollectionHolder(PersistentCollection holder) {
//TODO:refactor + make this method private
arrayHolders.put( holder.getValue(), holder );
}
@Override
public PersistentCollection removeCollectionHolder(Object array) {
return arrayHolders.remove( array );
}
@Override
public Serializable getSnapshot(PersistentCollection coll) {
return getCollectionEntry( coll ).getSnapshot();
}
@Override
public CollectionEntry getCollectionEntryOrNull(Object collection) {
PersistentCollection coll;
if ( collection instanceof PersistentCollection ) {
coll = (PersistentCollection) collection;
//if (collection==null) throw new TransientObjectException("Collection was not yet persistent");
}
else {
coll = getCollectionHolder( collection );
if ( coll == null ) {
//it might be an unwrapped collection reference!
//try to find a wrapper (slowish)
final Iterator<PersistentCollection> wrappers = collectionEntries.keyIterator();
while ( wrappers.hasNext() ) {
final PersistentCollection pc = wrappers.next();
if ( pc.isWrapper( collection ) ) {
coll = pc;
break;
}
}
}
}
return (coll == null) ? null : getCollectionEntry( coll );
}
@Override
public Object getProxy(EntityKey key) {
return proxiesByKey.get( key );
}
@Override
public void addProxy(EntityKey key, Object proxy) {
proxiesByKey.put( key, proxy );
}
@Override
public Object removeProxy(EntityKey key) {
if ( batchFetchQueue != null ) {
batchFetchQueue.removeBatchLoadableEntityKey( key );
batchFetchQueue.removeSubselect( key );
}
return proxiesByKey.remove( key );
}
@Override
public HashSet getNullifiableEntityKeys() {
return nullifiableEntityKeys;
}