/
EntityBinder.java
1329 lines (1192 loc) · 43.7 KB
/
EntityBinder.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.cfg.annotations;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import javax.persistence.Access;
import javax.persistence.Cacheable;
import javax.persistence.ConstraintMode;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.NamedEntityGraph;
import javax.persistence.NamedEntityGraphs;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.SecondaryTable;
import javax.persistence.SecondaryTables;
import javax.persistence.SharedCacheMode;
import org.hibernate.AnnotationException;
import org.hibernate.AssertionFailure;
import org.hibernate.EntityMode;
import org.hibernate.MappingException;
import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.FetchMode;
import org.hibernate.annotations.Filter;
import org.hibernate.annotations.Immutable;
import org.hibernate.annotations.Loader;
import org.hibernate.annotations.NaturalIdCache;
import org.hibernate.annotations.OptimisticLockType;
import org.hibernate.annotations.OptimisticLocking;
import org.hibernate.annotations.Persister;
import org.hibernate.annotations.Polymorphism;
import org.hibernate.annotations.PolymorphismType;
import org.hibernate.annotations.Proxy;
import org.hibernate.annotations.RowId;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.SQLDeleteAll;
import org.hibernate.annotations.SQLInsert;
import org.hibernate.annotations.SQLUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;
import org.hibernate.annotations.Subselect;
import org.hibernate.annotations.Synchronize;
import org.hibernate.annotations.Tables;
import org.hibernate.annotations.Tuplizer;
import org.hibernate.annotations.Tuplizers;
import org.hibernate.annotations.Where;
import org.hibernate.annotations.common.reflection.ReflectionManager;
import org.hibernate.annotations.common.reflection.XAnnotatedElement;
import org.hibernate.annotations.common.reflection.XClass;
import org.hibernate.boot.model.naming.EntityNaming;
import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.naming.ImplicitEntityNameSource;
import org.hibernate.boot.model.naming.NamingStrategyHelper;
import org.hibernate.boot.model.relational.QualifiedTableName;
import org.hibernate.boot.registry.classloading.spi.ClassLoadingException;
import org.hibernate.boot.spi.InFlightMetadataCollector;
import org.hibernate.boot.spi.MetadataBuildingContext;
import org.hibernate.cfg.AccessType;
import org.hibernate.cfg.AnnotationBinder;
import org.hibernate.cfg.BinderHelper;
import org.hibernate.cfg.Ejb3JoinColumn;
import org.hibernate.cfg.InheritanceState;
import org.hibernate.cfg.ObjectNameSource;
import org.hibernate.cfg.PropertyHolder;
import org.hibernate.cfg.UniqueConstraintHolder;
import org.hibernate.engine.OptimisticLockStyle;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.hibernate.engine.spi.ExecuteUpdateResultCheckStyle;
import org.hibernate.engine.spi.FilterDefinition;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.mapping.DependantValue;
import org.hibernate.mapping.Join;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.RootClass;
import org.hibernate.mapping.SimpleValue;
import org.hibernate.mapping.SingleTableSubclass;
import org.hibernate.mapping.Table;
import org.hibernate.mapping.TableOwner;
import org.hibernate.mapping.Value;
import org.jboss.logging.Logger;
import static org.hibernate.cfg.BinderHelper.toAliasEntityMap;
import static org.hibernate.cfg.BinderHelper.toAliasTableMap;
/**
* Stateful holder and processor for binding Entity information
*
* @author Emmanuel Bernard
*/
public class EntityBinder {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, EntityBinder.class.getName());
private static final String NATURAL_ID_CACHE_SUFFIX = "##NaturalId";
private MetadataBuildingContext context;
private String name;
private XClass annotatedClass;
private PersistentClass persistentClass;
private String discriminatorValue = "";
private Boolean forceDiscriminator;
private Boolean insertableDiscriminator;
private boolean dynamicInsert;
private boolean dynamicUpdate;
private boolean explicitHibernateEntityAnnotation;
private OptimisticLockType optimisticLockType;
private PolymorphismType polymorphismType;
private boolean selectBeforeUpdate;
private int batchSize;
private boolean lazy;
private XClass proxyClass;
private String where;
// todo : we should defer to InFlightMetadataCollector.EntityTableXref for secondary table tracking;
// atm we use both from here; HBM binding solely uses InFlightMetadataCollector.EntityTableXref
private java.util.Map<String, Join> secondaryTables = new HashMap<>();
private java.util.Map<String, Object> secondaryTableJoins = new HashMap<>();
private List<Filter> filters = new ArrayList<>();
private InheritanceState inheritanceState;
private boolean ignoreIdAnnotations;
private AccessType propertyAccessType = AccessType.DEFAULT;
private boolean wrapIdsInEmbeddedComponents;
private String subselect;
private boolean isCached;
private String cacheConcurrentStrategy;
private String cacheRegion;
private boolean cacheLazyProperty;
private String naturalIdCacheRegion;
public boolean wrapIdsInEmbeddedComponents() {
return wrapIdsInEmbeddedComponents;
}
/**
* Use as a fake one for Collection of elements
*/
public EntityBinder() {
}
public EntityBinder(
Entity ejb3Ann,
org.hibernate.annotations.Entity hibAnn,
XClass annotatedClass,
PersistentClass persistentClass,
MetadataBuildingContext context) {
this.context = context;
this.persistentClass = persistentClass;
this.annotatedClass = annotatedClass;
bindEjb3Annotation( ejb3Ann );
bindHibernateAnnotation( hibAnn );
}
/**
* For the most part, this is a simple delegation to {@link PersistentClass#isPropertyDefinedInHierarchy},
* after verifying that PersistentClass is indeed set here.
*
* @param name The name of the property to check
*
* @return {@code true} if a property by that given name does already exist in the super hierarchy.
*/
@SuppressWarnings("SimplifiableIfStatement")
public boolean isPropertyDefinedInSuperHierarchy(String name) {
// Yes, yes... persistentClass can be null because EntityBinder can be used
// to bind components as well, of course...
if ( persistentClass == null ) {
return false;
}
return persistentClass.isPropertyDefinedInSuperHierarchy( name );
}
@SuppressWarnings("SimplifiableConditionalExpression")
private void bindHibernateAnnotation(org.hibernate.annotations.Entity hibAnn) {
{
final DynamicInsert dynamicInsertAnn = annotatedClass.getAnnotation( DynamicInsert.class );
this.dynamicInsert = dynamicInsertAnn == null
? ( hibAnn == null ? false : hibAnn.dynamicInsert() )
: dynamicInsertAnn.value();
}
{
final DynamicUpdate dynamicUpdateAnn = annotatedClass.getAnnotation( DynamicUpdate.class );
this.dynamicUpdate = dynamicUpdateAnn == null
? ( hibAnn == null ? false : hibAnn.dynamicUpdate() )
: dynamicUpdateAnn.value();
}
{
final SelectBeforeUpdate selectBeforeUpdateAnn = annotatedClass.getAnnotation( SelectBeforeUpdate.class );
this.selectBeforeUpdate = selectBeforeUpdateAnn == null
? ( hibAnn == null ? false : hibAnn.selectBeforeUpdate() )
: selectBeforeUpdateAnn.value();
}
{
final OptimisticLocking optimisticLockingAnn = annotatedClass.getAnnotation( OptimisticLocking.class );
this.optimisticLockType = optimisticLockingAnn == null
? ( hibAnn == null ? OptimisticLockType.VERSION : hibAnn.optimisticLock() )
: optimisticLockingAnn.type();
}
{
final Polymorphism polymorphismAnn = annotatedClass.getAnnotation( Polymorphism.class );
this.polymorphismType = polymorphismAnn == null
? ( hibAnn == null ? PolymorphismType.IMPLICIT : hibAnn.polymorphism() )
: polymorphismAnn.type();
}
if ( hibAnn != null ) {
// used later in bind for logging
explicitHibernateEntityAnnotation = true;
//persister handled in bind
}
}
private void bindEjb3Annotation(Entity ejb3Ann) {
if ( ejb3Ann == null ) throw new AssertionFailure( "@Entity should always be not null" );
if ( BinderHelper.isEmptyAnnotationValue( ejb3Ann.name() ) ) {
name = StringHelper.unqualify( annotatedClass.getName() );
}
else {
name = ejb3Ann.name();
}
}
public boolean isRootEntity() {
// This is the best option I can think of here since PersistentClass is most likely not yet fully populated
return persistentClass instanceof RootClass;
}
public void setDiscriminatorValue(String discriminatorValue) {
this.discriminatorValue = discriminatorValue;
}
public void setForceDiscriminator(boolean forceDiscriminator) {
this.forceDiscriminator = forceDiscriminator;
}
public void setInsertableDiscriminator(boolean insertableDiscriminator) {
this.insertableDiscriminator = insertableDiscriminator;
}
public void bindEntity() {
persistentClass.setAbstract( annotatedClass.isAbstract() );
persistentClass.setClassName( annotatedClass.getName() );
persistentClass.setJpaEntityName(name);
//persistentClass.setDynamic(false); //no longer needed with the Entity name refactoring?
persistentClass.setEntityName( annotatedClass.getName() );
bindDiscriminatorValue();
persistentClass.setLazy( lazy );
if ( proxyClass != null ) {
persistentClass.setProxyInterfaceName( proxyClass.getName() );
}
persistentClass.setDynamicInsert( dynamicInsert );
persistentClass.setDynamicUpdate( dynamicUpdate );
if ( persistentClass instanceof RootClass ) {
RootClass rootClass = (RootClass) persistentClass;
boolean mutable = true;
//priority on @Immutable, then @Entity.mutable()
if ( annotatedClass.isAnnotationPresent( Immutable.class ) ) {
mutable = false;
}
else {
org.hibernate.annotations.Entity entityAnn =
annotatedClass.getAnnotation( org.hibernate.annotations.Entity.class );
if ( entityAnn != null ) {
mutable = entityAnn.mutable();
}
}
rootClass.setMutable( mutable );
rootClass.setExplicitPolymorphism( isExplicitPolymorphism( polymorphismType ) );
if ( StringHelper.isNotEmpty( where ) ) {
rootClass.setWhere( where );
}
if ( cacheConcurrentStrategy != null ) {
rootClass.setCacheConcurrencyStrategy( cacheConcurrentStrategy );
rootClass.setCacheRegionName( cacheRegion );
rootClass.setLazyPropertiesCacheable( cacheLazyProperty );
}
rootClass.setNaturalIdCacheRegionName( naturalIdCacheRegion );
boolean forceDiscriminatorInSelects = forceDiscriminator == null
? context.getBuildingOptions().shouldImplicitlyForceDiscriminatorInSelect()
: forceDiscriminator;
rootClass.setForceDiscriminator( forceDiscriminatorInSelects );
if ( insertableDiscriminator != null ) {
rootClass.setDiscriminatorInsertable( insertableDiscriminator );
}
}
else {
if (explicitHibernateEntityAnnotation) {
LOG.entityAnnotationOnNonRoot(annotatedClass.getName());
}
if (annotatedClass.isAnnotationPresent(Immutable.class)) {
LOG.immutableAnnotationOnNonRoot(annotatedClass.getName());
}
}
persistentClass.setCached( isCached );
persistentClass.setOptimisticLockStyle( getVersioning( optimisticLockType ) );
persistentClass.setSelectBeforeUpdate( selectBeforeUpdate );
//set persister if needed
Persister persisterAnn = annotatedClass.getAnnotation( Persister.class );
Class persister = null;
if ( persisterAnn != null ) {
persister = persisterAnn.impl();
}
else {
org.hibernate.annotations.Entity entityAnn = annotatedClass.getAnnotation( org.hibernate.annotations.Entity.class );
if ( entityAnn != null && !BinderHelper.isEmptyAnnotationValue( entityAnn.persister() ) ) {
try {
persister = context.getBootstrapContext().getClassLoaderAccess().classForName( entityAnn.persister() );
}
catch (ClassLoadingException e) {
throw new AnnotationException( "Could not find persister class: " + entityAnn.persister(), e );
}
}
}
if ( persister != null ) {
persistentClass.setEntityPersisterClass( persister );
}
persistentClass.setBatchSize( batchSize );
//SQL overriding
SQLInsert sqlInsert = annotatedClass.getAnnotation( SQLInsert.class );
SQLUpdate sqlUpdate = annotatedClass.getAnnotation( SQLUpdate.class );
SQLDelete sqlDelete = annotatedClass.getAnnotation( SQLDelete.class );
SQLDeleteAll sqlDeleteAll = annotatedClass.getAnnotation( SQLDeleteAll.class );
Loader loader = annotatedClass.getAnnotation( Loader.class );
if ( sqlInsert != null ) {
persistentClass.setCustomSQLInsert( sqlInsert.sql().trim(), sqlInsert.callable(),
ExecuteUpdateResultCheckStyle.fromExternalName( sqlInsert.check().toString().toLowerCase(Locale.ROOT) )
);
}
if ( sqlUpdate != null ) {
persistentClass.setCustomSQLUpdate( sqlUpdate.sql(), sqlUpdate.callable(),
ExecuteUpdateResultCheckStyle.fromExternalName( sqlUpdate.check().toString().toLowerCase(Locale.ROOT) )
);
}
if ( sqlDelete != null ) {
persistentClass.setCustomSQLDelete( sqlDelete.sql(), sqlDelete.callable(),
ExecuteUpdateResultCheckStyle.fromExternalName( sqlDelete.check().toString().toLowerCase(Locale.ROOT) )
);
}
if ( sqlDeleteAll != null ) {
persistentClass.setCustomSQLDelete( sqlDeleteAll.sql(), sqlDeleteAll.callable(),
ExecuteUpdateResultCheckStyle.fromExternalName( sqlDeleteAll.check().toString().toLowerCase(Locale.ROOT) )
);
}
if ( loader != null ) {
persistentClass.setLoaderName( loader.namedQuery() );
}
final JdbcEnvironment jdbcEnvironment = context.getMetadataCollector().getDatabase().getJdbcEnvironment();
if ( annotatedClass.isAnnotationPresent( Synchronize.class )) {
Synchronize synchronizedWith = annotatedClass.getAnnotation(Synchronize.class);
String [] tables = synchronizedWith.value();
for (String table : tables) {
persistentClass.addSynchronizedTable(
context.getBuildingOptions().getPhysicalNamingStrategy().toPhysicalTableName(
jdbcEnvironment.getIdentifierHelper().toIdentifier( table ),
jdbcEnvironment
).render( jdbcEnvironment.getDialect() )
);
}
}
if ( annotatedClass.isAnnotationPresent(Subselect.class )) {
Subselect subselect = annotatedClass.getAnnotation(Subselect.class);
this.subselect = subselect.value();
}
//tuplizers
if ( annotatedClass.isAnnotationPresent( Tuplizers.class ) ) {
for (Tuplizer tuplizer : annotatedClass.getAnnotation( Tuplizers.class ).value()) {
EntityMode mode = EntityMode.parse( tuplizer.entityMode() );
//todo tuplizer.entityModeType
persistentClass.addTuplizer( mode, tuplizer.impl().getName() );
}
}
if ( annotatedClass.isAnnotationPresent( Tuplizer.class ) ) {
Tuplizer tuplizer = annotatedClass.getAnnotation( Tuplizer.class );
EntityMode mode = EntityMode.parse( tuplizer.entityMode() );
//todo tuplizer.entityModeType
persistentClass.addTuplizer( mode, tuplizer.impl().getName() );
}
for ( Filter filter : filters ) {
String filterName = filter.name();
String cond = filter.condition();
if ( BinderHelper.isEmptyAnnotationValue( cond ) ) {
FilterDefinition definition = context.getMetadataCollector().getFilterDefinition( filterName );
cond = definition == null ? null : definition.getDefaultFilterCondition();
if ( StringHelper.isEmpty( cond ) ) {
throw new AnnotationException(
"no filter condition found for filter " + filterName + " in " + this.name
);
}
}
persistentClass.addFilter(filterName, cond, filter.deduceAliasInjectionPoints(),
toAliasTableMap(filter.aliases()), toAliasEntityMap(filter.aliases()));
}
LOG.debugf( "Import with entity name %s", name );
try {
context.getMetadataCollector().addImport( name, persistentClass.getEntityName() );
String entityName = persistentClass.getEntityName();
if ( !entityName.equals( name ) ) {
context.getMetadataCollector().addImport( entityName, entityName );
}
}
catch (MappingException me) {
throw new AnnotationException( "Use of the same entity name twice: " + name, me );
}
processNamedEntityGraphs();
}
private void processNamedEntityGraphs() {
processNamedEntityGraph( annotatedClass.getAnnotation( NamedEntityGraph.class ) );
final NamedEntityGraphs graphs = annotatedClass.getAnnotation( NamedEntityGraphs.class );
if ( graphs != null ) {
for ( NamedEntityGraph graph : graphs.value() ) {
processNamedEntityGraph( graph );
}
}
}
private void processNamedEntityGraph(NamedEntityGraph annotation) {
if ( annotation == null ) {
return;
}
context.getMetadataCollector().addNamedEntityGraph(
new NamedEntityGraphDefinition( annotation, name, persistentClass.getEntityName() )
);
}
public void bindDiscriminatorValue() {
if ( StringHelper.isEmpty( discriminatorValue ) ) {
Value discriminator = persistentClass.getDiscriminator();
if ( discriminator == null ) {
persistentClass.setDiscriminatorValue( name );
}
else if ( "character".equals( discriminator.getType().getName() ) ) {
throw new AnnotationException(
"Using default @DiscriminatorValue for a discriminator of type CHAR is not safe"
);
}
else if ( "integer".equals( discriminator.getType().getName() ) ) {
persistentClass.setDiscriminatorValue( String.valueOf( name.hashCode() ) );
}
else {
persistentClass.setDiscriminatorValue( name ); //Spec compliant
}
}
else {
//persistentClass.getDiscriminator()
persistentClass.setDiscriminatorValue( discriminatorValue );
}
}
OptimisticLockStyle getVersioning(OptimisticLockType type) {
switch ( type ) {
case VERSION:
return OptimisticLockStyle.VERSION;
case NONE:
return OptimisticLockStyle.NONE;
case DIRTY:
return OptimisticLockStyle.DIRTY;
case ALL:
return OptimisticLockStyle.ALL;
default:
throw new AssertionFailure( "optimistic locking not supported: " + type );
}
}
private boolean isExplicitPolymorphism(PolymorphismType type) {
switch ( type ) {
case IMPLICIT:
return false;
case EXPLICIT:
return true;
default:
throw new AssertionFailure( "Unknown polymorphism type: " + type );
}
}
public void setBatchSize(BatchSize sizeAnn) {
if ( sizeAnn != null ) {
batchSize = sizeAnn.size();
}
else {
batchSize = -1;
}
}
@SuppressWarnings({ "unchecked" })
public void setProxy(Proxy proxy) {
if ( proxy != null ) {
lazy = proxy.lazy();
if ( !lazy ) {
proxyClass = null;
}
else {
final ReflectionManager reflectionManager = context.getBootstrapContext().getReflectionManager();
if ( AnnotationBinder.isDefault( reflectionManager.toXClass( proxy.proxyClass() ), context ) ) {
proxyClass = annotatedClass;
}
else {
proxyClass = reflectionManager.toXClass( proxy.proxyClass() );
}
}
}
else {
lazy = true; //needed to allow association lazy loading.
proxyClass = annotatedClass;
}
}
public void setWhere(Where whereAnn) {
if ( whereAnn != null ) {
where = whereAnn.clause();
}
}
public void setWrapIdsInEmbeddedComponents(boolean wrapIdsInEmbeddedComponents) {
this.wrapIdsInEmbeddedComponents = wrapIdsInEmbeddedComponents;
}
public void applyCaching(
XClass clazzToProcess,
SharedCacheMode sharedCacheMode,
MetadataBuildingContext context) {
final Cache explicitCacheAnn = clazzToProcess.getAnnotation( Cache.class );
final Cacheable explicitCacheableAnn = clazzToProcess.getAnnotation( Cacheable.class );
isCached = false;
cacheConcurrentStrategy = null;
cacheRegion = null;
cacheLazyProperty = true;
if ( persistentClass instanceof RootClass ) {
Cache effectiveCacheAnn = explicitCacheAnn;
if ( explicitCacheAnn != null ) {
// preserve legacy behavior of circumventing SharedCacheMode when Hibernate's @Cache is used.
isCached = true;
}
else {
effectiveCacheAnn = buildCacheMock( clazzToProcess.getName(), context );
switch ( sharedCacheMode ) {
case ALL: {
// all entities should be cached
isCached = true;
break;
}
case ENABLE_SELECTIVE: {
if ( explicitCacheableAnn != null && explicitCacheableAnn.value() ) {
isCached = true;
}
break;
}
case DISABLE_SELECTIVE: {
if ( explicitCacheableAnn == null || explicitCacheableAnn.value() ) {
isCached = true;
}
break;
}
default: {
// treat both NONE and UNSPECIFIED the same
isCached = false;
break;
}
}
}
cacheConcurrentStrategy = resolveCacheConcurrencyStrategy( effectiveCacheAnn.usage() );
cacheRegion = effectiveCacheAnn.region();
switch ( effectiveCacheAnn.include().toLowerCase( Locale.ROOT ) ) {
case "all": {
cacheLazyProperty = true;
break;
}
case "non-lazy": {
cacheLazyProperty = false;
break;
}
default: {
throw new AnnotationException(
"Unknown @Cache.include value [" + effectiveCacheAnn.include() + "] : "
+ annotatedClass.getName()
);
}
}
}
else {
if ( explicitCacheAnn != null ) {
LOG.cacheOrCacheableAnnotationOnNonRoot(
persistentClass.getClassName() == null
? annotatedClass.getName()
: persistentClass.getClassName()
);
}
else if ( explicitCacheableAnn == null && persistentClass.getSuperclass() != null ) {
// we should inherit our super's caching config
isCached = persistentClass.getSuperclass().isCached();
}
else {
switch ( sharedCacheMode ) {
case ALL: {
// all entities should be cached
isCached = true;
break;
}
case ENABLE_SELECTIVE: {
// only entities with @Cacheable(true) should be cached
if ( explicitCacheableAnn != null && explicitCacheableAnn.value() ) {
isCached = true;
}
break;
}
case DISABLE_SELECTIVE: {
if ( explicitCacheableAnn == null || !explicitCacheableAnn.value() ) {
isCached = true;
}
break;
}
default: {
// treat both NONE and UNSPECIFIED the same
isCached = false;
break;
}
}
}
}
naturalIdCacheRegion = null;
final NaturalIdCache naturalIdCacheAnn = clazzToProcess.getAnnotation( NaturalIdCache.class );
if ( naturalIdCacheAnn != null ) {
if ( BinderHelper.isEmptyAnnotationValue( naturalIdCacheAnn.region() ) ) {
if ( explicitCacheAnn != null && StringHelper.isNotEmpty( explicitCacheAnn.region() ) ) {
naturalIdCacheRegion = explicitCacheAnn.region() + NATURAL_ID_CACHE_SUFFIX;
}
else {
naturalIdCacheRegion = clazzToProcess.getName() + NATURAL_ID_CACHE_SUFFIX;
}
}
else {
naturalIdCacheRegion = naturalIdCacheAnn.region();
}
}
}
private static String resolveCacheConcurrencyStrategy(CacheConcurrencyStrategy strategy) {
final org.hibernate.cache.spi.access.AccessType accessType = strategy.toAccessType();
return accessType == null ? null : accessType.getExternalName();
}
private static Cache buildCacheMock(String region, MetadataBuildingContext context) {
return new LocalCacheAnnotationStub( region, determineCacheConcurrencyStrategy( context ) );
}
@SuppressWarnings({ "ClassExplicitlyAnnotation" })
private static class LocalCacheAnnotationStub implements Cache {
private final String region;
private final CacheConcurrencyStrategy usage;
private LocalCacheAnnotationStub(String region, CacheConcurrencyStrategy usage) {
this.region = region;
this.usage = usage;
}
public CacheConcurrencyStrategy usage() {
return usage;
}
public String region() {
return region;
}
public String include() {
return "all";
}
public Class<? extends Annotation> annotationType() {
return Cache.class;
}
}
private static CacheConcurrencyStrategy determineCacheConcurrencyStrategy(MetadataBuildingContext context) {
return CacheConcurrencyStrategy.fromAccessType(
context.getBuildingOptions().getImplicitCacheAccessType()
);
}
private static class EntityTableObjectNameSource implements ObjectNameSource {
private final String explicitName;
private final String logicalName;
private EntityTableObjectNameSource(String explicitName, String entityName) {
this.explicitName = explicitName;
this.logicalName = StringHelper.isNotEmpty( explicitName )
? explicitName
: StringHelper.unqualify( entityName );
}
public String getExplicitName() {
return explicitName;
}
public String getLogicalName() {
return logicalName;
}
}
private static class EntityTableNamingStrategyHelper implements NamingStrategyHelper {
private final String className;
private final String entityName;
private final String jpaEntityName;
private EntityTableNamingStrategyHelper(String className, String entityName, String jpaEntityName) {
this.className = className;
this.entityName = entityName;
this.jpaEntityName = jpaEntityName;
}
public Identifier determineImplicitName(final MetadataBuildingContext buildingContext) {
return buildingContext.getBuildingOptions().getImplicitNamingStrategy().determinePrimaryTableName(
new ImplicitEntityNameSource() {
private final EntityNaming entityNaming = new EntityNaming() {
@Override
public String getClassName() {
return className;
}
@Override
public String getEntityName() {
return entityName;
}
@Override
public String getJpaEntityName() {
return jpaEntityName;
}
};
@Override
public EntityNaming getEntityNaming() {
return entityNaming;
}
@Override
public MetadataBuildingContext getBuildingContext() {
return buildingContext;
}
}
);
}
@Override
public Identifier handleExplicitName(String explicitName, MetadataBuildingContext buildingContext) {
return buildingContext.getMetadataCollector()
.getDatabase()
.getJdbcEnvironment()
.getIdentifierHelper()
.toIdentifier( explicitName );
}
@Override
public Identifier toPhysicalName(Identifier logicalName, MetadataBuildingContext buildingContext) {
return buildingContext.getBuildingOptions().getPhysicalNamingStrategy().toPhysicalTableName(
logicalName,
buildingContext.getMetadataCollector().getDatabase().getJdbcEnvironment()
);
}
}
public void bindTableForDiscriminatedSubclass(InFlightMetadataCollector.EntityTableXref superTableXref) {
if ( !SingleTableSubclass.class.isInstance( persistentClass ) ) {
throw new AssertionFailure(
"Was expecting a discriminated subclass [" + SingleTableSubclass.class.getName() +
"] but found [" + persistentClass.getClass().getName() + "] for entity [" +
persistentClass.getEntityName() + "]"
);
}
context.getMetadataCollector().addEntityTableXref(
persistentClass.getEntityName(),
context.getMetadataCollector().getDatabase().toIdentifier(
context.getMetadataCollector().getLogicalTableName(
superTableXref.getPrimaryTable()
)
),
superTableXref.getPrimaryTable(),
superTableXref
);
}
public void bindTable(
String schema,
String catalog,
String tableName,
List<UniqueConstraintHolder> uniqueConstraints,
String constraints,
InFlightMetadataCollector.EntityTableXref denormalizedSuperTableXref) {
EntityTableNamingStrategyHelper namingStrategyHelper = new EntityTableNamingStrategyHelper(
persistentClass.getClassName(),
persistentClass.getEntityName(),
name
);
final Identifier logicalName;
if ( StringHelper.isNotEmpty( tableName ) ) {
logicalName = namingStrategyHelper.handleExplicitName( tableName, context );
}
else {
logicalName = namingStrategyHelper.determineImplicitName( context );
}
final Table table = TableBinder.buildAndFillTable(
schema,
catalog,
logicalName,
persistentClass.isAbstract(),
uniqueConstraints,
null,
constraints,
context,
this.subselect,
denormalizedSuperTableXref
);
final RowId rowId = annotatedClass.getAnnotation( RowId.class );
if ( rowId != null ) {
table.setRowId( rowId.value() );
}
context.getMetadataCollector().addEntityTableXref(
persistentClass.getEntityName(),
logicalName,
table,
denormalizedSuperTableXref
);
if ( persistentClass instanceof TableOwner ) {
LOG.debugf( "Bind entity %s on table %s", persistentClass.getEntityName(), table.getName() );
( (TableOwner) persistentClass ).setTable( table );
}
else {
throw new AssertionFailure( "binding a table for a subclass" );
}
}
public void finalSecondaryTableBinding(PropertyHolder propertyHolder) {
/*
* Those operations has to be done after the id definition of the persistence class.
* ie after the properties parsing
*/
Iterator joins = secondaryTables.values().iterator();
Iterator joinColumns = secondaryTableJoins.values().iterator();
while ( joins.hasNext() ) {
Object uncastedColumn = joinColumns.next();
Join join = (Join) joins.next();
createPrimaryColumnsToSecondaryTable( uncastedColumn, propertyHolder, join );
}
}
private void createPrimaryColumnsToSecondaryTable(Object uncastedColumn, PropertyHolder propertyHolder, Join join) {
Ejb3JoinColumn[] ejb3JoinColumns;
PrimaryKeyJoinColumn[] pkColumnsAnn = null;
JoinColumn[] joinColumnsAnn = null;
if ( uncastedColumn instanceof PrimaryKeyJoinColumn[] ) {
pkColumnsAnn = (PrimaryKeyJoinColumn[]) uncastedColumn;
}
if ( uncastedColumn instanceof JoinColumn[] ) {
joinColumnsAnn = (JoinColumn[]) uncastedColumn;
}
if ( pkColumnsAnn == null && joinColumnsAnn == null ) {
ejb3JoinColumns = new Ejb3JoinColumn[1];
ejb3JoinColumns[0] = Ejb3JoinColumn.buildJoinColumn(
null,
null,
persistentClass.getIdentifier(),
secondaryTables,
propertyHolder,
context
);
}
else {
int nbrOfJoinColumns = pkColumnsAnn != null ?
pkColumnsAnn.length :
joinColumnsAnn.length;
if ( nbrOfJoinColumns == 0 ) {
ejb3JoinColumns = new Ejb3JoinColumn[1];
ejb3JoinColumns[0] = Ejb3JoinColumn.buildJoinColumn(
null,
null,
persistentClass.getIdentifier(),
secondaryTables,
propertyHolder,
context
);
}
else {
ejb3JoinColumns = new Ejb3JoinColumn[nbrOfJoinColumns];
if ( pkColumnsAnn != null ) {
for (int colIndex = 0; colIndex < nbrOfJoinColumns; colIndex++) {
ejb3JoinColumns[colIndex] = Ejb3JoinColumn.buildJoinColumn(
pkColumnsAnn[colIndex],
null,
persistentClass.getIdentifier(),
secondaryTables,
propertyHolder,
context
);
}
}
else {
for (int colIndex = 0; colIndex < nbrOfJoinColumns; colIndex++) {
ejb3JoinColumns[colIndex] = Ejb3JoinColumn.buildJoinColumn(
null,
joinColumnsAnn[colIndex],
persistentClass.getIdentifier(),
secondaryTables,
propertyHolder,
context
);
}
}
}
}
for (Ejb3JoinColumn joinColumn : ejb3JoinColumns) {
joinColumn.forceNotNull();
}
bindJoinToPersistentClass( join, ejb3JoinColumns, context );
}
private void bindJoinToPersistentClass(Join join, Ejb3JoinColumn[] ejb3JoinColumns, MetadataBuildingContext buildingContext) {
SimpleValue key = new DependantValue( buildingContext, join.getTable(), persistentClass.getIdentifier() );
join.setKey( key );
setFKNameIfDefined( join );
key.setCascadeDeleteEnabled( false );
TableBinder.bindFk( persistentClass, null, ejb3JoinColumns, key, false, buildingContext );
join.createPrimaryKey();
join.createForeignKey();
persistentClass.addJoin( join );
}
private void setFKNameIfDefined(Join join) {
// just awful..
org.hibernate.annotations.Table matchingTable = findMatchingComplimentTableAnnotation( join );
if ( matchingTable != null && !BinderHelper.isEmptyAnnotationValue( matchingTable.foreignKey().name() ) ) {
( (SimpleValue) join.getKey() ).setForeignKeyName( matchingTable.foreignKey().name() );
}
else {
javax.persistence.SecondaryTable jpaSecondaryTable = findMatchingSecondaryTable( join );
if ( jpaSecondaryTable != null ) {
if ( jpaSecondaryTable.foreignKey().value() == ConstraintMode.NO_CONSTRAINT ) {
( (SimpleValue) join.getKey() ).setForeignKeyName( "none" );
}
else {
( (SimpleValue) join.getKey() ).setForeignKeyName( StringHelper.nullIfEmpty( jpaSecondaryTable.foreignKey().name() ) );
( (SimpleValue) join.getKey() ).setForeignKeyDefinition( StringHelper.nullIfEmpty( jpaSecondaryTable.foreignKey().foreignKeyDefinition() ) );
}
}
}
}
private SecondaryTable findMatchingSecondaryTable(Join join) {
final String nameToMatch = join.getTable().getQuotedName();