/
Loader.java
2745 lines (2417 loc) · 84.7 KB
/
Loader.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
*
* Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by
* third-party contributors as indicated by either @author tags or express
* copyright attribution statements applied by the authors. All
* third-party contributions are distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.loader;
import java.io.Serializable;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jboss.logging.Logger;
import org.hibernate.AssertionFailure;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.LockOptions;
import org.hibernate.QueryException;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.StaleObjectStateException;
import org.hibernate.WrongClassException;
import org.hibernate.cache.spi.FilterKey;
import org.hibernate.cache.spi.QueryCache;
import org.hibernate.cache.spi.QueryKey;
import org.hibernate.cache.spi.entry.CacheEntry;
import org.hibernate.cache.spi.entry.ReferenceCacheEntryImpl;
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.pagination.LimitHandler;
import org.hibernate.dialect.pagination.LimitHelper;
import org.hibernate.dialect.pagination.NoopLimitHandler;
import org.hibernate.engine.internal.CacheHelper;
import org.hibernate.engine.internal.TwoPhaseLoad;
import org.hibernate.engine.jdbc.ColumnNameCache;
import org.hibernate.engine.spi.EntityEntry;
import org.hibernate.engine.spi.EntityKey;
import org.hibernate.engine.spi.EntityUniqueKey;
import org.hibernate.engine.spi.PersistenceContext;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.RowSelection;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.engine.spi.SubselectFetch;
import org.hibernate.engine.spi.TypedValue;
import org.hibernate.event.spi.EventSource;
import org.hibernate.event.spi.PostLoadEvent;
import org.hibernate.event.spi.PreLoadEvent;
import org.hibernate.hql.internal.HolderInstantiator;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.FetchingScrollableResultsImpl;
import org.hibernate.internal.ScrollableResultsImpl;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.collections.CollectionHelper;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.persister.entity.Loadable;
import org.hibernate.persister.entity.UniqueKeyLoadable;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.transform.CacheableResultTransformer;
import org.hibernate.transform.ResultTransformer;
import org.hibernate.type.AssociationType;
import org.hibernate.type.EntityType;
import org.hibernate.type.Type;
import org.hibernate.type.VersionType;
/**
* Abstract superclass of object loading (and querying) strategies. This class implements
* useful common functionality that concrete loaders delegate to. It is not intended that this
* functionality would be directly accessed by client code. (Hence, all methods of this class
* are declared <tt>protected</tt> or <tt>private</tt>.) This class relies heavily upon the
* <tt>Loadable</tt> interface, which is the contract between this class and
* <tt>EntityPersister</tt>s that may be loaded by it.<br>
* <br>
* The present implementation is able to load any number of columns of entities and at most
* one collection role per query.
*
* @author Gavin King
* @see org.hibernate.persister.entity.Loadable
*/
public abstract class Loader {
protected static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, Loader.class.getName());
protected static final boolean DEBUG_ENABLED = LOG.isDebugEnabled();
private final SessionFactoryImplementor factory;
private volatile ColumnNameCache columnNameCache;
private final boolean referenceCachingEnabled;
public Loader(SessionFactoryImplementor factory) {
this.factory = factory;
this.referenceCachingEnabled = factory.getSettings().isDirectReferenceCacheEntriesEnabled();
}
/**
* The SQL query string to be called; implemented by all subclasses
*
* @return The sql command this loader should use to get its {@link ResultSet}.
*/
public abstract String getSQLString();
/**
* An array of persisters of entity classes contained in each row of results;
* implemented by all subclasses
*
* @return The entity persisters.
*/
protected abstract Loadable[] getEntityPersisters();
/**
* An array indicating whether the entities have eager property fetching
* enabled.
*
* @return Eager property fetching indicators.
*/
protected boolean[] getEntityEagerPropertyFetches() {
return null;
}
/**
* An array of indexes of the entity that owns a one-to-one association
* to the entity at the given index (-1 if there is no "owner"). The
* indexes contained here are relative to the result of
* {@link #getEntityPersisters}.
*
* @return The owner indicators (see discussion above).
*/
protected int[] getOwners() {
return null;
}
/**
* An array of the owner types corresponding to the {@link #getOwners()}
* returns. Indices indicating no owner would be null here.
*
* @return The types for the owners.
*/
protected EntityType[] getOwnerAssociationTypes() {
return null;
}
/**
* An (optional) persister for a collection to be initialized; only
* collection loaders return a non-null value
*/
protected CollectionPersister[] getCollectionPersisters() {
return null;
}
/**
* Get the index of the entity that owns the collection, or -1
* if there is no owner in the query results (ie. in the case of a
* collection initializer) or no collection.
*/
protected int[] getCollectionOwners() {
return null;
}
protected int[][] getCompositeKeyManyToOneTargetIndices() {
return null;
}
/**
* What lock options does this load entities with?
*
* @param lockOptions a collection of lock options specified dynamically via the Query interface
*/
//protected abstract LockOptions[] getLockOptions(Map lockOptions);
protected abstract LockMode[] getLockModes(LockOptions lockOptions);
/**
* Append <tt>FOR UPDATE OF</tt> clause, if necessary. This
* empty superclass implementation merely returns its first
* argument.
*/
protected String applyLocks(
String sql,
QueryParameters parameters,
Dialect dialect,
List<AfterLoadAction> afterLoadActions) throws HibernateException {
return sql;
}
/**
* Does this query return objects that might be already cached
* by the session, whose lock mode may need upgrading
*/
protected boolean upgradeLocks() {
return false;
}
/**
* Return false is this loader is a batch entity loader
*/
protected boolean isSingleRowLoader() {
return false;
}
/**
* Get the SQL table aliases of entities whose
* associations are subselect-loadable, returning
* null if this loader does not support subselect
* loading
*/
protected String[] getAliases() {
return null;
}
/**
* Modify the SQL, adding lock hints and comments, if necessary
*/
protected String preprocessSQL(
String sql,
QueryParameters parameters,
Dialect dialect,
List<AfterLoadAction> afterLoadActions) throws HibernateException {
sql = applyLocks( sql, parameters, dialect, afterLoadActions );
return getFactory().getSettings().isCommentsEnabled()
? prependComment( sql, parameters )
: sql;
}
protected static interface AfterLoadAction {
public void afterLoad(SessionImplementor session, Object entity, Loadable persister);
}
protected boolean shouldUseFollowOnLocking(
QueryParameters parameters,
Dialect dialect,
List<AfterLoadAction> afterLoadActions) {
if ( dialect.useFollowOnLocking() ) {
LOG.usingFollowOnLocking();
// currently only one lock mode is allowed in follow-on locking
final LockMode lockMode = determineFollowOnLockMode( parameters.getLockOptions() );
final LockOptions lockOptions = new LockOptions( lockMode );
lockOptions.setTimeOut( parameters.getLockOptions().getTimeOut() );
lockOptions.setScope( parameters.getLockOptions().getScope() );
afterLoadActions.add(
new AfterLoadAction() {
@Override
public void afterLoad(SessionImplementor session, Object entity, Loadable persister) {
( (Session) session ).buildLockRequest( lockOptions ).lock( persister.getEntityName(), entity );
}
}
);
parameters.setLockOptions( new LockOptions() );
return true;
}
return false;
}
protected LockMode determineFollowOnLockMode(LockOptions lockOptions) {
final LockMode lockModeToUse = lockOptions.findGreatestLockMode();
if ( lockOptions.hasAliasSpecificLockModes() ) {
LOG.aliasSpecificLockingWithFollowOnLocking( lockModeToUse );
}
return lockModeToUse;
}
private String prependComment(String sql, QueryParameters parameters) {
String comment = parameters.getComment();
if ( comment == null ) {
return sql;
}
else {
return new StringBuilder( comment.length() + sql.length() + 5 )
.append( "/* " )
.append( comment )
.append( " */ " )
.append( sql )
.toString();
}
}
/**
* Execute an SQL query and attempt to instantiate instances of the class mapped by the given
* persister from each row of the <tt>ResultSet</tt>. If an object is supplied, will attempt to
* initialize that object. If a collection is supplied, attempt to initialize that collection.
*/
public List doQueryAndInitializeNonLazyCollections(
final SessionImplementor session,
final QueryParameters queryParameters,
final boolean returnProxies) throws HibernateException, SQLException {
return doQueryAndInitializeNonLazyCollections(
session,
queryParameters,
returnProxies,
null
);
}
public List doQueryAndInitializeNonLazyCollections(
final SessionImplementor session,
final QueryParameters queryParameters,
final boolean returnProxies,
final ResultTransformer forcedResultTransformer)
throws HibernateException, SQLException {
final PersistenceContext persistenceContext = session.getPersistenceContext();
boolean defaultReadOnlyOrig = persistenceContext.isDefaultReadOnly();
if ( queryParameters.isReadOnlyInitialized() ) {
// The read-only/modifiable mode for the query was explicitly set.
// Temporarily set the default read-only/modifiable setting to the query's setting.
persistenceContext.setDefaultReadOnly( queryParameters.isReadOnly() );
}
else {
// The read-only/modifiable setting for the query was not initialized.
// Use the default read-only/modifiable from the persistence context instead.
queryParameters.setReadOnly( persistenceContext.isDefaultReadOnly() );
}
persistenceContext.beforeLoad();
List result;
try {
try {
result = doQuery( session, queryParameters, returnProxies, forcedResultTransformer );
}
finally {
persistenceContext.afterLoad();
}
persistenceContext.initializeNonLazyCollections();
}
finally {
// Restore the original default
persistenceContext.setDefaultReadOnly( defaultReadOnlyOrig );
}
return result;
}
/**
* Loads a single row from the result set. This is the processing used from the
* ScrollableResults where no collection fetches were encountered.
*
* @param resultSet The result set from which to do the load.
* @param session The session from which the request originated.
* @param queryParameters The query parameters specified by the user.
* @param returnProxies Should proxies be generated
* @return The loaded "row".
* @throws HibernateException
*/
public Object loadSingleRow(
final ResultSet resultSet,
final SessionImplementor session,
final QueryParameters queryParameters,
final boolean returnProxies) throws HibernateException {
final int entitySpan = getEntityPersisters().length;
final List hydratedObjects = entitySpan == 0 ?
null : new ArrayList( entitySpan );
final Object result;
try {
result = getRowFromResultSet(
resultSet,
session,
queryParameters,
getLockModes( queryParameters.getLockOptions() ),
null,
hydratedObjects,
new EntityKey[entitySpan],
returnProxies
);
}
catch ( SQLException sqle ) {
throw factory.getSQLExceptionHelper().convert(
sqle,
"could not read next row of results",
getSQLString()
);
}
initializeEntitiesAndCollections(
hydratedObjects,
resultSet,
session,
queryParameters.isReadOnly( session )
);
session.getPersistenceContext().initializeNonLazyCollections();
return result;
}
private Object sequentialLoad(
final ResultSet resultSet,
final SessionImplementor session,
final QueryParameters queryParameters,
final boolean returnProxies,
final EntityKey keyToRead) throws HibernateException {
final int entitySpan = getEntityPersisters().length;
final List hydratedObjects = entitySpan == 0 ?
null : new ArrayList( entitySpan );
Object result = null;
final EntityKey[] loadedKeys = new EntityKey[entitySpan];
try {
do {
Object loaded = getRowFromResultSet(
resultSet,
session,
queryParameters,
getLockModes( queryParameters.getLockOptions() ),
null,
hydratedObjects,
loadedKeys,
returnProxies
);
if ( ! keyToRead.equals( loadedKeys[0] ) ) {
throw new AssertionFailure(
String.format(
"Unexpected key read for row; expected [%s]; actual [%s]",
keyToRead,
loadedKeys[0] )
);
}
if ( result == null ) {
result = loaded;
}
}
while ( resultSet.next() &&
isCurrentRowForSameEntity( keyToRead, 0, resultSet, session ) );
}
catch ( SQLException sqle ) {
throw factory.getSQLExceptionHelper().convert(
sqle,
"could not doAfterTransactionCompletion sequential read of results (forward)",
getSQLString()
);
}
initializeEntitiesAndCollections(
hydratedObjects,
resultSet,
session,
queryParameters.isReadOnly( session )
);
session.getPersistenceContext().initializeNonLazyCollections();
return result;
}
private boolean isCurrentRowForSameEntity(
final EntityKey keyToRead,
final int persisterIndex,
final ResultSet resultSet,
final SessionImplementor session) throws SQLException {
EntityKey currentRowKey = getKeyFromResultSet(
persisterIndex, getEntityPersisters()[persisterIndex], null, resultSet, session
);
return keyToRead.equals( currentRowKey );
}
/**
* Loads a single logical row from the result set moving forward. This is the
* processing used from the ScrollableResults where there were collection fetches
* encountered; thus a single logical row may have multiple rows in the underlying
* result set.
*
* @param resultSet The result set from which to do the load.
* @param session The session from which the request originated.
* @param queryParameters The query parameters specified by the user.
* @param returnProxies Should proxies be generated
* @return The loaded "row".
* @throws HibernateException
*/
public Object loadSequentialRowsForward(
final ResultSet resultSet,
final SessionImplementor session,
final QueryParameters queryParameters,
final boolean returnProxies) throws HibernateException {
// note that for sequential scrolling, we make the assumption that
// the first persister element is the "root entity"
try {
if ( resultSet.isAfterLast() ) {
// don't even bother trying to read further
return null;
}
if ( resultSet.isBeforeFirst() ) {
resultSet.next();
}
// We call getKeyFromResultSet() here so that we can know the
// key value upon which to doAfterTransactionCompletion the breaking logic. However,
// it is also then called from getRowFromResultSet() which is certainly
// not the most efficient. But the call here is needed, and there
// currently is no other way without refactoring of the doQuery()/getRowFromResultSet()
// methods
final EntityKey currentKey = getKeyFromResultSet(
0,
getEntityPersisters()[0],
null,
resultSet,
session
);
return sequentialLoad( resultSet, session, queryParameters, returnProxies, currentKey );
}
catch ( SQLException sqle ) {
throw factory.getSQLExceptionHelper().convert(
sqle,
"could not perform sequential read of results (forward)",
getSQLString()
);
}
}
/**
* Loads a single logical row from the result set moving forward. This is the
* processing used from the ScrollableResults where there were collection fetches
* encountered; thus a single logical row may have multiple rows in the underlying
* result set.
*
* @param resultSet The result set from which to do the load.
* @param session The session from which the request originated.
* @param queryParameters The query parameters specified by the user.
* @param returnProxies Should proxies be generated
* @return The loaded "row".
* @throws HibernateException
*/
public Object loadSequentialRowsReverse(
final ResultSet resultSet,
final SessionImplementor session,
final QueryParameters queryParameters,
final boolean returnProxies,
final boolean isLogicallyAfterLast) throws HibernateException {
// note that for sequential scrolling, we make the assumption that
// the first persister element is the "root entity"
try {
if ( resultSet.isFirst() ) {
// don't even bother trying to read any further
return null;
}
EntityKey keyToRead = null;
// This check is needed since processing leaves the cursor
// after the last physical row for the current logical row;
// thus if we are after the last physical row, this might be
// caused by either:
// 1) scrolling to the last logical row
// 2) scrolling past the last logical row
// In the latter scenario, the previous logical row
// really is the last logical row.
//
// In all other cases, we should process back two
// logical records (the current logic row, plus the
// previous logical row).
if ( resultSet.isAfterLast() && isLogicallyAfterLast ) {
// position cursor to the last row
resultSet.last();
keyToRead = getKeyFromResultSet(
0,
getEntityPersisters()[0],
null,
resultSet,
session
);
}
else {
// Since the result set cursor is always left at the first
// physical row after the "last processed", we need to jump
// back one position to get the key value we are interested
// in skipping
resultSet.previous();
// sequentially read the result set in reverse until we recognize
// a change in the key value. At that point, we are pointed at
// the last physical sequential row for the logical row in which
// we are interested in processing
boolean firstPass = true;
final EntityKey lastKey = getKeyFromResultSet(
0,
getEntityPersisters()[0],
null,
resultSet,
session
);
while ( resultSet.previous() ) {
EntityKey checkKey = getKeyFromResultSet(
0,
getEntityPersisters()[0],
null,
resultSet,
session
);
if ( firstPass ) {
firstPass = false;
keyToRead = checkKey;
}
if ( !lastKey.equals( checkKey ) ) {
break;
}
}
}
// Read backwards until we read past the first physical sequential
// row with the key we are interested in loading
while ( resultSet.previous() ) {
EntityKey checkKey = getKeyFromResultSet(
0,
getEntityPersisters()[0],
null,
resultSet,
session
);
if ( !keyToRead.equals( checkKey ) ) {
break;
}
}
// Finally, read ahead one row to position result set cursor
// at the first physical row we are interested in loading
resultSet.next();
// and doAfterTransactionCompletion the load
return sequentialLoad( resultSet, session, queryParameters, returnProxies, keyToRead );
}
catch ( SQLException sqle ) {
throw factory.getSQLExceptionHelper().convert(
sqle,
"could not doAfterTransactionCompletion sequential read of results (forward)",
getSQLString()
);
}
}
private static EntityKey getOptionalObjectKey(QueryParameters queryParameters, SessionImplementor session) {
final Object optionalObject = queryParameters.getOptionalObject();
final Serializable optionalId = queryParameters.getOptionalId();
final String optionalEntityName = queryParameters.getOptionalEntityName();
if ( optionalObject != null && optionalEntityName != null ) {
return session.generateEntityKey( optionalId, session.getEntityPersister( optionalEntityName, optionalObject ) );
}
else {
return null;
}
}
private Object getRowFromResultSet(
final ResultSet resultSet,
final SessionImplementor session,
final QueryParameters queryParameters,
final LockMode[] lockModesArray,
final EntityKey optionalObjectKey,
final List hydratedObjects,
final EntityKey[] keys,
boolean returnProxies) throws SQLException, HibernateException {
return getRowFromResultSet(
resultSet,
session,
queryParameters,
lockModesArray,
optionalObjectKey,
hydratedObjects,
keys,
returnProxies,
null
);
}
private Object getRowFromResultSet(
final ResultSet resultSet,
final SessionImplementor session,
final QueryParameters queryParameters,
final LockMode[] lockModesArray,
final EntityKey optionalObjectKey,
final List hydratedObjects,
final EntityKey[] keys,
boolean returnProxies,
ResultTransformer forcedResultTransformer) throws SQLException, HibernateException {
final Loadable[] persisters = getEntityPersisters();
final int entitySpan = persisters.length;
extractKeysFromResultSet( persisters, queryParameters, resultSet, session, keys, lockModesArray, hydratedObjects );
registerNonExists( keys, persisters, session );
// this call is side-effecty
Object[] row = getRow(
resultSet,
persisters,
keys,
queryParameters.getOptionalObject(),
optionalObjectKey,
lockModesArray,
hydratedObjects,
session
);
readCollectionElements( row, resultSet, session );
if ( returnProxies ) {
// now get an existing proxy for each row element (if there is one)
for ( int i = 0; i < entitySpan; i++ ) {
Object entity = row[i];
Object proxy = session.getPersistenceContext().proxyFor( persisters[i], keys[i], entity );
if ( entity != proxy ) {
// force the proxy to resolve itself
( (HibernateProxy) proxy ).getHibernateLazyInitializer().setImplementation(entity);
row[i] = proxy;
}
}
}
applyPostLoadLocks( row, lockModesArray, session );
return forcedResultTransformer == null ?
getResultColumnOrRow( row, queryParameters.getResultTransformer(), resultSet, session ) :
forcedResultTransformer.transformTuple(
getResultRow( row, resultSet, session ),
getResultRowAliases()
)
;
}
protected void extractKeysFromResultSet(
Loadable[] persisters,
QueryParameters queryParameters,
ResultSet resultSet,
SessionImplementor session,
EntityKey[] keys,
LockMode[] lockModes,
List hydratedObjects) throws SQLException {
final int entitySpan = persisters.length;
final int numberOfPersistersToProcess;
final Serializable optionalId = queryParameters.getOptionalId();
if ( isSingleRowLoader() && optionalId != null ) {
keys[ entitySpan - 1 ] = session.generateEntityKey( optionalId, persisters[ entitySpan - 1 ] );
// skip the last persister below...
numberOfPersistersToProcess = entitySpan - 1;
}
else {
numberOfPersistersToProcess = entitySpan;
}
final Object[] hydratedKeyState = new Object[numberOfPersistersToProcess];
for ( int i = 0; i < numberOfPersistersToProcess; i++ ) {
final Type idType = persisters[i].getIdentifierType();
hydratedKeyState[i] = idType.hydrate( resultSet, getEntityAliases()[i].getSuffixedKeyAliases(), session, null );
}
for ( int i = 0; i < numberOfPersistersToProcess; i++ ) {
final Type idType = persisters[i].getIdentifierType();
if ( idType.isComponentType() && getCompositeKeyManyToOneTargetIndices() != null ) {
// we may need to force resolve any key-many-to-one(s)
int[] keyManyToOneTargetIndices = getCompositeKeyManyToOneTargetIndices()[i];
// todo : better solution is to order the index processing based on target indices
// that would account for multiple levels whereas this scheme does not
if ( keyManyToOneTargetIndices != null ) {
for ( int targetIndex : keyManyToOneTargetIndices ) {
if ( targetIndex < numberOfPersistersToProcess ) {
final Type targetIdType = persisters[targetIndex].getIdentifierType();
final Serializable targetId = (Serializable) targetIdType.resolve(
hydratedKeyState[targetIndex],
session,
null
);
// todo : need a way to signal that this key is resolved and its data resolved
keys[targetIndex] = session.generateEntityKey( targetId, persisters[targetIndex] );
}
// this part copied from #getRow, this section could be refactored out
Object object = session.getEntityUsingInterceptor( keys[targetIndex] );
if ( object != null ) {
//its already loaded so don't need to hydrate it
instanceAlreadyLoaded(
resultSet,
targetIndex,
persisters[targetIndex],
keys[targetIndex],
object,
lockModes[targetIndex],
session
);
}
else {
instanceNotYetLoaded(
resultSet,
targetIndex,
persisters[targetIndex],
getEntityAliases()[targetIndex].getRowIdAlias(),
keys[targetIndex],
lockModes[targetIndex],
getOptionalObjectKey( queryParameters, session ),
queryParameters.getOptionalObject(),
hydratedObjects,
session
);
}
}
}
}
final Serializable resolvedId = (Serializable) idType.resolve( hydratedKeyState[i], session, null );
keys[i] = resolvedId == null ? null : session.generateEntityKey( resolvedId, persisters[i] );
}
}
protected void applyPostLoadLocks(Object[] row, LockMode[] lockModesArray, SessionImplementor session) {
}
/**
* Read any collection elements contained in a single row of the result set
*/
private void readCollectionElements(Object[] row, ResultSet resultSet, SessionImplementor session)
throws SQLException, HibernateException {
//TODO: make this handle multiple collection roles!
final CollectionPersister[] collectionPersisters = getCollectionPersisters();
if ( collectionPersisters != null ) {
final CollectionAliases[] descriptors = getCollectionAliases();
final int[] collectionOwners = getCollectionOwners();
for ( int i=0; i<collectionPersisters.length; i++ ) {
final boolean hasCollectionOwners = collectionOwners !=null &&
collectionOwners[i] > -1;
//true if this is a query and we are loading multiple instances of the same collection role
//otherwise this is a CollectionInitializer and we are loading up a single collection or batch
final Object owner = hasCollectionOwners ?
row[ collectionOwners[i] ] :
null; //if null, owner will be retrieved from session
final CollectionPersister collectionPersister = collectionPersisters[i];
final Serializable key;
if ( owner == null ) {
key = null;
}
else {
key = collectionPersister.getCollectionType().getKeyOfOwner( owner, session );
//TODO: old version did not require hashmap lookup:
//keys[collectionOwner].getIdentifier()
}
readCollectionElement(
owner,
key,
collectionPersister,
descriptors[i],
resultSet,
session
);
}
}
}
private List doQuery(
final SessionImplementor session,
final QueryParameters queryParameters,
final boolean returnProxies,
final ResultTransformer forcedResultTransformer) throws SQLException, HibernateException {
final RowSelection selection = queryParameters.getRowSelection();
final int maxRows = LimitHelper.hasMaxRows( selection ) ?
selection.getMaxRows() :
Integer.MAX_VALUE;
final List<AfterLoadAction> afterLoadActions = new ArrayList<AfterLoadAction>();
final SqlStatementWrapper wrapper = executeQueryStatement( queryParameters, false, afterLoadActions, session );
final ResultSet rs = wrapper.getResultSet();
final Statement st = wrapper.getStatement();
// would be great to move all this below here into another method that could also be used
// from the new scrolling stuff.
//
// Would need to change the way the max-row stuff is handled (i.e. behind an interface) so
// that I could do the control breaking at the means to know when to stop
try {
return processResultSet( rs, queryParameters, session, returnProxies, forcedResultTransformer, maxRows, afterLoadActions );
}
finally {
session.getTransactionCoordinator().getJdbcCoordinator().release( st );
}
}
protected List processResultSet(
ResultSet rs,
QueryParameters queryParameters,
SessionImplementor session,
boolean returnProxies,
ResultTransformer forcedResultTransformer,
int maxRows,
List<AfterLoadAction> afterLoadActions) throws SQLException {
final int entitySpan = getEntityPersisters().length;
final EntityKey optionalObjectKey = getOptionalObjectKey( queryParameters, session );
final LockMode[] lockModesArray = getLockModes( queryParameters.getLockOptions() );
final boolean createSubselects = isSubselectLoadingEnabled();
final List subselectResultKeys = createSubselects ? new ArrayList() : null;
final ArrayList hydratedObjects = entitySpan == 0 ? null : new ArrayList( entitySpan * 10 );
final List results = new ArrayList();
handleEmptyCollections( queryParameters.getCollectionKeys(), rs, session );
EntityKey[] keys = new EntityKey[entitySpan]; //we can reuse it for each row
LOG.trace( "Processing result set" );
int count;
for ( count = 0; count < maxRows && rs.next(); count++ ) {
if ( DEBUG_ENABLED )
LOG.debugf( "Result set row: %s", count );
Object result = getRowFromResultSet(
rs,
session,
queryParameters,
lockModesArray,
optionalObjectKey,
hydratedObjects,
keys,
returnProxies,
forcedResultTransformer
);
results.add( result );
if ( createSubselects ) {
subselectResultKeys.add(keys);
keys = new EntityKey[entitySpan]; //can't reuse in this case
}
}
LOG.tracev( "Done processing result set ({0} rows)", count );
initializeEntitiesAndCollections(
hydratedObjects,
rs,
session,
queryParameters.isReadOnly( session ),
afterLoadActions
);
if ( createSubselects ) {
createSubselects( subselectResultKeys, queryParameters, session );
}
return results;
}
protected boolean isSubselectLoadingEnabled() {
return false;
}
protected boolean hasSubselectLoadableCollections() {
final Loadable[] loadables = getEntityPersisters();
for ( Loadable loadable : loadables ) {
if ( loadable.hasSubselectLoadableCollections() ) {
return true;
}
}
return false;
}
private static Set[] transpose( List keys ) {
Set[] result = new Set[ ( ( EntityKey[] ) keys.get(0) ).length ];
for ( int j=0; j<result.length; j++ ) {
result[j] = new HashSet( keys.size() );
for ( Object key : keys ) {