/
AbstractEntityPersister.java
5640 lines (4894 loc) · 187 KB
/
AbstractEntityPersister.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.persister.entity;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.hibernate.AssertionFailure;
import org.hibernate.EntityMode;
import org.hibernate.FetchMode;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.LockOptions;
import org.hibernate.MappingException;
import org.hibernate.QueryException;
import org.hibernate.Session;
import org.hibernate.StaleObjectStateException;
import org.hibernate.StaleStateException;
import org.hibernate.bytecode.enhance.spi.LazyPropertyInitializer;
import org.hibernate.bytecode.enhance.spi.interceptor.LazyAttributeDescriptor;
import org.hibernate.bytecode.enhance.spi.interceptor.LazyAttributeLoadingInterceptor;
import org.hibernate.bytecode.enhance.spi.interceptor.LazyAttributesMetadata;
import org.hibernate.bytecode.spi.BytecodeEnhancementMetadata;
import org.hibernate.cache.spi.access.EntityRegionAccessStrategy;
import org.hibernate.cache.spi.access.NaturalIdRegionAccessStrategy;
import org.hibernate.cache.spi.entry.CacheEntry;
import org.hibernate.cache.spi.entry.CacheEntryStructure;
import org.hibernate.cache.spi.entry.ReferenceCacheEntryImpl;
import org.hibernate.cache.spi.entry.StandardCacheEntryImpl;
import org.hibernate.cache.spi.entry.StructuredCacheEntry;
import org.hibernate.cache.spi.entry.UnstructuredCacheEntry;
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.lock.LockingStrategy;
import org.hibernate.engine.OptimisticLockStyle;
import org.hibernate.engine.internal.CacheHelper;
import org.hibernate.engine.internal.ImmutableEntityEntryFactory;
import org.hibernate.engine.internal.MutableEntityEntryFactory;
import org.hibernate.engine.internal.StatefulPersistenceContext;
import org.hibernate.engine.internal.Versioning;
import org.hibernate.engine.jdbc.batch.internal.BasicBatchKey;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.engine.spi.CachedNaturalIdValueSource;
import org.hibernate.engine.spi.CascadeStyle;
import org.hibernate.engine.spi.CascadingActions;
import org.hibernate.engine.spi.CollectionKey;
import org.hibernate.engine.spi.EntityEntry;
import org.hibernate.engine.spi.EntityEntryFactory;
import org.hibernate.engine.spi.EntityKey;
import org.hibernate.engine.spi.ExecuteUpdateResultCheckStyle;
import org.hibernate.engine.spi.LoadQueryInfluencers;
import org.hibernate.engine.spi.Mapping;
import org.hibernate.engine.spi.PersistenceContext.NaturalIdHelper;
import org.hibernate.engine.spi.PersistentAttributeInterceptable;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.engine.spi.ValueInclusion;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.id.PostInsertIdentifierGenerator;
import org.hibernate.id.PostInsertIdentityPersister;
import org.hibernate.id.insert.Binder;
import org.hibernate.id.insert.InsertGeneratedIdentifierDelegate;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.FilterHelper;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.collections.ArrayHelper;
import org.hibernate.jdbc.Expectation;
import org.hibernate.jdbc.Expectations;
import org.hibernate.jdbc.TooManyRowsAffectedException;
import org.hibernate.loader.custom.sql.SQLQueryParser;
import org.hibernate.loader.entity.BatchingEntityLoaderBuilder;
import org.hibernate.loader.entity.CascadeEntityLoader;
import org.hibernate.loader.entity.DynamicBatchingEntityLoaderBuilder;
import org.hibernate.loader.entity.EntityLoader;
import org.hibernate.loader.entity.UniqueEntityLoader;
import org.hibernate.mapping.Column;
import org.hibernate.mapping.Component;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
import org.hibernate.mapping.Selectable;
import org.hibernate.mapping.Table;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.persister.spi.PersisterCreationContext;
import org.hibernate.persister.walking.internal.EntityIdentifierDefinitionHelper;
import org.hibernate.persister.walking.spi.AttributeDefinition;
import org.hibernate.persister.walking.spi.EntityIdentifierDefinition;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.property.access.internal.PropertyAccessStrategyBackRefImpl;
import org.hibernate.sql.Alias;
import org.hibernate.sql.Delete;
import org.hibernate.sql.Insert;
import org.hibernate.sql.JoinFragment;
import org.hibernate.sql.JoinType;
import org.hibernate.sql.Select;
import org.hibernate.sql.SelectFragment;
import org.hibernate.sql.SimpleSelect;
import org.hibernate.sql.Template;
import org.hibernate.sql.Update;
import org.hibernate.tuple.GenerationTiming;
import org.hibernate.tuple.InDatabaseValueGenerationStrategy;
import org.hibernate.tuple.InMemoryValueGenerationStrategy;
import org.hibernate.tuple.NonIdentifierAttribute;
import org.hibernate.tuple.ValueGeneration;
import org.hibernate.tuple.entity.EntityMetamodel;
import org.hibernate.tuple.entity.EntityTuplizer;
import org.hibernate.type.AssociationType;
import org.hibernate.type.CollectionType;
import org.hibernate.type.ComponentType;
import org.hibernate.type.CompositeType;
import org.hibernate.type.EntityType;
import org.hibernate.type.Type;
import org.hibernate.type.TypeHelper;
import org.hibernate.type.VersionType;
/**
* Basic functionality for persisting an entity via JDBC
* through either generated or custom SQL
*
* @author Gavin King
*/
public abstract class AbstractEntityPersister
implements OuterJoinLoadable, Queryable, ClassMetadata, UniqueKeyLoadable,
SQLLoadable, LazyPropertyInitializer, PostInsertIdentityPersister, Lockable {
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( AbstractEntityPersister.class );
public static final String ENTITY_CLASS = "class";
// moved up from AbstractEntityPersister ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private final SessionFactoryImplementor factory;
private final EntityRegionAccessStrategy cacheAccessStrategy;
private final NaturalIdRegionAccessStrategy naturalIdRegionAccessStrategy;
private final boolean isLazyPropertiesCacheable;
private final CacheEntryHelper cacheEntryHelper;
private final EntityMetamodel entityMetamodel;
private final EntityTuplizer entityTuplizer;
private final EntityEntryFactory entityEntryFactory;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private final String[] rootTableKeyColumnNames;
private final String[] rootTableKeyColumnReaders;
private final String[] rootTableKeyColumnReaderTemplates;
private final String[] identifierAliases;
private final int identifierColumnSpan;
private final String versionColumnName;
private final boolean hasFormulaProperties;
protected final int batchSize;
private final boolean hasSubselectLoadableCollections;
protected final String rowIdName;
// The optional SQL string defined in the where attribute
private final String sqlWhereString;
private final String sqlWhereStringTemplate;
//information about properties of this class,
//including inherited properties
//(only really needed for updatable/insertable properties)
private final int[] propertyColumnSpans;
private final String[] propertySubclassNames;
private final String[][] propertyColumnAliases;
private final String[][] propertyColumnNames;
private final String[][] propertyColumnFormulaTemplates;
private final String[][] propertyColumnReaderTemplates;
private final String[][] propertyColumnWriters;
private final boolean[][] propertyColumnUpdateable;
private final boolean[][] propertyColumnInsertable;
private final boolean[] propertyUniqueness;
private final boolean[] propertySelectable;
private final List<Integer> lobProperties = new ArrayList<>();
//information about lazy properties of this class
private final String[] lazyPropertyNames;
private final int[] lazyPropertyNumbers;
private final Type[] lazyPropertyTypes;
private final String[][] lazyPropertyColumnAliases;
//information about all properties in class hierarchy
private final String[] subclassPropertyNameClosure;
private final String[] subclassPropertySubclassNameClosure;
private final Type[] subclassPropertyTypeClosure;
private final String[][] subclassPropertyFormulaTemplateClosure;
private final String[][] subclassPropertyColumnNameClosure;
private final String[][] subclassPropertyColumnReaderClosure;
private final String[][] subclassPropertyColumnReaderTemplateClosure;
private final FetchMode[] subclassPropertyFetchModeClosure;
private final boolean[] subclassPropertyNullabilityClosure;
private final boolean[] propertyDefinedOnSubclass;
private final int[][] subclassPropertyColumnNumberClosure;
private final int[][] subclassPropertyFormulaNumberClosure;
private final CascadeStyle[] subclassPropertyCascadeStyleClosure;
//information about all columns/formulas in class hierarchy
private final String[] subclassColumnClosure;
private final boolean[] subclassColumnLazyClosure;
private final String[] subclassColumnAliasClosure;
private final boolean[] subclassColumnSelectableClosure;
private final String[] subclassColumnReaderTemplateClosure;
private final String[] subclassFormulaClosure;
private final String[] subclassFormulaTemplateClosure;
private final String[] subclassFormulaAliasClosure;
private final boolean[] subclassFormulaLazyClosure;
// dynamic filters attached to the class-level
private final FilterHelper filterHelper;
private final Set<String> affectingFetchProfileNames = new HashSet<>();
private final Map uniqueKeyLoaders = new HashMap();
private final Map lockers = new HashMap();
private final Map loaders = new HashMap();
// SQL strings
private String sqlVersionSelectString;
private String sqlSnapshotSelectString;
private Map<String,String> sqlLazySelectStringsByFetchGroup;
private String sqlIdentityInsertString;
private String sqlUpdateByRowIdString;
private String sqlLazyUpdateByRowIdString;
private String[] sqlDeleteStrings;
private String[] sqlInsertStrings;
private String[] sqlUpdateStrings;
private String[] sqlLazyUpdateStrings;
private String sqlInsertGeneratedValuesSelectString;
private String sqlUpdateGeneratedValuesSelectString;
//Custom SQL (would be better if these were private)
protected boolean[] insertCallable;
protected boolean[] updateCallable;
protected boolean[] deleteCallable;
protected String[] customSQLInsert;
protected String[] customSQLUpdate;
protected String[] customSQLDelete;
protected ExecuteUpdateResultCheckStyle[] insertResultCheckStyles;
protected ExecuteUpdateResultCheckStyle[] updateResultCheckStyles;
protected ExecuteUpdateResultCheckStyle[] deleteResultCheckStyles;
private InsertGeneratedIdentifierDelegate identityDelegate;
private boolean[] tableHasColumns;
private final String loaderName;
private UniqueEntityLoader queryLoader;
private final Map subclassPropertyAliases = new HashMap();
private final Map subclassPropertyColumnNames = new HashMap();
/**
* Warning:
* When there are duplicated property names in the subclasses
* then propertyMapping will only contain one of those properties.
* To ensure correct results, propertyMapping should only be used
* for the concrete EntityPersister (since the concrete EntityPersister
* cannot have duplicated property names).
*/
protected final BasicEntityPropertyMapping propertyMapping;
private final boolean useReferenceCacheEntries;
protected void addDiscriminatorToInsert(Insert insert) {
}
protected void addDiscriminatorToSelect(SelectFragment select, String name, String suffix) {
}
protected abstract int[] getSubclassColumnTableNumberClosure();
protected abstract int[] getSubclassFormulaTableNumberClosure();
public abstract String getSubclassTableName(int j);
protected abstract String[] getSubclassTableKeyColumns(int j);
protected abstract boolean isClassOrSuperclassTable(int j);
public abstract int getSubclassTableSpan();
protected abstract int getTableSpan();
protected abstract boolean isTableCascadeDeleteEnabled(int j);
protected abstract String getTableName(int j);
protected abstract String[] getKeyColumns(int j);
protected abstract boolean isPropertyOfTable(int property, int j);
protected abstract int[] getPropertyTableNumbersInSelect();
protected abstract int[] getPropertyTableNumbers();
protected abstract int getSubclassPropertyTableNumber(int i);
protected abstract String filterFragment(String alias) throws MappingException;
protected abstract String filterFragment(String alias, Set<String> treatAsDeclarations);
private static final String DISCRIMINATOR_ALIAS = "clazz_";
public String getDiscriminatorColumnName() {
return DISCRIMINATOR_ALIAS;
}
public String getDiscriminatorColumnReaders() {
return DISCRIMINATOR_ALIAS;
}
public String getDiscriminatorColumnReaderTemplate() {
return Template.TEMPLATE + "." + DISCRIMINATOR_ALIAS;
}
protected String getDiscriminatorAlias() {
return DISCRIMINATOR_ALIAS;
}
protected String getDiscriminatorFormulaTemplate() {
return null;
}
protected boolean isInverseTable(int j) {
return false;
}
protected boolean isNullableTable(int j) {
return false;
}
protected boolean isNullableSubclassTable(int j) {
return false;
}
protected boolean isInverseSubclassTable(int j) {
return false;
}
public boolean isSubclassEntityName(String entityName) {
return entityMetamodel.getSubclassEntityNames().contains( entityName );
}
private boolean[] getTableHasColumns() {
return tableHasColumns;
}
public String[] getRootTableKeyColumnNames() {
return rootTableKeyColumnNames;
}
protected String[] getSQLUpdateByRowIdStrings() {
if ( sqlUpdateByRowIdString == null ) {
throw new AssertionFailure( "no update by row id" );
}
String[] result = new String[getTableSpan() + 1];
result[0] = sqlUpdateByRowIdString;
System.arraycopy( sqlUpdateStrings, 0, result, 1, getTableSpan() );
return result;
}
protected String[] getSQLLazyUpdateByRowIdStrings() {
if ( sqlLazyUpdateByRowIdString == null ) {
throw new AssertionFailure( "no update by row id" );
}
String[] result = new String[getTableSpan()];
result[0] = sqlLazyUpdateByRowIdString;
System.arraycopy( sqlLazyUpdateStrings, 1, result, 1, getTableSpan() - 1 );
return result;
}
protected String getSQLSnapshotSelectString() {
return sqlSnapshotSelectString;
}
protected String getSQLLazySelectString(String fetchGroup) {
return sqlLazySelectStringsByFetchGroup.get( fetchGroup );
}
protected String[] getSQLDeleteStrings() {
return sqlDeleteStrings;
}
protected String[] getSQLInsertStrings() {
return sqlInsertStrings;
}
protected String[] getSQLUpdateStrings() {
return sqlUpdateStrings;
}
protected String[] getSQLLazyUpdateStrings() {
return sqlLazyUpdateStrings;
}
/**
* The query that inserts a row, letting the database generate an id
*
* @return The IDENTITY-based insertion query.
*/
protected String getSQLIdentityInsertString() {
return sqlIdentityInsertString;
}
protected String getVersionSelectString() {
return sqlVersionSelectString;
}
protected boolean isInsertCallable(int j) {
return insertCallable[j];
}
protected boolean isUpdateCallable(int j) {
return updateCallable[j];
}
protected boolean isDeleteCallable(int j) {
return deleteCallable[j];
}
protected boolean isSubclassPropertyDeferred(String propertyName, String entityName) {
return false;
}
protected boolean isSubclassTableSequentialSelect(int j) {
return false;
}
public boolean hasSequentialSelect() {
return false;
}
/**
* Decide which tables need to be updated.
* <p/>
* The return here is an array of boolean values with each index corresponding
* to a given table in the scope of this persister.
*
* @param dirtyProperties The indices of all the entity properties considered dirty.
* @param hasDirtyCollection Whether any collections owned by the entity which were considered dirty.
*
* @return Array of booleans indicating which table require updating.
*/
protected boolean[] getTableUpdateNeeded(final int[] dirtyProperties, boolean hasDirtyCollection) {
if ( dirtyProperties == null ) {
return getTableHasColumns(); // for objects that came in via update()
}
else {
boolean[] updateability = getPropertyUpdateability();
int[] propertyTableNumbers = getPropertyTableNumbers();
boolean[] tableUpdateNeeded = new boolean[getTableSpan()];
for ( int property : dirtyProperties ) {
int table = propertyTableNumbers[property];
tableUpdateNeeded[table] = tableUpdateNeeded[table] ||
( getPropertyColumnSpan( property ) > 0 && updateability[property] );
}
if ( isVersioned() ) {
tableUpdateNeeded[0] = tableUpdateNeeded[0] ||
Versioning.isVersionIncrementRequired(
dirtyProperties,
hasDirtyCollection,
getPropertyVersionability()
);
}
return tableUpdateNeeded;
}
}
public boolean hasRowId() {
return rowIdName != null;
}
protected boolean[][] getPropertyColumnUpdateable() {
return propertyColumnUpdateable;
}
protected boolean[][] getPropertyColumnInsertable() {
return propertyColumnInsertable;
}
protected boolean[] getPropertySelectable() {
return propertySelectable;
}
@SuppressWarnings("UnnecessaryBoxing")
public AbstractEntityPersister(
final PersistentClass persistentClass,
final EntityRegionAccessStrategy cacheAccessStrategy,
final NaturalIdRegionAccessStrategy naturalIdRegionAccessStrategy,
final PersisterCreationContext creationContext) throws HibernateException {
// moved up from AbstractEntityPersister ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
this.factory = creationContext.getSessionFactory();
this.cacheAccessStrategy = cacheAccessStrategy;
this.naturalIdRegionAccessStrategy = naturalIdRegionAccessStrategy;
isLazyPropertiesCacheable = persistentClass.isLazyPropertiesCacheable();
this.entityMetamodel = new EntityMetamodel( persistentClass, this, factory );
this.entityTuplizer = this.entityMetamodel.getTuplizer();
if ( entityMetamodel.isMutable() ) {
this.entityEntryFactory = MutableEntityEntryFactory.INSTANCE;
}
else {
this.entityEntryFactory = ImmutableEntityEntryFactory.INSTANCE;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
final JdbcServices jdbcServices = factory.getServiceRegistry().getService( JdbcServices.class );
final Dialect dialect = jdbcServices.getJdbcEnvironment().getDialect();
int batch = persistentClass.getBatchSize();
if ( batch == -1 ) {
batch = factory.getSessionFactoryOptions().getDefaultBatchFetchSize();
}
batchSize = batch;
hasSubselectLoadableCollections = persistentClass.hasSubselectLoadableCollections();
propertyMapping = new BasicEntityPropertyMapping( this );
// IDENTIFIER
identifierColumnSpan = persistentClass.getIdentifier().getColumnSpan();
rootTableKeyColumnNames = new String[identifierColumnSpan];
rootTableKeyColumnReaders = new String[identifierColumnSpan];
rootTableKeyColumnReaderTemplates = new String[identifierColumnSpan];
identifierAliases = new String[identifierColumnSpan];
rowIdName = persistentClass.getRootTable().getRowId();
loaderName = persistentClass.getLoaderName();
Iterator iter = persistentClass.getIdentifier().getColumnIterator();
int i = 0;
while ( iter.hasNext() ) {
Column col = (Column) iter.next();
rootTableKeyColumnNames[i] = col.getQuotedName( dialect );
rootTableKeyColumnReaders[i] = col.getReadExpr( dialect );
rootTableKeyColumnReaderTemplates[i] = col.getTemplate(
dialect,
factory.getSqlFunctionRegistry()
);
identifierAliases[i] = col.getAlias( dialect, persistentClass.getRootTable() );
i++;
}
// VERSION
if ( persistentClass.isVersioned() ) {
versionColumnName = ( (Column) persistentClass.getVersion().getColumnIterator().next() ).getQuotedName( dialect );
}
else {
versionColumnName = null;
}
//WHERE STRING
sqlWhereString = StringHelper.isNotEmpty( persistentClass.getWhere() ) ?
"( " + persistentClass.getWhere() + ") " :
null;
sqlWhereStringTemplate = sqlWhereString == null ?
null :
Template.renderWhereStringTemplate(
sqlWhereString,
dialect,
factory.getSqlFunctionRegistry()
);
// PROPERTIES
final boolean lazyAvailable = isInstrumented();
int hydrateSpan = entityMetamodel.getPropertySpan();
propertyColumnSpans = new int[hydrateSpan];
propertySubclassNames = new String[hydrateSpan];
propertyColumnAliases = new String[hydrateSpan][];
propertyColumnNames = new String[hydrateSpan][];
propertyColumnFormulaTemplates = new String[hydrateSpan][];
propertyColumnReaderTemplates = new String[hydrateSpan][];
propertyColumnWriters = new String[hydrateSpan][];
propertyUniqueness = new boolean[hydrateSpan];
propertySelectable = new boolean[hydrateSpan];
propertyColumnUpdateable = new boolean[hydrateSpan][];
propertyColumnInsertable = new boolean[hydrateSpan][];
HashSet thisClassProperties = new HashSet();
ArrayList lazyNames = new ArrayList();
ArrayList lazyNumbers = new ArrayList();
ArrayList lazyTypes = new ArrayList();
ArrayList lazyColAliases = new ArrayList();
iter = persistentClass.getPropertyClosureIterator();
i = 0;
boolean foundFormula = false;
while ( iter.hasNext() ) {
Property prop = (Property) iter.next();
thisClassProperties.add( prop );
int span = prop.getColumnSpan();
propertyColumnSpans[i] = span;
propertySubclassNames[i] = prop.getPersistentClass().getEntityName();
String[] colNames = new String[span];
String[] colAliases = new String[span];
String[] colReaderTemplates = new String[span];
String[] colWriters = new String[span];
String[] formulaTemplates = new String[span];
Iterator colIter = prop.getColumnIterator();
int k = 0;
while ( colIter.hasNext() ) {
Selectable thing = (Selectable) colIter.next();
colAliases[k] = thing.getAlias( dialect, prop.getValue().getTable() );
if ( thing.isFormula() ) {
foundFormula = true;
formulaTemplates[k] = thing.getTemplate( dialect, factory.getSqlFunctionRegistry() );
}
else {
Column col = (Column) thing;
colNames[k] = col.getQuotedName( dialect );
colReaderTemplates[k] = col.getTemplate( dialect, factory.getSqlFunctionRegistry() );
colWriters[k] = col.getWriteExpr();
}
k++;
}
propertyColumnNames[i] = colNames;
propertyColumnFormulaTemplates[i] = formulaTemplates;
propertyColumnReaderTemplates[i] = colReaderTemplates;
propertyColumnWriters[i] = colWriters;
propertyColumnAliases[i] = colAliases;
if ( lazyAvailable && prop.isLazy() ) {
lazyNames.add( prop.getName() );
lazyNumbers.add( i );
lazyTypes.add( prop.getValue().getType() );
lazyColAliases.add( colAliases );
}
propertyColumnUpdateable[i] = prop.getValue().getColumnUpdateability();
propertyColumnInsertable[i] = prop.getValue().getColumnInsertability();
propertySelectable[i] = prop.isSelectable();
propertyUniqueness[i] = prop.getValue().isAlternateUniqueKey();
if ( prop.isLob() && dialect.forceLobAsLastValue() ) {
lobProperties.add( i );
}
i++;
}
hasFormulaProperties = foundFormula;
lazyPropertyColumnAliases = ArrayHelper.to2DStringArray( lazyColAliases );
lazyPropertyNames = ArrayHelper.toStringArray( lazyNames );
lazyPropertyNumbers = ArrayHelper.toIntArray( lazyNumbers );
lazyPropertyTypes = ArrayHelper.toTypeArray( lazyTypes );
// SUBCLASS PROPERTY CLOSURE
ArrayList columns = new ArrayList();
ArrayList columnsLazy = new ArrayList();
ArrayList columnReaderTemplates = new ArrayList();
ArrayList aliases = new ArrayList();
ArrayList formulas = new ArrayList();
ArrayList formulaAliases = new ArrayList();
ArrayList formulaTemplates = new ArrayList();
ArrayList formulasLazy = new ArrayList();
ArrayList types = new ArrayList();
ArrayList names = new ArrayList();
ArrayList classes = new ArrayList();
ArrayList templates = new ArrayList();
ArrayList propColumns = new ArrayList();
ArrayList propColumnReaders = new ArrayList();
ArrayList propColumnReaderTemplates = new ArrayList();
ArrayList joinedFetchesList = new ArrayList();
ArrayList cascades = new ArrayList();
ArrayList definedBySubclass = new ArrayList();
ArrayList propColumnNumbers = new ArrayList();
ArrayList propFormulaNumbers = new ArrayList();
ArrayList columnSelectables = new ArrayList();
ArrayList propNullables = new ArrayList();
iter = persistentClass.getSubclassPropertyClosureIterator();
while ( iter.hasNext() ) {
Property prop = (Property) iter.next();
names.add( prop.getName() );
classes.add( prop.getPersistentClass().getEntityName() );
boolean isDefinedBySubclass = !thisClassProperties.contains( prop );
definedBySubclass.add( Boolean.valueOf( isDefinedBySubclass ) );
propNullables.add( Boolean.valueOf( prop.isOptional() || isDefinedBySubclass ) ); //TODO: is this completely correct?
types.add( prop.getType() );
Iterator colIter = prop.getColumnIterator();
String[] cols = new String[prop.getColumnSpan()];
String[] readers = new String[prop.getColumnSpan()];
String[] readerTemplates = new String[prop.getColumnSpan()];
String[] forms = new String[prop.getColumnSpan()];
int[] colnos = new int[prop.getColumnSpan()];
int[] formnos = new int[prop.getColumnSpan()];
int l = 0;
Boolean lazy = Boolean.valueOf( prop.isLazy() && lazyAvailable );
while ( colIter.hasNext() ) {
Selectable thing = (Selectable) colIter.next();
if ( thing.isFormula() ) {
String template = thing.getTemplate( dialect, factory.getSqlFunctionRegistry() );
formnos[l] = formulaTemplates.size();
colnos[l] = -1;
formulaTemplates.add( template );
forms[l] = template;
formulas.add( thing.getText( dialect ) );
formulaAliases.add( thing.getAlias( dialect ) );
formulasLazy.add( lazy );
}
else {
Column col = (Column) thing;
String colName = col.getQuotedName( dialect );
colnos[l] = columns.size(); //before add :-)
formnos[l] = -1;
columns.add( colName );
cols[l] = colName;
aliases.add( thing.getAlias( dialect, prop.getValue().getTable() ) );
columnsLazy.add( lazy );
columnSelectables.add( Boolean.valueOf( prop.isSelectable() ) );
readers[l] = col.getReadExpr( dialect );
String readerTemplate = col.getTemplate( dialect, factory.getSqlFunctionRegistry() );
readerTemplates[l] = readerTemplate;
columnReaderTemplates.add( readerTemplate );
}
l++;
}
propColumns.add( cols );
propColumnReaders.add( readers );
propColumnReaderTemplates.add( readerTemplates );
templates.add( forms );
propColumnNumbers.add( colnos );
propFormulaNumbers.add( formnos );
joinedFetchesList.add( prop.getValue().getFetchMode() );
cascades.add( prop.getCascadeStyle() );
}
subclassColumnClosure = ArrayHelper.toStringArray( columns );
subclassColumnAliasClosure = ArrayHelper.toStringArray( aliases );
subclassColumnLazyClosure = ArrayHelper.toBooleanArray( columnsLazy );
subclassColumnSelectableClosure = ArrayHelper.toBooleanArray( columnSelectables );
subclassColumnReaderTemplateClosure = ArrayHelper.toStringArray( columnReaderTemplates );
subclassFormulaClosure = ArrayHelper.toStringArray( formulas );
subclassFormulaTemplateClosure = ArrayHelper.toStringArray( formulaTemplates );
subclassFormulaAliasClosure = ArrayHelper.toStringArray( formulaAliases );
subclassFormulaLazyClosure = ArrayHelper.toBooleanArray( formulasLazy );
subclassPropertyNameClosure = ArrayHelper.toStringArray( names );
subclassPropertySubclassNameClosure = ArrayHelper.toStringArray( classes );
subclassPropertyTypeClosure = ArrayHelper.toTypeArray( types );
subclassPropertyNullabilityClosure = ArrayHelper.toBooleanArray( propNullables );
subclassPropertyFormulaTemplateClosure = ArrayHelper.to2DStringArray( templates );
subclassPropertyColumnNameClosure = ArrayHelper.to2DStringArray( propColumns );
subclassPropertyColumnReaderClosure = ArrayHelper.to2DStringArray( propColumnReaders );
subclassPropertyColumnReaderTemplateClosure = ArrayHelper.to2DStringArray( propColumnReaderTemplates );
subclassPropertyColumnNumberClosure = ArrayHelper.to2DIntArray( propColumnNumbers );
subclassPropertyFormulaNumberClosure = ArrayHelper.to2DIntArray( propFormulaNumbers );
subclassPropertyCascadeStyleClosure = new CascadeStyle[cascades.size()];
iter = cascades.iterator();
int j = 0;
while ( iter.hasNext() ) {
subclassPropertyCascadeStyleClosure[j++] = (CascadeStyle) iter.next();
}
subclassPropertyFetchModeClosure = new FetchMode[joinedFetchesList.size()];
iter = joinedFetchesList.iterator();
j = 0;
while ( iter.hasNext() ) {
subclassPropertyFetchModeClosure[j++] = (FetchMode) iter.next();
}
propertyDefinedOnSubclass = new boolean[definedBySubclass.size()];
iter = definedBySubclass.iterator();
j = 0;
while ( iter.hasNext() ) {
propertyDefinedOnSubclass[j++] = (Boolean) iter.next();
}
// Handle any filters applied to the class level
filterHelper = new FilterHelper( persistentClass.getFilters(), factory );
// Check if we can use Reference Cached entities in 2lc
// todo : should really validate that the cache access type is read-only
boolean refCacheEntries = true;
if ( !factory.getSessionFactoryOptions().isDirectReferenceCacheEntriesEnabled() ) {
refCacheEntries = false;
}
// for now, limit this to just entities that:
// 1) are immutable
if ( entityMetamodel.isMutable() ) {
refCacheEntries = false;
}
// 2) have no associations. Eventually we want to be a little more lenient with associations.
for ( Type type : getSubclassPropertyTypeClosure() ) {
if ( type.isAssociationType() ) {
refCacheEntries = false;
}
}
useReferenceCacheEntries = refCacheEntries;
this.cacheEntryHelper = buildCacheEntryHelper();
}
protected CacheEntryHelper buildCacheEntryHelper() {
if ( cacheAccessStrategy == null ) {
// the entity defined no caching...
return NoopCacheEntryHelper.INSTANCE;
}
if ( canUseReferenceCacheEntries() ) {
entityMetamodel.setLazy( false );
// todo : do we also need to unset proxy factory?
return new ReferenceCacheEntryHelper( this );
}
return factory.getSessionFactoryOptions().isStructuredCacheEntriesEnabled()
? new StructuredCacheEntryHelper( this )
: new StandardCacheEntryHelper( this );
}
public boolean canUseReferenceCacheEntries() {
return useReferenceCacheEntries;
}
protected static String getTemplateFromString(String string, SessionFactoryImplementor factory) {
return string == null ?
null :
Template.renderWhereStringTemplate( string, factory.getDialect(), factory.getSqlFunctionRegistry() );
}
protected Map<String,String> generateLazySelectStringsByFetchGroup() {
final BytecodeEnhancementMetadata enhancementMetadata = entityMetamodel.getBytecodeEnhancementMetadata();
if ( !enhancementMetadata.isEnhancedForLazyLoading()
|| !enhancementMetadata.getLazyAttributesMetadata().hasLazyAttributes() ) {
return Collections.emptyMap();
}
Map<String,String> result = new HashMap<>();
final LazyAttributesMetadata lazyAttributesMetadata = enhancementMetadata.getLazyAttributesMetadata();
for ( String groupName : lazyAttributesMetadata.getFetchGroupNames() ) {
HashSet tableNumbers = new HashSet();
ArrayList columnNumbers = new ArrayList();
ArrayList formulaNumbers = new ArrayList();
for ( LazyAttributeDescriptor lazyAttributeDescriptor :
lazyAttributesMetadata.getFetchGroupAttributeDescriptors( groupName ) ) {
// all this only really needs to consider properties
// of this class, not its subclasses, but since we
// are reusing code used for sequential selects, we
// use the subclass closure
int propertyNumber = getSubclassPropertyIndex( lazyAttributeDescriptor.getName() );
int tableNumber = getSubclassPropertyTableNumber( propertyNumber );
tableNumbers.add( tableNumber );
int[] colNumbers = subclassPropertyColumnNumberClosure[propertyNumber];
for ( int colNumber : colNumbers ) {
if ( colNumber != -1 ) {
columnNumbers.add( colNumber );
}
}
int[] formNumbers = subclassPropertyFormulaNumberClosure[propertyNumber];
for ( int formNumber : formNumbers ) {
if ( formNumber != -1 ) {
formulaNumbers.add( formNumber );
}
}
}
if ( columnNumbers.size() == 0 && formulaNumbers.size() == 0 ) {
// only one-to-one is lazy fetched
continue;
}
result.put(
groupName,
renderSelect(
ArrayHelper.toIntArray( tableNumbers ),
ArrayHelper.toIntArray( columnNumbers ),
ArrayHelper.toIntArray( formulaNumbers )
)
);
}
return result;
}
public Object initializeLazyProperty(String fieldName, Object entity, SharedSessionContractImplementor session) {
final EntityEntry entry = session.getPersistenceContext().getEntry( entity );
final InterceptorImplementor interceptor = ( (PersistentAttributeInterceptable) entity ).$$_hibernate_getInterceptor();
assert interceptor != null : "Expecting bytecode interceptor to be non-null";
if ( hasCollections() ) {
final Type type = getPropertyType( fieldName );
if ( type.isCollectionType() ) {
// we have a condition where a collection attribute is being access via enhancement:
// we can circumvent all the rest and just return the PersistentCollection
final CollectionType collectionType = (CollectionType) type;
final CollectionPersister persister = factory.getMetamodel().collectionPersister( collectionType.getRole() );
// Get/create the collection, and make sure it is initialized! This initialized part is
// different from proxy-based scenarios where we have to create the PersistentCollection
// reference "ahead of time" to add as a reference to the proxy. For bytecode solutions
// we are not creating the PersistentCollection ahead of time, but instead we are creating
// it on first request through the enhanced entity.
// see if there is already a collection instance associated with the session
// NOTE : can this ever happen?
final Serializable key = getCollectionKey( persister, entity, entry, session );
PersistentCollection collection = session.getPersistenceContext().getCollection( new CollectionKey( persister, key ) );
if ( collection == null ) {
collection = collectionType.instantiate( session, persister, key );
collection.setOwner( entity );
session.getPersistenceContext().addUninitializedCollection( persister, collection, key );
}
// HHH-11161 Initialize, if the collection is not extra lazy
if ( !persister.isExtraLazy() ) {
session.initializeCollection( collection, false );
}
interceptor.attributeInitialized( fieldName );
if ( collectionType.isArrayType() ) {
session.getPersistenceContext().addCollectionHolder( collection );
}
// update the "state" of the entity's EntityEntry to over-write UNFETCHED_PROPERTY reference
// for the collection to the just loaded collection
final EntityEntry ownerEntry = session.getPersistenceContext().getEntry( entity );
if ( ownerEntry == null ) {
// not good
throw new AssertionFailure(
"Could not locate EntityEntry for the collection owner in the PersistenceContext"
);
}
ownerEntry.overwriteLoadedStateCollectionValue( fieldName, collection );
// EARLY EXIT!!!
return collection;
}
}
final Serializable id = session.getContextEntityIdentifier( entity );
if ( entry == null ) {
throw new HibernateException( "entity is not associated with the session: " + id );
}
if ( LOG.isTraceEnabled() ) {
LOG.tracev(
"Initializing lazy properties of: {0}, field access: {1}", MessageHelper.infoString(
this,
id,
getFactory()
), fieldName
);
}
if ( session.getCacheMode().isGetEnabled() && hasCache() && isLazyPropertiesCacheable() ) {
final EntityRegionAccessStrategy cache = getCacheAccessStrategy();
final Object cacheKey = cache.generateCacheKey(id, this, session.getFactory(), session.getTenantIdentifier() );
final Object ce = CacheHelper.fromSharedCache( session, cacheKey, cache );
if ( ce != null ) {
final CacheEntry cacheEntry = (CacheEntry) getCacheEntryStructure().destructure( ce, factory );
final Object initializedValue = initializeLazyPropertiesFromCache( fieldName, entity, session, entry, cacheEntry );
if (initializedValue != LazyPropertyInitializer.UNFETCHED_PROPERTY) {
// The following should be redundant, since the setter should have set this already.
// interceptor.attributeInitialized(fieldName);
// NOTE EARLY EXIT!!!
return initializedValue;