/
Loader.cs
1801 lines (1578 loc) · 59.5 KB
/
Loader.cs
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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Iesi.Collections;
using Iesi.Collections.Generic;
using log4net;
using NHibernate.AdoNet;
using NHibernate.Cache;
using NHibernate.Collection;
using NHibernate.Engine;
using NHibernate.Event;
using NHibernate.Exceptions;
using NHibernate.Impl;
using NHibernate.Persister.Collection;
using NHibernate.Persister.Entity;
using NHibernate.Proxy;
using NHibernate.SqlCommand;
using NHibernate.SqlTypes;
using NHibernate.Transform;
using NHibernate.Type;
using NHibernate.Util;
namespace NHibernate.Loader
{
/// <summary>
/// Abstract superclass of object loading (and querying) strategies.
/// </summary>
/// <remarks>
/// <p>
/// This class implements useful common functionality that concrete loaders would delegate to.
/// It is not intended that this functionality would be directly accessed by client code (Hence,
/// all methods of this class are declared <c>protected</c> or <c>private</c>.) This class relies heavily upon the
/// <see cref="ILoadable" /> interface, which is the contract between this class and
/// <see cref="IEntityPersister" />s that may be loaded by it.
/// </p>
/// <p>
/// The present implementation is able to load any number of columns of entities and at most
/// one collection role per query.
/// </p>
/// </remarks>
/// <seealso cref="NHibernate.Persister.Entity.ILoadable"/>
public abstract class Loader
{
private static readonly ILog log = LogManager.GetLogger(typeof (Loader));
private readonly ISessionFactoryImplementor factory;
private ColumnNameCache columnNameCache;
public Loader(ISessionFactoryImplementor factory)
{
this.factory = factory;
}
/// <summary>
/// An array indicating whether the entities have eager property fetching
/// enabled.
/// </summary>
/// <value> Eager property fetching indicators. </value>
protected virtual bool[] EntityEagerPropertyFetches
{
get { return null; }
}
/// <summary>
/// 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")
/// </summary>
/// <remarks>
/// The indexes contained here are relative to the result of <see cref="EntityPersisters"/>.
/// </remarks>
protected virtual int[] Owners
{
get { return null; }
}
/// <summary>
/// An array of the owner types corresponding to the <see cref="Owners"/>
/// returns. Indices indicating no owner would be null here.
/// </summary>
protected virtual EntityType[] OwnerAssociationTypes
{
get { return null; }
}
/// <summary>
/// Get the index of the entity that owns the collection, or -1
/// if there is no owner in the query results (i.e. in the case of a
/// collection initializer) or no collection.
/// </summary>
protected virtual int[] CollectionOwners
{
get { return null; }
}
/// <summary>
/// Return false is this loader is a batch entity loader
/// </summary>
protected virtual bool IsSingleRowLoader
{
get { return false; }
}
public virtual bool IsSubselectLoadingEnabled
{
get { return false; }
}
/// <summary>
/// Get the result set descriptor
/// </summary>
protected abstract IEntityAliases[] EntityAliases { get; }
protected abstract ICollectionAliases[] CollectionAliases { get; }
public ISessionFactoryImplementor Factory
{
get { return factory; }
}
/// <summary>
/// The SqlString to be called; implemented by all subclasses
/// </summary>
/// <remarks>
/// <para>
/// The <c>setter</c> was added so that class inheriting from Loader could write a
/// value using the Property instead of directly to the field.
/// </para>
/// <para>
/// The scope is <c>protected internal</c> because the <see cref="Hql.Classic.WhereParser"/> needs to
/// be able to <c>get</c> the SqlString of the <see cref="Hql.Classic.QueryTranslator"/> when
/// it is parsing a subquery.
/// </para>
/// </remarks>
public abstract SqlString SqlString { get; }
/// <summary>
/// An array of persisters of entity classes contained in each row of results;
/// implemented by all subclasses
/// </summary>
/// <remarks>
/// The <c>setter</c> was added so that classes inheriting from Loader could write a
/// value using the Property instead of directly to the field.
/// </remarks>
public abstract ILoadable[] EntityPersisters { get; }
/// <summary>
/// An (optional) persister for a collection to be initialized; only collection loaders
/// return a non-null value
/// </summary>
protected virtual ICollectionPersister[] CollectionPersisters
{
get { return null; }
}
/// <summary>
/// What lock mode does this load entities with?
/// </summary>
/// <param name="lockModes">A Collection of lock modes specified dynamically via the Query Interface</param>
/// <returns></returns>
public abstract LockMode[] GetLockModes(IDictionary<string, LockMode> lockModes);
/// <summary>
/// Append <c>FOR UPDATE OF</c> clause, if necessary. This
/// empty superclass implementation merely returns its first
/// argument.
/// </summary>
protected virtual SqlString ApplyLocks(SqlString sql, IDictionary<string, LockMode> lockModes, Dialect.Dialect dialect)
{
return sql;
}
/// <summary>
/// Does this query return objects that might be already cached by
/// the session, whose lock mode may need upgrading.
/// </summary>
/// <returns></returns>
protected virtual bool UpgradeLocks()
{
return false;
}
/// <summary>
/// Get the SQL table aliases of entities whose
/// associations are subselect-loadable, returning
/// null if this loader does not support subselect
/// loading
/// </summary>
protected virtual string[] Aliases
{
get { return null; }
}
/// <summary>
/// Modify the SQL, adding lock hints and comments, if necessary
/// </summary>
protected virtual SqlString PreprocessSQL(SqlString sql, QueryParameters parameters, Dialect.Dialect dialect)
{
sql = ApplyLocks(sql, parameters.LockModes, dialect);
return Factory.Settings.IsCommentsEnabled ? PrependComment(sql, parameters) : sql;
}
private static SqlString PrependComment(SqlString sql, QueryParameters parameters)
{
string comment = parameters.Comment;
if (string.IsNullOrEmpty(comment))
{
return sql;
}
else
{
return sql.Insert(0, "/* " + comment + " */");
}
}
/// <summary>
/// Execute an SQL query and attempt to instantiate instances of the class mapped by the given
/// persister from each row of the <c>DataReader</c>. If an object is supplied, will attempt to
/// initialize that object. If a collection is supplied, attempt to initialize that collection.
/// </summary>
private IList DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters,
bool returnProxies)
{
IPersistenceContext persistenceContext = session.PersistenceContext;
persistenceContext.BeforeLoad();
IList result;
try
{
result = DoQuery(session, queryParameters, returnProxies);
}
finally
{
persistenceContext.AfterLoad();
}
persistenceContext.InitializeNonLazyCollections();
return result;
}
/// <summary>
/// Loads a single row from the result set. This is the processing used from the
/// ScrollableResults where no collection fetches were encountered.
/// </summary>
/// <param name="resultSet">The result set from which to do the load.</param>
/// <param name="session">The session from which the request originated.</param>
/// <param name="queryParameters">The query parameters specified by the user.</param>
/// <param name="returnProxies">Should proxies be generated</param>
/// <returns>The loaded "row".</returns>
/// <exception cref="HibernateException" />
protected object LoadSingleRow(IDataReader resultSet, ISessionImplementor session, QueryParameters queryParameters,
bool returnProxies)
{
int entitySpan = EntityPersisters.Length;
IList hydratedObjects = entitySpan == 0 ? null : new List<object>(entitySpan);
object result;
try
{
result =
GetRowFromResultSet(resultSet, session, queryParameters, GetLockModes(queryParameters.LockModes), null,
hydratedObjects, new EntityKey[entitySpan], returnProxies);
}
catch (HibernateException)
{
throw; // Don't call Convert on HibernateExceptions
}
catch (Exception sqle)
{
throw ADOExceptionHelper.Convert(Factory.SQLExceptionConverter, sqle, "could not read next row of results",
SqlString, queryParameters.PositionalParameterValues,
queryParameters.NamedParameters);
}
InitializeEntitiesAndCollections(hydratedObjects, resultSet, session, queryParameters.ReadOnly);
session.PersistenceContext.InitializeNonLazyCollections();
return result;
}
// Not ported: sequentialLoad, loadSequentialRowsForward, loadSequentialRowsReverse
internal static EntityKey GetOptionalObjectKey(QueryParameters queryParameters, ISessionImplementor session)
{
object optionalObject = queryParameters.OptionalObject;
object optionalId = queryParameters.OptionalId;
string optionalEntityName = queryParameters.OptionalEntityName;
if (optionalObject != null && !string.IsNullOrEmpty(optionalEntityName))
{
return new EntityKey(optionalId, session.GetEntityPersister(optionalEntityName, optionalObject), session.EntityMode);
}
else
{
return null;
}
}
internal object GetRowFromResultSet(IDataReader resultSet, ISessionImplementor session,
QueryParameters queryParameters, LockMode[] lockModeArray,
EntityKey optionalObjectKey, IList hydratedObjects, EntityKey[] keys,
bool returnProxies)
{
ILoadable[] persisters = EntityPersisters;
int entitySpan = persisters.Length;
for (int i = 0; i < entitySpan; i++)
{
keys[i] =
GetKeyFromResultSet(i, persisters[i], i == entitySpan - 1 ? queryParameters.OptionalId : null, resultSet, session);
//TODO: the i==entitySpan-1 bit depends upon subclass implementation (very bad)
}
RegisterNonExists(keys, session);
// this call is side-effecty
object[] row =
GetRow(resultSet, persisters, keys, queryParameters.OptionalObject, optionalObjectKey, lockModeArray,
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.PersistenceContext.ProxyFor(persisters[i], keys[i], entity);
if (entity != proxy)
{
// Force the proxy to resolve itself
((INHibernateProxy) proxy).HibernateLazyInitializer.SetImplementation(entity);
row[i] = proxy;
}
}
}
return GetResultColumnOrRow(row, queryParameters.ResultTransformer, resultSet, session);
}
/// <summary>
/// Read any collection elements contained in a single row of the result set
/// </summary>
private void ReadCollectionElements(object[] row, IDataReader resultSet, ISessionImplementor session)
{
//TODO: make this handle multiple collection roles!
ICollectionPersister[] collectionPersisters = CollectionPersisters;
if (collectionPersisters != null)
{
ICollectionAliases[] descriptors = CollectionAliases;
int[] collectionOwners = CollectionOwners;
for (int i = 0; i < collectionPersisters.Length; i++)
{
bool 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
object owner = hasCollectionOwners ? row[collectionOwners[i]] : null;
//if null, owner will be retrieved from session
ICollectionPersister collectionPersister = collectionPersisters[i];
object key;
if (owner == null)
{
key = null;
}
else
{
key = collectionPersister.CollectionType.GetKeyOfOwner(owner, session);
//TODO: old version did not require hashmap lookup:
//keys[collectionOwner].getIdentifier()
}
ReadCollectionElement(owner, key, collectionPersister, descriptors[i], resultSet, session);
}
}
}
private IList DoQuery(ISessionImplementor session, QueryParameters queryParameters, bool returnProxies)
{
RowSelection selection = queryParameters.RowSelection;
int maxRows = HasMaxRows(selection) ? selection.MaxRows : int.MaxValue;
int entitySpan = EntityPersisters.Length;
List<object> hydratedObjects = entitySpan == 0 ? null : new List<object>(entitySpan * 10);
IDbCommand st = PrepareQueryCommand(queryParameters, false, session);
IDataReader rs = GetResultSet(st, queryParameters.HasAutoDiscoverScalarTypes, queryParameters.Callable, selection,
session);
// 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
LockMode[] lockModeArray = GetLockModes(queryParameters.LockModes);
EntityKey optionalObjectKey = GetOptionalObjectKey(queryParameters, session);
bool createSubselects = IsSubselectLoadingEnabled;
List<EntityKey[]> subselectResultKeys = createSubselects ? new List<EntityKey[]>() : null;
IList results = new List<object>();
try
{
HandleEmptyCollections(queryParameters.CollectionKeys, rs, session);
EntityKey[] keys = new EntityKey[entitySpan]; // we can reuse it each time
if (log.IsDebugEnabled)
{
log.Debug("processing result set");
}
int count;
for (count = 0; count < maxRows && rs.Read(); count++)
{
if (log.IsDebugEnabled)
{
log.Debug("result set row: " + count);
}
object result = GetRowFromResultSet(rs, session, queryParameters, lockModeArray, optionalObjectKey, hydratedObjects,
keys, returnProxies);
results.Add(result);
if (createSubselects)
{
subselectResultKeys.Add(keys);
keys = new EntityKey[entitySpan]; //can't reuse in this case
}
}
if (log.IsDebugEnabled)
{
log.Debug(string.Format("done processing result set ({0} rows)", count));
}
}
catch (Exception e)
{
e.Data["actual-sql-query"] = st.CommandText;
throw;
}
finally
{
session.Batcher.CloseCommand(st, rs);
}
InitializeEntitiesAndCollections(hydratedObjects, rs, session, queryParameters.ReadOnly);
if (createSubselects)
{
CreateSubselects(subselectResultKeys, queryParameters, session);
}
return results;
}
protected bool HasSubselectLoadableCollections()
{
foreach (ILoadable loadable in EntityPersisters)
{
if (loadable.HasSubselectLoadableCollections)
{
return true;
}
}
return false;
}
private static ISet<EntityKey>[] Transpose(IList<EntityKey[]> keys)
{
ISet<EntityKey>[] result = new ISet<EntityKey>[keys[0].Length];
for (int j = 0; j < result.Length; j++)
{
result[j] = new HashedSet<EntityKey>();
for (int i = 0; i < keys.Count; i++)
{
EntityKey key = keys[i][j];
if (key != null)
{
result[j].Add(key);
}
}
}
return result;
}
internal void CreateSubselects(IList<EntityKey[]> keys, QueryParameters queryParameters, ISessionImplementor session)
{
if (keys.Count > 1)
{
//if we only returned one entity, query by key is more efficient
ISet<EntityKey>[] keySets = Transpose(keys);
IDictionary<string, int[]> namedParameterLocMap = BuildNamedParameterLocMap(queryParameters);
ILoadable[] loadables = EntityPersisters;
string[] aliases = Aliases;
foreach (EntityKey[] rowKeys in keys)
{
for (int i = 0; i < rowKeys.Length; i++)
{
if (rowKeys[i] != null && loadables[i].HasSubselectLoadableCollections)
{
SubselectFetch subselectFetch =
new SubselectFetch(aliases[i], loadables[i], queryParameters, keySets[i], namedParameterLocMap);
session.PersistenceContext.BatchFetchQueue.AddSubselect(rowKeys[i], subselectFetch);
}
}
}
}
}
private IDictionary<string, int[]> BuildNamedParameterLocMap(QueryParameters queryParameters)
{
if (queryParameters.NamedParameters != null)
{
IDictionary<string, int[]> namedParameterLocMap = new Dictionary<string, int[]>();
foreach (string name in queryParameters.NamedParameters.Keys)
{
namedParameterLocMap[name] = GetNamedParameterLocs(name);
}
return namedParameterLocMap;
}
else
{
return null;
}
}
internal void InitializeEntitiesAndCollections(IList hydratedObjects, object resultSetId, ISessionImplementor session,
bool readOnly)
{
ICollectionPersister[] collectionPersisters = CollectionPersisters;
if (collectionPersisters != null)
{
for (int i = 0; i < collectionPersisters.Length; i++)
{
if (collectionPersisters[i].IsArray)
{
//for arrays, we should end the collection load before resolving
//the entities, since the actual array instances are not instantiated
//during loading
//TODO: or we could do this polymorphically, and have two
// different operations implemented differently for arrays
EndCollectionLoad(resultSetId, session, collectionPersisters[i]);
}
}
}
//important: reuse the same event instances for performance!
PreLoadEvent pre;
PostLoadEvent post;
if (session.IsEventSource)
{
var eventSourceSession = (IEventSource) session;
pre = new PreLoadEvent(eventSourceSession);
post = new PostLoadEvent(eventSourceSession);
}
else
{
pre = null;
post = null;
}
if (hydratedObjects != null)
{
int hydratedObjectsSize = hydratedObjects.Count;
if (log.IsDebugEnabled)
{
log.Debug(string.Format("total objects hydrated: {0}", hydratedObjectsSize));
}
for (int i = 0; i < hydratedObjectsSize; i++)
{
TwoPhaseLoad.InitializeEntity(hydratedObjects[i], readOnly, session, pre, post);
}
}
if (collectionPersisters != null)
{
for (int i = 0; i < collectionPersisters.Length; i++)
{
if (!collectionPersisters[i].IsArray)
{
//for sets, we should end the collection load after resolving
//the entities, since we might call hashCode() on the elements
//TODO: or we could do this polymorphically, and have two
// different operations implemented differently for arrays
EndCollectionLoad(resultSetId, session, collectionPersisters[i]);
}
}
}
}
private static void EndCollectionLoad(object resultSetId, ISessionImplementor session,
ICollectionPersister collectionPersister)
{
//this is a query and we are loading multiple instances of the same collection role
session.PersistenceContext.LoadContexts.GetCollectionLoadContext((IDataReader) resultSetId).EndLoadingCollections(
collectionPersister);
}
protected virtual IList GetResultList(IList results, IResultTransformer resultTransformer)
{
return results;
}
/// <summary>
/// Get the actual object that is returned in the user-visible result list.
/// </summary>
/// <remarks>
/// This empty implementation merely returns its first argument. This is
/// overridden by some subclasses.
/// </remarks>
protected virtual object GetResultColumnOrRow(object[] row, IResultTransformer resultTransformer, IDataReader rs,
ISessionImplementor session)
{
return row;
}
/// <summary>
/// For missing objects associated by one-to-one with another object in the
/// result set, register the fact that the the object is missing with the
/// session.
/// </summary>
private void RegisterNonExists(EntityKey[] keys, ISessionImplementor session)
{
int[] owners = Owners;
if (owners != null)
{
EntityType[] ownerAssociationTypes = OwnerAssociationTypes;
for (int i = 0; i < keys.Length; i++)
{
int owner = owners[i];
if (owner > -1)
{
EntityKey ownerKey = keys[owner];
if (keys[i] == null && ownerKey != null)
{
bool isOneToOneAssociation = ownerAssociationTypes != null && ownerAssociationTypes[i] != null
&& ownerAssociationTypes[i].IsOneToOne;
if (isOneToOneAssociation)
{
session.PersistenceContext.AddNullProperty(ownerKey, ownerAssociationTypes[i].PropertyName);
}
}
}
}
}
}
/// <summary>
/// Read one collection element from the current row of the ADO.NET result set
/// </summary>
private static void ReadCollectionElement(object optionalOwner, object optionalKey, ICollectionPersister persister,
ICollectionAliases descriptor, IDataReader rs, ISessionImplementor session)
{
IPersistenceContext persistenceContext = session.PersistenceContext;
object collectionRowKey = persister.ReadKey(rs, descriptor.SuffixedKeyAliases, session);
if (collectionRowKey != null)
{
// we found a collection element in the result set
if (log.IsDebugEnabled)
{
log.Debug("found row of collection: " + MessageHelper.InfoString(persister, collectionRowKey));
}
object owner = optionalOwner;
if (owner == null)
{
owner = persistenceContext.GetCollectionOwner(collectionRowKey, persister);
if (owner == null)
{
//TODO: This is assertion is disabled because there is a bug that means the
// original owner of a transient, uninitialized collection is not known
// if the collection is re-referenced by a different object associated
// with the current Session
//throw new AssertionFailure("bug loading unowned collection");
}
}
IPersistentCollection rowCollection =
persistenceContext.LoadContexts.GetCollectionLoadContext(rs).GetLoadingCollection(persister, collectionRowKey);
if (rowCollection != null)
{
rowCollection.ReadFrom(rs, persister, descriptor, owner);
}
}
else if (optionalKey != null)
{
// we did not find a collection element in the result set, so we
// ensure that a collection is created with the owner's identifier,
// since what we have is an empty collection
if (log.IsDebugEnabled)
{
log.Debug("result set contains (possibly empty) collection: " + MessageHelper.InfoString(persister, optionalKey));
}
persistenceContext.LoadContexts.GetCollectionLoadContext(rs).GetLoadingCollection(persister, optionalKey);
// handle empty collection
}
// else no collection element, but also no owner
}
/// <summary>
/// If this is a collection initializer, we need to tell the session that a collection
/// is being initilized, to account for the possibility of the collection having
/// no elements (hence no rows in the result set).
/// </summary>
internal void HandleEmptyCollections(object[] keys, object resultSetId, ISessionImplementor session)
{
if (keys != null)
{
// this is a collection initializer, so we must create a collection
// for each of the passed-in keys, to account for the possibility
// that the collection is empty and has no rows in the result set
ICollectionPersister[] collectionPersisters = CollectionPersisters;
for (int j = 0; j < collectionPersisters.Length; j++)
{
for (int i = 0; i < keys.Length; i++)
{
// handle empty collections
if (log.IsDebugEnabled)
{
log.Debug("result set contains (possibly empty) collection: "
+ MessageHelper.InfoString(collectionPersisters[j], keys[i]));
}
session.PersistenceContext.LoadContexts.GetCollectionLoadContext((IDataReader) resultSetId).GetLoadingCollection(
collectionPersisters[j], keys[i]);
}
}
}
// else this is not a collection initializer (and empty collections will
// be detected by looking for the owner's identifier in the result set)
}
/// <summary>
/// Read a row of <c>EntityKey</c>s from the <c>IDataReader</c> into the given array.
/// </summary>
/// <remarks>
/// Warning: this method is side-effecty. If an <c>id</c> is given, don't bother going
/// to the <c>IDataReader</c>
/// </remarks>
private EntityKey GetKeyFromResultSet(int i, IEntityPersister persister, object id, IDataReader rs,
ISessionImplementor session)
{
object resultId;
// if we know there is exactly 1 row, we can skip.
// it would be great if we could _always_ skip this;
// it is a problem for <key-many-to-one>
if (IsSingleRowLoader && id != null)
{
resultId = id;
}
else
{
IType idType = persister.IdentifierType;
resultId = idType.NullSafeGet(rs, EntityAliases[i].SuffixedKeyAliases, session, null);
bool idIsResultId = id != null && resultId != null && idType.IsEqual(id, resultId, session.EntityMode, factory);
if (idIsResultId)
{
resultId = id; //use the id passed in
}
}
return resultId == null ? null : new EntityKey(resultId, persister, session.EntityMode);
}
/// <summary>
/// Check the version of the object in the <c>IDataReader</c> against
/// the object version in the session cache, throwing an exception
/// if the version numbers are different.
/// </summary>
/// <exception cref="StaleObjectStateException"></exception>
private void CheckVersion(int i, IEntityPersister persister, object id, object entity, IDataReader rs,
ISessionImplementor session)
{
object version = session.PersistenceContext.GetEntry(entity).Version;
// null version means the object is in the process of being loaded somewhere else in the ResultSet
if (version != null)
{
IVersionType versionType = persister.VersionType;
object currentVersion = versionType.NullSafeGet(rs, EntityAliases[i].SuffixedVersionAliases, session, null);
if (!versionType.IsEqual(version, currentVersion))
{
if (session.Factory.Statistics.IsStatisticsEnabled)
{
session.Factory.StatisticsImplementor.OptimisticFailure(persister.EntityName);
}
throw new StaleObjectStateException(persister.EntityName, id);
}
}
}
/// <summary>
/// Resolve any ids for currently loaded objects, duplications within the <c>IDataReader</c>,
/// etc. Instanciate empty objects to be initialized from the <c>IDataReader</c>. Return an
/// array of objects (a row of results) and an array of booleans (by side-effect) that determine
/// wheter the corresponding object should be initialized
/// </summary>
private object[] GetRow(IDataReader rs, ILoadable[] persisters, EntityKey[] keys, object optionalObject,
EntityKey optionalObjectKey, LockMode[] lockModes, IList hydratedObjects,
ISessionImplementor session)
{
int cols = persisters.Length;
IEntityAliases[] descriptors = EntityAliases;
if (log.IsDebugEnabled)
{
log.Debug("result row: " + StringHelper.ToString(keys));
}
object[] rowResults = new object[cols];
for (int i = 0; i < cols; i++)
{
object obj = null;
EntityKey key = keys[i];
if (keys[i] == null)
{
// do nothing
/* TODO NH-1001 : if (persisters[i]...EntityType) is an OneToMany or a ManyToOne and
* the keys.length > 1 and the relation IsIgnoreNotFound probably we are in presence of
* an load with "outer join" the relation can be considerer loaded even if the key is null (mean not found)
*/
}
else
{
//If the object is already loaded, return the loaded one
obj = session.GetEntityUsingInterceptor(key);
if (obj != null)
{
//its already loaded so dont need to hydrate it
InstanceAlreadyLoaded(rs, i, persisters[i], key, obj, lockModes[i], session);
}
else
{
obj =
InstanceNotYetLoaded(rs, i, persisters[i], key, lockModes[i], descriptors[i].RowIdAlias, optionalObjectKey,
optionalObject, hydratedObjects, session);
}
}
rowResults[i] = obj;
}
return rowResults;
}
/// <summary>
/// The entity instance is already in the session cache
/// </summary>
private void InstanceAlreadyLoaded(IDataReader rs, int i, IEntityPersister persister, EntityKey key, object obj,
LockMode lockMode, ISessionImplementor session)
{
if (!persister.IsInstance(obj, session.EntityMode))
{
string errorMsg = string.Format("loading object was of wrong class [{0}]", obj.GetType().FullName);
throw new WrongClassException(errorMsg, key.Identifier, persister.EntityName);
}
if (LockMode.None != lockMode && UpgradeLocks())
{
EntityEntry entry = session.PersistenceContext.GetEntry(obj);
bool isVersionCheckNeeded = persister.IsVersioned && entry.LockMode.LessThan(lockMode);
// we don't need to worry about existing version being uninitialized
// because this block isn't called by a re-entrant load (re-entrant
// load _always_ have lock mode NONE
if (isVersionCheckNeeded)
{
// we only check the version when _upgrading_ lock modes
CheckVersion(i, persister, key.Identifier, obj, rs, session);
// we need to upgrade the lock mode to the mode requested
entry.LockMode = lockMode;
}
}
}
/// <summary>
/// The entity instance is not in the session cache
/// </summary>
private object InstanceNotYetLoaded(IDataReader dr, int i, ILoadable persister, EntityKey key, LockMode lockMode,
string rowIdAlias, EntityKey optionalObjectKey, object optionalObject,
IList hydratedObjects, ISessionImplementor session)
{
object obj;
string instanceClass = GetInstanceClass(dr, i, persister, key.Identifier, session);
if (optionalObjectKey != null && key.Equals(optionalObjectKey))
{
// its the given optional object
obj = optionalObject;
}
else
{
obj = session.Instantiate(instanceClass, key.Identifier);
}
// need to hydrate it
// grab its state from the DataReader and keep it in the Session
// (but don't yet initialize the object itself)
// note that we acquired LockMode.READ even if it was not requested
LockMode acquiredLockMode = lockMode == LockMode.None ? LockMode.Read : lockMode;
LoadFromResultSet(dr, i, obj, instanceClass, key, rowIdAlias, acquiredLockMode, persister, session);
// materialize associations (and initialize the object) later
hydratedObjects.Add(obj);
return obj;
}
private bool IsEagerPropertyFetchEnabled(int i)
{
bool[] array = EntityEagerPropertyFetches;
return array != null && array[i];
}
/// <summary>
/// Hydrate the state of an object from the SQL <c>IDataReader</c>, into
/// an array of "hydrated" values (do not resolve associations yet),
/// and pass the hydrated state to the session.
/// </summary>
private void LoadFromResultSet(IDataReader rs, int i, object obj, string instanceClass, EntityKey key,
string rowIdAlias, LockMode lockMode, ILoadable rootPersister,
ISessionImplementor session)
{
object id = key.Identifier;
// Get the persister for the _subclass_
ILoadable persister = (ILoadable) Factory.GetEntityPersister(instanceClass);
if (log.IsDebugEnabled)
{
log.Debug("Initializing object from DataReader: " + MessageHelper.InfoString(persister, id));
}
bool eagerPropertyFetch = IsEagerPropertyFetchEnabled(i);
// add temp entry so that the next step is circular-reference
// safe - only needed because some types don't take proper
// advantage of two-phase-load (esp. components)
TwoPhaseLoad.AddUninitializedEntity(key, obj, persister, lockMode, !eagerPropertyFetch, session);
// This is not very nice (and quite slow):
string[][] cols = persister == rootPersister
? EntityAliases[i].SuffixedPropertyAliases
: EntityAliases[i].GetSuffixedPropertyAliases(persister);
object[] values = persister.Hydrate(rs, id, obj, rootPersister, cols, eagerPropertyFetch, session);
object rowId = persister.HasRowId ? rs[rowIdAlias] : null;
IAssociationType[] ownerAssociationTypes = OwnerAssociationTypes;
if (ownerAssociationTypes != null && ownerAssociationTypes[i] != null)
{
string ukName = ownerAssociationTypes[i].RHSUniqueKeyPropertyName;
if (ukName != null)
{
int index = ((IUniqueKeyLoadable) persister).GetPropertyIndex(ukName);
IType type = persister.PropertyTypes[index];
// polymorphism not really handled completely correctly,
// perhaps...well, actually its ok, assuming that the
// entity name used in the lookup is the same as the
// the one used here, which it will be
EntityUniqueKey euk =
new EntityUniqueKey(rootPersister.EntityName, ukName, type.SemiResolve(values[index], session, obj), type,
session.EntityMode, session.Factory);
session.PersistenceContext.AddEntity(euk, obj);
}
}