/
CollectionBinder.java
1671 lines (1544 loc) · 58.2 KB
/
CollectionBinder.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.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.CollectionTable;
import javax.persistence.ConstraintMode;
import javax.persistence.ElementCollection;
import javax.persistence.Embeddable;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.MapKey;
import javax.persistence.MapKeyColumn;
import javax.persistence.OneToMany;
import org.hibernate.AnnotationException;
import org.hibernate.FetchMode;
import org.hibernate.MappingException;
import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CollectionId;
import org.hibernate.annotations.CollectionType;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.Filter;
import org.hibernate.annotations.FilterJoinTable;
import org.hibernate.annotations.FilterJoinTables;
import org.hibernate.annotations.Filters;
import org.hibernate.annotations.ForeignKey;
import org.hibernate.annotations.Immutable;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import org.hibernate.annotations.Loader;
import org.hibernate.annotations.ManyToAny;
import org.hibernate.annotations.OptimisticLock;
import org.hibernate.annotations.OrderBy;
import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.Persister;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.SQLDeleteAll;
import org.hibernate.annotations.SQLInsert;
import org.hibernate.annotations.SQLUpdate;
import org.hibernate.annotations.Sort;
import org.hibernate.annotations.SortComparator;
import org.hibernate.annotations.SortNatural;
import org.hibernate.annotations.SortType;
import org.hibernate.annotations.Where;
import org.hibernate.annotations.WhereJoinTable;
import org.hibernate.annotations.common.AssertionFailure;
import org.hibernate.annotations.common.reflection.XClass;
import org.hibernate.annotations.common.reflection.XProperty;
import org.hibernate.boot.model.IdentifierGeneratorDefinition;
import org.hibernate.boot.model.TypeDefinition;
import org.hibernate.boot.spi.MetadataBuildingContext;
import org.hibernate.cfg.AccessType;
import org.hibernate.cfg.AnnotatedClassType;
import org.hibernate.cfg.AnnotationBinder;
import org.hibernate.cfg.BinderHelper;
import org.hibernate.cfg.CollectionPropertyHolder;
import org.hibernate.cfg.CollectionSecondPass;
import org.hibernate.cfg.Ejb3Column;
import org.hibernate.cfg.Ejb3JoinColumn;
import org.hibernate.cfg.IndexColumn;
import org.hibernate.cfg.InheritanceState;
import org.hibernate.cfg.PropertyData;
import org.hibernate.cfg.PropertyHolder;
import org.hibernate.cfg.PropertyHolderBuilder;
import org.hibernate.cfg.PropertyInferredData;
import org.hibernate.cfg.PropertyPreloadedData;
import org.hibernate.cfg.SecondPass;
import org.hibernate.engine.spi.ExecuteUpdateResultCheckStyle;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.mapping.Any;
import org.hibernate.mapping.Backref;
import org.hibernate.mapping.Collection;
import org.hibernate.mapping.Column;
import org.hibernate.mapping.Component;
import org.hibernate.mapping.DependantValue;
import org.hibernate.mapping.Join;
import org.hibernate.mapping.KeyValue;
import org.hibernate.mapping.ManyToOne;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
import org.hibernate.mapping.SimpleValue;
import org.hibernate.mapping.Table;
import org.jboss.logging.Logger;
import static org.hibernate.cfg.BinderHelper.toAliasEntityMap;
import static org.hibernate.cfg.BinderHelper.toAliasTableMap;
/**
* Base class for binding different types of collections to Hibernate configuration objects.
*
* @author inger
* @author Emmanuel Bernard
*/
@SuppressWarnings({"unchecked", "serial"})
public abstract class CollectionBinder {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, CollectionBinder.class.getName());
private MetadataBuildingContext buildingContext;
protected Collection collection;
protected String propertyName;
PropertyHolder propertyHolder;
int batchSize;
private String mappedBy;
private XClass collectionType;
private XClass targetEntity;
private Ejb3JoinColumn[] inverseJoinColumns;
private String cascadeStrategy;
String cacheConcurrencyStrategy;
String cacheRegionName;
private boolean oneToMany;
protected IndexColumn indexColumn;
protected boolean cascadeDeleteEnabled;
protected String mapKeyPropertyName;
private boolean insertable = true;
private boolean updatable = true;
private Ejb3JoinColumn[] fkJoinColumns;
private boolean isExplicitAssociationTable;
private Ejb3Column[] elementColumns;
private boolean isEmbedded;
private XProperty property;
private boolean ignoreNotFound;
private TableBinder tableBinder;
private Ejb3Column[] mapKeyColumns;
private Ejb3JoinColumn[] mapKeyManyToManyColumns;
protected HashMap<String, IdentifierGeneratorDefinition> localGenerators;
protected Map<XClass, InheritanceState> inheritanceStatePerClass;
private XClass declaringClass;
private boolean declaringClassSet;
private AccessType accessType;
private boolean hibernateExtensionMapping;
private boolean isSortedCollection;
private javax.persistence.OrderBy jpaOrderBy;
private OrderBy sqlOrderBy;
private Sort deprecatedSort;
private SortNatural naturalSort;
private SortComparator comparatorSort;
private String explicitType;
private final Properties explicitTypeParameters = new Properties();
protected MetadataBuildingContext getBuildingContext() {
return buildingContext;
}
public void setBuildingContext(MetadataBuildingContext buildingContext) {
this.buildingContext = buildingContext;
}
public boolean isMap() {
return false;
}
public void setIsHibernateExtensionMapping(boolean hibernateExtensionMapping) {
this.hibernateExtensionMapping = hibernateExtensionMapping;
}
protected boolean isHibernateExtensionMapping() {
return hibernateExtensionMapping;
}
public void setUpdatable(boolean updatable) {
this.updatable = updatable;
}
public void setInheritanceStatePerClass(Map<XClass, InheritanceState> inheritanceStatePerClass) {
this.inheritanceStatePerClass = inheritanceStatePerClass;
}
public void setInsertable(boolean insertable) {
this.insertable = insertable;
}
public void setCascadeStrategy(String cascadeStrategy) {
this.cascadeStrategy = cascadeStrategy;
}
public void setAccessType(AccessType accessType) {
this.accessType = accessType;
}
public void setInverseJoinColumns(Ejb3JoinColumn[] inverseJoinColumns) {
this.inverseJoinColumns = inverseJoinColumns;
}
public void setJoinColumns(Ejb3JoinColumn[] joinColumns) {
this.joinColumns = joinColumns;
}
private Ejb3JoinColumn[] joinColumns;
public void setPropertyHolder(PropertyHolder propertyHolder) {
this.propertyHolder = propertyHolder;
}
public void setBatchSize(BatchSize batchSize) {
this.batchSize = batchSize == null ? -1 : batchSize.size();
}
public void setJpaOrderBy(javax.persistence.OrderBy jpaOrderBy) {
this.jpaOrderBy = jpaOrderBy;
}
public void setSqlOrderBy(OrderBy sqlOrderBy) {
this.sqlOrderBy = sqlOrderBy;
}
public void setSort(Sort deprecatedSort) {
this.deprecatedSort = deprecatedSort;
}
public void setNaturalSort(SortNatural naturalSort) {
this.naturalSort = naturalSort;
}
public void setComparatorSort(SortComparator comparatorSort) {
this.comparatorSort = comparatorSort;
}
/**
* collection binder factory
*/
public static CollectionBinder getCollectionBinder(
String entityName,
XProperty property,
boolean isIndexed,
boolean isHibernateExtensionMapping,
MetadataBuildingContext buildingContext) {
final CollectionBinder result;
if ( property.isArray() ) {
if ( property.getElementClass().isPrimitive() ) {
result = new PrimitiveArrayBinder();
}
else {
result = new ArrayBinder();
}
}
else if ( property.isCollection() ) {
//TODO consider using an XClass
Class returnedClass = property.getCollectionClass();
if ( java.util.Set.class.equals( returnedClass ) ) {
if ( property.isAnnotationPresent( CollectionId.class ) ) {
throw new AnnotationException( "Set do not support @CollectionId: "
+ StringHelper.qualify( entityName, property.getName() ) );
}
result = new SetBinder( false );
}
else if ( java.util.SortedSet.class.equals( returnedClass ) ) {
if ( property.isAnnotationPresent( CollectionId.class ) ) {
throw new AnnotationException( "Set do not support @CollectionId: "
+ StringHelper.qualify( entityName, property.getName() ) );
}
result = new SetBinder( true );
}
else if ( java.util.Map.class.equals( returnedClass ) ) {
if ( property.isAnnotationPresent( CollectionId.class ) ) {
throw new AnnotationException( "Map do not support @CollectionId: "
+ StringHelper.qualify( entityName, property.getName() ) );
}
result = new MapBinder( false );
}
else if ( java.util.SortedMap.class.equals( returnedClass ) ) {
if ( property.isAnnotationPresent( CollectionId.class ) ) {
throw new AnnotationException( "Map do not support @CollectionId: "
+ StringHelper.qualify( entityName, property.getName() ) );
}
result = new MapBinder( true );
}
else if ( java.util.Collection.class.equals( returnedClass ) ) {
if ( property.isAnnotationPresent( CollectionId.class ) ) {
result = new IdBagBinder();
}
else {
result = new BagBinder();
}
}
else if ( java.util.List.class.equals( returnedClass ) ) {
if ( isIndexed ) {
if ( property.isAnnotationPresent( CollectionId.class ) ) {
throw new AnnotationException(
"List do not support @CollectionId and @OrderColumn (or @IndexColumn) at the same time: "
+ StringHelper.qualify( entityName, property.getName() ) );
}
result = new ListBinder();
}
else if ( property.isAnnotationPresent( CollectionId.class ) ) {
result = new IdBagBinder();
}
else {
result = new BagBinder();
}
}
else {
throw new AnnotationException(
returnedClass.getName() + " collection not yet supported: "
+ StringHelper.qualify( entityName, property.getName() )
);
}
}
else {
throw new AnnotationException(
"Illegal attempt to map a non collection as a @OneToMany, @ManyToMany or @CollectionOfElements: "
+ StringHelper.qualify( entityName, property.getName() )
);
}
result.setIsHibernateExtensionMapping( isHibernateExtensionMapping );
final CollectionType typeAnnotation = property.getAnnotation( CollectionType.class );
if ( typeAnnotation != null ) {
final String typeName = typeAnnotation.type();
// see if it names a type-def
final TypeDefinition typeDef = buildingContext.getMetadataCollector().getTypeDefinition( typeName );
if ( typeDef != null ) {
result.explicitType = typeDef.getTypeImplementorClass().getName();
result.explicitTypeParameters.putAll( typeDef.getParameters() );
}
else {
result.explicitType = typeName;
for ( Parameter param : typeAnnotation.parameters() ) {
result.explicitTypeParameters.setProperty( param.name(), param.value() );
}
}
}
return result;
}
protected CollectionBinder(boolean isSortedCollection) {
this.isSortedCollection = isSortedCollection;
}
public void setMappedBy(String mappedBy) {
this.mappedBy = mappedBy;
}
public void setTableBinder(TableBinder tableBinder) {
this.tableBinder = tableBinder;
}
public void setCollectionType(XClass collectionType) {
// NOTE: really really badly named. This is actually NOT the collection-type, but rather the collection-element-type!
this.collectionType = collectionType;
}
public void setTargetEntity(XClass targetEntity) {
this.targetEntity = targetEntity;
}
protected abstract Collection createCollection(PersistentClass persistentClass);
public Collection getCollection() {
return collection;
}
public void setPropertyName(String propertyName) {
this.propertyName = propertyName;
}
public void setDeclaringClass(XClass declaringClass) {
this.declaringClass = declaringClass;
this.declaringClassSet = true;
}
public void bind() {
this.collection = createCollection( propertyHolder.getPersistentClass() );
String role = StringHelper.qualify( propertyHolder.getPath(), propertyName );
LOG.debugf( "Collection role: %s", role );
collection.setRole( role );
collection.setMappedByProperty( mappedBy );
if ( property.isAnnotationPresent( MapKeyColumn.class )
&& mapKeyPropertyName != null ) {
throw new AnnotationException(
"Cannot mix @javax.persistence.MapKey and @MapKeyColumn or @org.hibernate.annotations.MapKey "
+ "on the same collection: " + StringHelper.qualify(
propertyHolder.getPath(), propertyName
)
);
}
// set explicit type information
if ( explicitType != null ) {
final TypeDefinition typeDef = buildingContext.getMetadataCollector().getTypeDefinition( explicitType );
if ( typeDef == null ) {
collection.setTypeName( explicitType );
collection.setTypeParameters( explicitTypeParameters );
}
else {
collection.setTypeName( typeDef.getTypeImplementorClass().getName() );
collection.setTypeParameters( typeDef.getParameters() );
}
}
//set laziness
defineFetchingStrategy();
collection.setBatchSize( batchSize );
collection.setMutable( !property.isAnnotationPresent( Immutable.class ) );
//work on association
boolean isMappedBy = !BinderHelper.isEmptyAnnotationValue( mappedBy );
final OptimisticLock lockAnn = property.getAnnotation( OptimisticLock.class );
final boolean includeInOptimisticLockChecks = ( lockAnn != null )
? ! lockAnn.excluded()
: ! isMappedBy;
collection.setOptimisticLocked( includeInOptimisticLockChecks );
Persister persisterAnn = property.getAnnotation( Persister.class );
if ( persisterAnn != null ) {
collection.setCollectionPersisterClass( persisterAnn.impl() );
}
applySortingAndOrdering( collection );
//set cache
if ( StringHelper.isNotEmpty( cacheConcurrencyStrategy ) ) {
collection.setCacheConcurrencyStrategy( cacheConcurrencyStrategy );
collection.setCacheRegionName( cacheRegionName );
}
//SQL overriding
SQLInsert sqlInsert = property.getAnnotation( SQLInsert.class );
SQLUpdate sqlUpdate = property.getAnnotation( SQLUpdate.class );
SQLDelete sqlDelete = property.getAnnotation( SQLDelete.class );
SQLDeleteAll sqlDeleteAll = property.getAnnotation( SQLDeleteAll.class );
Loader loader = property.getAnnotation( Loader.class );
if ( sqlInsert != null ) {
collection.setCustomSQLInsert( sqlInsert.sql().trim(), sqlInsert.callable(),
ExecuteUpdateResultCheckStyle.fromExternalName( sqlInsert.check().toString().toLowerCase(Locale.ROOT) )
);
}
if ( sqlUpdate != null ) {
collection.setCustomSQLUpdate( sqlUpdate.sql(), sqlUpdate.callable(),
ExecuteUpdateResultCheckStyle.fromExternalName( sqlUpdate.check().toString().toLowerCase(Locale.ROOT) )
);
}
if ( sqlDelete != null ) {
collection.setCustomSQLDelete( sqlDelete.sql(), sqlDelete.callable(),
ExecuteUpdateResultCheckStyle.fromExternalName( sqlDelete.check().toString().toLowerCase(Locale.ROOT) )
);
}
if ( sqlDeleteAll != null ) {
collection.setCustomSQLDeleteAll( sqlDeleteAll.sql(), sqlDeleteAll.callable(),
ExecuteUpdateResultCheckStyle.fromExternalName( sqlDeleteAll.check().toString().toLowerCase(Locale.ROOT) )
);
}
if ( loader != null ) {
collection.setLoaderName( loader.namedQuery() );
}
if (isMappedBy
&& (property.isAnnotationPresent( JoinColumn.class )
|| property.isAnnotationPresent( JoinColumns.class )
|| propertyHolder.getJoinTable( property ) != null ) ) {
String message = "Associations marked as mappedBy must not define database mappings like @JoinTable or @JoinColumn: ";
message += StringHelper.qualify( propertyHolder.getPath(), propertyName );
throw new AnnotationException( message );
}
collection.setInverse( isMappedBy );
//many to many may need some second pass informations
if ( !oneToMany && isMappedBy ) {
buildingContext.getMetadataCollector().addMappedBy( getCollectionType().getName(), mappedBy, propertyName );
}
//TODO reducce tableBinder != null and oneToMany
XClass collectionType = getCollectionType();
if ( inheritanceStatePerClass == null) throw new AssertionFailure( "inheritanceStatePerClass not set" );
SecondPass sp = getSecondPass(
fkJoinColumns,
joinColumns,
inverseJoinColumns,
elementColumns,
mapKeyColumns,
mapKeyManyToManyColumns,
isEmbedded,
property,
collectionType,
ignoreNotFound,
oneToMany,
tableBinder,
buildingContext
);
if ( collectionType.isAnnotationPresent( Embeddable.class )
|| property.isAnnotationPresent( ElementCollection.class ) //JPA 2
) {
// do it right away, otherwise @ManyToOne on composite element call addSecondPass
// and raise a ConcurrentModificationException
//sp.doSecondPass( CollectionHelper.EMPTY_MAP );
buildingContext.getMetadataCollector().addSecondPass( sp, !isMappedBy );
}
else {
buildingContext.getMetadataCollector().addSecondPass( sp, !isMappedBy );
}
buildingContext.getMetadataCollector().addCollectionBinding( collection );
//property building
PropertyBinder binder = new PropertyBinder();
binder.setName( propertyName );
binder.setValue( collection );
binder.setCascade( cascadeStrategy );
if ( cascadeStrategy != null && cascadeStrategy.indexOf( "delete-orphan" ) >= 0 ) {
collection.setOrphanDelete( true );
}
binder.setLazy( collection.isLazy() );
binder.setAccessType( accessType );
binder.setProperty( property );
binder.setInsertable( insertable );
binder.setUpdatable( updatable );
Property prop = binder.makeProperty();
//we don't care about the join stuffs because the column is on the association table.
if (! declaringClassSet) throw new AssertionFailure( "DeclaringClass is not set in CollectionBinder while binding" );
propertyHolder.addProperty( prop, declaringClass );
}
private void applySortingAndOrdering(Collection collection) {
boolean isSorted = isSortedCollection;
boolean hadOrderBy = false;
boolean hadExplicitSort = false;
Class<? extends Comparator> comparatorClass = null;
if ( jpaOrderBy == null && sqlOrderBy == null ) {
if ( deprecatedSort != null ) {
LOG.debug( "Encountered deprecated @Sort annotation; use @SortNatural or @SortComparator instead." );
if ( naturalSort != null || comparatorSort != null ) {
throw buildIllegalSortCombination();
}
hadExplicitSort = deprecatedSort.type() != SortType.UNSORTED;
if ( deprecatedSort.type() == SortType.NATURAL ) {
isSorted = true;
}
else if ( deprecatedSort.type() == SortType.COMPARATOR ) {
isSorted = true;
comparatorClass = deprecatedSort.comparator();
}
}
else if ( naturalSort != null ) {
if ( comparatorSort != null ) {
throw buildIllegalSortCombination();
}
hadExplicitSort = true;
}
else if ( comparatorSort != null ) {
hadExplicitSort = true;
comparatorClass = comparatorSort.value();
}
}
else {
if ( jpaOrderBy != null && sqlOrderBy != null ) {
throw new AnnotationException(
String.format(
"Illegal combination of @%s and @%s on %s",
javax.persistence.OrderBy.class.getName(),
OrderBy.class.getName(),
safeCollectionRole()
)
);
}
hadOrderBy = true;
hadExplicitSort = false;
// we can only apply the sql-based order by up front. The jpa order by has to wait for second pass
if ( sqlOrderBy != null ) {
collection.setOrderBy( sqlOrderBy.clause() );
}
}
if ( isSortedCollection ) {
if ( ! hadExplicitSort && !hadOrderBy ) {
throw new AnnotationException(
"A sorted collection must define and ordering or sorting : " + safeCollectionRole()
);
}
}
collection.setSorted( isSortedCollection || hadExplicitSort );
if ( comparatorClass != null ) {
try {
collection.setComparator( comparatorClass.newInstance() );
}
catch (Exception e) {
throw new AnnotationException(
String.format(
"Could not instantiate comparator class [%s] for %s",
comparatorClass.getName(),
safeCollectionRole()
)
);
}
}
}
private AnnotationException buildIllegalSortCombination() {
return new AnnotationException(
String.format(
"Illegal combination of annotations on %s. Only one of @%s, @%s and @%s can be used",
safeCollectionRole(),
Sort.class.getName(),
SortNatural.class.getName(),
SortComparator.class.getName()
)
);
}
private void defineFetchingStrategy() {
LazyCollection lazy = property.getAnnotation( LazyCollection.class );
Fetch fetch = property.getAnnotation( Fetch.class );
OneToMany oneToMany = property.getAnnotation( OneToMany.class );
ManyToMany manyToMany = property.getAnnotation( ManyToMany.class );
ElementCollection elementCollection = property.getAnnotation( ElementCollection.class ); //jpa 2
ManyToAny manyToAny = property.getAnnotation( ManyToAny.class );
FetchType fetchType;
if ( oneToMany != null ) {
fetchType = oneToMany.fetch();
}
else if ( manyToMany != null ) {
fetchType = manyToMany.fetch();
}
else if ( elementCollection != null ) {
fetchType = elementCollection.fetch();
}
else if ( manyToAny != null ) {
fetchType = FetchType.LAZY;
}
else {
throw new AssertionFailure(
"Define fetch strategy on a property not annotated with @ManyToOne nor @OneToMany nor @CollectionOfElements"
);
}
if ( lazy != null ) {
collection.setLazy( !( lazy.value() == LazyCollectionOption.FALSE ) );
collection.setExtraLazy( lazy.value() == LazyCollectionOption.EXTRA );
}
else {
collection.setLazy( fetchType == FetchType.LAZY );
collection.setExtraLazy( false );
}
if ( fetch != null ) {
if ( fetch.value() == org.hibernate.annotations.FetchMode.JOIN ) {
collection.setFetchMode( FetchMode.JOIN );
collection.setLazy( false );
}
else if ( fetch.value() == org.hibernate.annotations.FetchMode.SELECT ) {
collection.setFetchMode( FetchMode.SELECT );
}
else if ( fetch.value() == org.hibernate.annotations.FetchMode.SUBSELECT ) {
collection.setFetchMode( FetchMode.SELECT );
collection.setSubselectLoadable( true );
collection.getOwner().setSubselectLoadableCollections( true );
}
else {
throw new AssertionFailure( "Unknown FetchMode: " + fetch.value() );
}
}
else {
collection.setFetchMode( AnnotationBinder.getFetchMode( fetchType ) );
}
}
private XClass getCollectionType() {
if ( AnnotationBinder.isDefault( targetEntity, buildingContext ) ) {
if ( collectionType != null ) {
return collectionType;
}
else {
String errorMsg = "Collection has neither generic type or OneToMany.targetEntity() defined: "
+ safeCollectionRole();
throw new AnnotationException( errorMsg );
}
}
else {
return targetEntity;
}
}
public SecondPass getSecondPass(
final Ejb3JoinColumn[] fkJoinColumns,
final Ejb3JoinColumn[] keyColumns,
final Ejb3JoinColumn[] inverseColumns,
final Ejb3Column[] elementColumns,
final Ejb3Column[] mapKeyColumns,
final Ejb3JoinColumn[] mapKeyManyToManyColumns,
final boolean isEmbedded,
final XProperty property,
final XClass collType,
final boolean ignoreNotFound,
final boolean unique,
final TableBinder assocTableBinder,
final MetadataBuildingContext buildingContext) {
return new CollectionSecondPass( buildingContext, collection ) {
@Override
public void secondPass(java.util.Map persistentClasses, java.util.Map inheritedMetas) throws MappingException {
bindStarToManySecondPass(
persistentClasses,
collType,
fkJoinColumns,
keyColumns,
inverseColumns,
elementColumns,
isEmbedded,
property,
unique,
assocTableBinder,
ignoreNotFound,
buildingContext
);
}
};
}
/**
* return true if it's a Fk, false if it's an association table
*/
protected boolean bindStarToManySecondPass(
Map persistentClasses,
XClass collType,
Ejb3JoinColumn[] fkJoinColumns,
Ejb3JoinColumn[] keyColumns,
Ejb3JoinColumn[] inverseColumns,
Ejb3Column[] elementColumns,
boolean isEmbedded,
XProperty property,
boolean unique,
TableBinder associationTableBinder,
boolean ignoreNotFound,
MetadataBuildingContext buildingContext) {
PersistentClass persistentClass = (PersistentClass) persistentClasses.get( collType.getName() );
boolean reversePropertyInJoin = false;
if ( persistentClass != null && StringHelper.isNotEmpty( this.mappedBy ) ) {
try {
reversePropertyInJoin = 0 != persistentClass.getJoinNumber(
persistentClass.getRecursiveProperty( this.mappedBy )
);
}
catch (MappingException e) {
StringBuilder error = new StringBuilder( 80 );
error.append( "mappedBy reference an unknown target entity property: " )
.append( collType ).append( "." ).append( this.mappedBy )
.append( " in " )
.append( collection.getOwnerEntityName() )
.append( "." )
.append( property.getName() );
throw new AnnotationException( error.toString() );
}
}
if ( persistentClass != null
&& !reversePropertyInJoin
&& oneToMany
&& !this.isExplicitAssociationTable
&& ( joinColumns[0].isImplicit() && !BinderHelper.isEmptyAnnotationValue( this.mappedBy ) //implicit @JoinColumn
|| !fkJoinColumns[0].isImplicit() ) //this is an explicit @JoinColumn
) {
//this is a Foreign key
bindOneToManySecondPass(
getCollection(),
persistentClasses,
fkJoinColumns,
collType,
cascadeDeleteEnabled,
ignoreNotFound,
buildingContext,
inheritanceStatePerClass
);
return true;
}
else {
//this is an association table
bindManyToManySecondPass(
this.collection,
persistentClasses,
keyColumns,
inverseColumns,
elementColumns,
isEmbedded, collType,
ignoreNotFound, unique,
cascadeDeleteEnabled,
associationTableBinder,
property,
propertyHolder,
buildingContext
);
return false;
}
}
protected void bindOneToManySecondPass(
Collection collection,
Map persistentClasses,
Ejb3JoinColumn[] fkJoinColumns,
XClass collectionType,
boolean cascadeDeleteEnabled,
boolean ignoreNotFound,
MetadataBuildingContext buildingContext,
Map<XClass, InheritanceState> inheritanceStatePerClass) {
final boolean debugEnabled = LOG.isDebugEnabled();
if ( debugEnabled ) {
LOG.debugf( "Binding a OneToMany: %s.%s through a foreign key", propertyHolder.getEntityName(), propertyName );
}
org.hibernate.mapping.OneToMany oneToMany = new org.hibernate.mapping.OneToMany( buildingContext.getMetadataCollector(), collection.getOwner() );
collection.setElement( oneToMany );
oneToMany.setReferencedEntityName( collectionType.getName() );
oneToMany.setIgnoreNotFound( ignoreNotFound );
String assocClass = oneToMany.getReferencedEntityName();
PersistentClass associatedClass = (PersistentClass) persistentClasses.get( assocClass );
if ( jpaOrderBy != null ) {
final String orderByFragment = buildOrderByClauseFromHql(
jpaOrderBy.value(),
associatedClass,
collection.getRole()
);
if ( StringHelper.isNotEmpty( orderByFragment ) ) {
collection.setOrderBy( orderByFragment );
}
}
if ( buildingContext == null ) {
throw new AssertionFailure(
"CollectionSecondPass for oneToMany should not be called with null mappings"
);
}
Map<String, Join> joins = buildingContext.getMetadataCollector().getJoins( assocClass );
if ( associatedClass == null ) {
throw new MappingException(
"Association references unmapped class: " + assocClass
);
}
oneToMany.setAssociatedClass( associatedClass );
for (Ejb3JoinColumn column : fkJoinColumns) {
column.setPersistentClass( associatedClass, joins, inheritanceStatePerClass );
column.setJoins( joins );
collection.setCollectionTable( column.getTable() );
}
if ( debugEnabled ) {
LOG.debugf( "Mapping collection: %s -> %s", collection.getRole(), collection.getCollectionTable().getName() );
}
bindFilters( false );
bindCollectionSecondPass( collection, null, fkJoinColumns, cascadeDeleteEnabled, property, buildingContext );
if ( !collection.isInverse()
&& !collection.getKey().isNullable() ) {
// for non-inverse one-to-many, with a not-null fk, add a backref!
String entityName = oneToMany.getReferencedEntityName();
PersistentClass referenced = buildingContext.getMetadataCollector().getEntityBinding( entityName );
Backref prop = new Backref();
prop.setName( '_' + fkJoinColumns[0].getPropertyName() + '_' + fkJoinColumns[0].getLogicalColumnName() + "Backref" );
prop.setUpdateable( false );
prop.setSelectable( false );
prop.setCollectionRole( collection.getRole() );
prop.setEntityName( collection.getOwner().getEntityName() );
prop.setValue( collection.getKey() );
referenced.addProperty( prop );
}
}
private void bindFilters(boolean hasAssociationTable) {
Filter simpleFilter = property.getAnnotation( Filter.class );
//set filtering
//test incompatible choices
//if ( StringHelper.isNotEmpty( where ) ) collection.setWhere( where );
if ( simpleFilter != null ) {
if ( hasAssociationTable ) {
collection.addManyToManyFilter(simpleFilter.name(), getCondition(simpleFilter), simpleFilter.deduceAliasInjectionPoints(),
toAliasTableMap(simpleFilter.aliases()), toAliasEntityMap(simpleFilter.aliases()));
}
else {
collection.addFilter(simpleFilter.name(), getCondition(simpleFilter), simpleFilter.deduceAliasInjectionPoints(),
toAliasTableMap(simpleFilter.aliases()), toAliasEntityMap(simpleFilter.aliases()));
}
}
Filters filters = property.getAnnotation( Filters.class );
if ( filters != null ) {
for (Filter filter : filters.value()) {
if ( hasAssociationTable ) {
collection.addManyToManyFilter( filter.name(), getCondition(filter), filter.deduceAliasInjectionPoints(),
toAliasTableMap(filter.aliases()), toAliasEntityMap(filter.aliases()));
}
else {
collection.addFilter(filter.name(), getCondition(filter), filter.deduceAliasInjectionPoints(),
toAliasTableMap(filter.aliases()), toAliasEntityMap(filter.aliases()));
}
}
}
FilterJoinTable simpleFilterJoinTable = property.getAnnotation( FilterJoinTable.class );
if ( simpleFilterJoinTable != null ) {
if ( hasAssociationTable ) {
collection.addFilter(simpleFilterJoinTable.name(), simpleFilterJoinTable.condition(),
simpleFilterJoinTable.deduceAliasInjectionPoints(),
toAliasTableMap(simpleFilterJoinTable.aliases()), toAliasEntityMap(simpleFilterJoinTable.aliases()));
}
else {
throw new AnnotationException(
"Illegal use of @FilterJoinTable on an association without join table:"
+ StringHelper.qualify( propertyHolder.getPath(), propertyName )
);
}
}
FilterJoinTables filterJoinTables = property.getAnnotation( FilterJoinTables.class );
if ( filterJoinTables != null ) {
for (FilterJoinTable filter : filterJoinTables.value()) {
if ( hasAssociationTable ) {
collection.addFilter(filter.name(), filter.condition(),
filter.deduceAliasInjectionPoints(),
toAliasTableMap(filter.aliases()), toAliasEntityMap(filter.aliases()));
}
else {
throw new AnnotationException(
"Illegal use of @FilterJoinTable on an association without join table:"
+ StringHelper.qualify( propertyHolder.getPath(), propertyName )
);
}
}
}
Where where = property.getAnnotation( Where.class );
String whereClause = where == null ? null : where.clause();
if ( StringHelper.isNotEmpty( whereClause ) ) {
if ( hasAssociationTable ) {
collection.setManyToManyWhere( whereClause );
}
else {
collection.setWhere( whereClause );
}
}
WhereJoinTable whereJoinTable = property.getAnnotation( WhereJoinTable.class );
String whereJoinTableClause = whereJoinTable == null ? null : whereJoinTable.clause();
if ( StringHelper.isNotEmpty( whereJoinTableClause ) ) {
if ( hasAssociationTable ) {
collection.setWhere( whereJoinTableClause );
}
else {
throw new AnnotationException(
"Illegal use of @WhereJoinTable on an association without join table:"
+ StringHelper.qualify( propertyHolder.getPath(), propertyName )
);
}
}
// This cannot happen in annotations since the second fetch is hardcoded to join
// if ( ( ! collection.getManyToManyFilterMap().isEmpty() || collection.getManyToManyWhere() != null ) &&
// collection.getFetchMode() == FetchMode.JOIN &&
// collection.getElement().getFetchMode() != FetchMode.JOIN ) {
// throw new MappingException(
// "association with join table defining filter or where without join fetching " +
// "not valid within collection using join fetching [" + collection.getRole() + "]"
// );
// }
}
private String getCondition(FilterJoinTable filter) {
//set filtering
String name = filter.name();
String cond = filter.condition();
return getCondition( cond, name );
}
private String getCondition(Filter filter) {
//set filtering
String name = filter.name();
String cond = filter.condition();
return getCondition( cond, name );
}
private String getCondition(String cond, String name) {
if ( BinderHelper.isEmptyAnnotationValue( cond ) ) {
cond = buildingContext.getMetadataCollector().getFilterDefinition( name ).getDefaultFilterCondition();
if ( StringHelper.isEmpty( cond ) ) {
throw new AnnotationException(
"no filter condition found for filter " + name + " in "
+ StringHelper.qualify( propertyHolder.getPath(), propertyName )
);
}
}