/
MetadataBuildingProcess.java
1438 lines (1244 loc) · 52.2 KB
/
MetadataBuildingProcess.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2014, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.internal;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.hibernate.AssertionFailure;
import org.hibernate.DuplicateMappingException;
import org.hibernate.EntityMode;
import org.hibernate.MappingException;
import org.hibernate.SessionFactory;
import org.hibernate.annotations.common.util.StringHelper;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
import org.hibernate.boot.spi.CacheRegionDefinition;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.cfg.NamingStrategy;
import org.hibernate.cfg.ObjectNameNormalizer;
import org.hibernate.cfg.annotations.NamedEntityGraphDefinition;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.ResultSetMappingDefinition;
import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.engine.spi.FilterDefinition;
import org.hibernate.engine.spi.NamedQueryDefinition;
import org.hibernate.engine.spi.NamedSQLQueryDefinition;
import org.hibernate.engine.spi.SyntheticAttributeHelper;
import org.hibernate.id.EntityIdentifierNature;
import org.hibernate.id.factory.IdentifierGeneratorFactory;
import org.hibernate.id.factory.spi.MutableIdentifierGeneratorFactory;
import org.hibernate.internal.util.collections.CollectionHelper;
import org.hibernate.internal.util.config.ConfigurationHelper;
import org.hibernate.metamodel.MetadataSources;
import org.hibernate.metamodel.NamedStoredProcedureQueryDefinition;
import org.hibernate.metamodel.SessionFactoryBuilder;
import org.hibernate.metamodel.archive.internal.StandardArchiveDescriptorFactory;
import org.hibernate.metamodel.archive.scan.internal.StandardScanner;
import org.hibernate.metamodel.archive.scan.spi.ClassDescriptor;
import org.hibernate.metamodel.archive.scan.spi.JandexInitializer;
import org.hibernate.metamodel.archive.scan.spi.MappingFileDescriptor;
import org.hibernate.metamodel.archive.scan.spi.PackageDescriptor;
import org.hibernate.metamodel.archive.scan.spi.ScanParameters;
import org.hibernate.metamodel.archive.scan.spi.ScanResult;
import org.hibernate.metamodel.archive.scan.spi.Scanner;
import org.hibernate.metamodel.archive.spi.ArchiveDescriptorFactory;
import org.hibernate.metamodel.internal.binder.Binder;
import org.hibernate.metamodel.reflite.internal.JavaTypeDescriptorRepositoryImpl;
import org.hibernate.metamodel.reflite.spi.JavaTypeDescriptor;
import org.hibernate.metamodel.reflite.spi.JavaTypeDescriptorRepository;
import org.hibernate.metamodel.source.internal.annotations.AnnotationMetadataSourceProcessor;
import org.hibernate.metamodel.source.internal.annotations.JandexAccess;
import org.hibernate.metamodel.source.internal.annotations.JandexAccessImpl;
import org.hibernate.metamodel.source.internal.jandex.Unifier;
import org.hibernate.metamodel.source.internal.jaxb.JaxbEntityMappings;
import org.hibernate.metamodel.source.spi.FilterDefinitionSource;
import org.hibernate.metamodel.source.spi.FilterParameterSource;
import org.hibernate.metamodel.source.spi.IdentifierGeneratorSource;
import org.hibernate.metamodel.source.spi.MappingDefaults;
import org.hibernate.metamodel.source.spi.MetaAttributeContext;
import org.hibernate.metamodel.source.spi.TypeDescriptorSource;
import org.hibernate.metamodel.spi.AdditionalJaxbRootProducer;
import org.hibernate.metamodel.spi.AdditionalJaxbRootProducer.AdditionalJaxbRootProducerContext;
import org.hibernate.metamodel.spi.BindingContext;
import org.hibernate.metamodel.spi.ClassLoaderAccess;
import org.hibernate.metamodel.spi.InFlightMetadataCollector;
import org.hibernate.metamodel.spi.MetadataBuildingOptions;
import org.hibernate.metamodel.spi.MetadataContributor;
import org.hibernate.metamodel.spi.PluralAttributeElementNature;
import org.hibernate.metamodel.spi.TypeContributions;
import org.hibernate.metamodel.spi.TypeContributor;
import org.hibernate.metamodel.spi.binding.AttributeBinding;
import org.hibernate.metamodel.spi.binding.BackRefAttributeBinding;
import org.hibernate.metamodel.spi.binding.EntityBinding;
import org.hibernate.metamodel.spi.binding.EntityIdentifier;
import org.hibernate.metamodel.spi.binding.FetchProfile;
import org.hibernate.metamodel.spi.binding.IdentifierGeneratorDefinition;
import org.hibernate.metamodel.spi.binding.IndexedPluralAttributeBinding;
import org.hibernate.metamodel.spi.binding.ManyToOneAttributeBinding;
import org.hibernate.metamodel.spi.binding.PluralAttributeBinding;
import org.hibernate.metamodel.spi.binding.PluralAttributeIndexBinding;
import org.hibernate.metamodel.spi.binding.PluralAttributeKeyBinding;
import org.hibernate.metamodel.spi.binding.RelationalValueBinding;
import org.hibernate.metamodel.spi.binding.SecondaryTable;
import org.hibernate.metamodel.spi.binding.TypeDefinition;
import org.hibernate.metamodel.spi.domain.Aggregate;
import org.hibernate.metamodel.spi.domain.BasicType;
import org.hibernate.metamodel.spi.domain.Entity;
import org.hibernate.metamodel.spi.domain.Hierarchical;
import org.hibernate.metamodel.spi.domain.MappedSuperclass;
import org.hibernate.metamodel.spi.domain.SingularAttribute;
import org.hibernate.metamodel.spi.domain.Type;
import org.hibernate.metamodel.spi.relational.Database;
import org.hibernate.metamodel.spi.relational.Identifier;
import org.hibernate.metamodel.spi.relational.Schema;
import org.hibernate.metamodel.spi.relational.Table;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.BasicTypeRegistry;
import org.hibernate.type.TypeFactory;
import org.hibernate.type.TypeResolver;
import org.hibernate.usertype.CompositeUserType;
import org.hibernate.usertype.UserType;
import org.hibernate.xml.spi.BindResult;
import org.jboss.jandex.DotName;
import org.jboss.jandex.IndexView;
import org.jboss.logging.Logger;
/**
* Represents the process of building a Metadata object. The main entry point is the
* static {@link #build}
*
* @author Steve Ebersole
*/
public class MetadataBuildingProcess {
private static final Logger log = Logger.getLogger( MetadataBuildingProcess.class );
public static MetadataImpl build(MetadataSources sources, final MetadataBuildingOptions options) {
final ClassLoaderAccess classLoaderAccess = new ClassLoaderAccessImpl(
options.getTempClassLoader(),
options.getServiceRegistry()
);
final JandexInitManager jandexInitializer = buildJandexInitializer( options, classLoaderAccess );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// scanning - Jandex initialization and source discovery
if ( options.getScanEnvironment() != null ) {
final Scanner scanner = buildScanner( options, classLoaderAccess );
final ScanResult scanResult = scanner.scan(
options.getScanEnvironment(),
options.getScanOptions(),
new ScanParameters() {
@Override
public JandexInitializer getJandexInitializer() {
return jandexInitializer;
}
}
);
// Add to the MetadataSources any classes/packages/mappings discovered during scanning
addScanResultsToSources( scanResult, sources );
}
// todo : add options.getScanEnvironment().getExplicitlyListedClassNames() to jandex?
// ^^ - another option is to make sure that they are added to sources
if ( !jandexInitializer.wasIndexSupplied() ) {
// If the Jandex Index(View) was supplied, we consider that supplied
// one "complete".
// Here though we were NOT supplied an index; in this case we want to
// additionally ensure that any-and-all "known" classes are added to
// the index we are building
sources.indexKnownClasses( jandexInitializer );
}
// It's necessary to delay the binding of XML resources until now. ClassLoaderAccess is needed for
// reflection, etc.
sources.buildBindResults( classLoaderAccess );
final IndexView jandexView = augmentJandexFromMappings( jandexInitializer.buildIndex(), sources, options );
final BasicTypeRegistry basicTypeRegistry = handleTypes( options );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// prep to start handling binding in earnest
final MappingDefaultsImpl mappingDefaults = new MappingDefaultsImpl( options );
final JandexAccessImpl jandexAccess = new JandexAccessImpl(
jandexView,
classLoaderAccess
);
final JavaTypeDescriptorRepository javaTypeDescriptorRepository = new JavaTypeDescriptorRepositoryImpl(
jandexAccess,
classLoaderAccess
);
final InFlightMetadataCollectorImpl metadataCollector = new InFlightMetadataCollectorImpl(
options,
new TypeResolver( basicTypeRegistry, new TypeFactory() )
);
final RootBindingContextImpl rootBindingContext = new RootBindingContextImpl(
options,
mappingDefaults,
javaTypeDescriptorRepository,
jandexAccess,
classLoaderAccess,
metadataCollector
);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Set up the processors and start binding
// NOTE : this becomes even more simplified after we move purely
// to unified model
final AnnotationMetadataSourceProcessor processor = new AnnotationMetadataSourceProcessor(
rootBindingContext, jandexView );
processTypeDefinitions( processor, rootBindingContext );
processFilterDefinitions( processor, rootBindingContext );
processIdentifierGenerators( processor, rootBindingContext );
processMappings( processor, rootBindingContext );
bindMappingDependentMetadata( processor, rootBindingContext );
final ClassLoaderService classLoaderService = options.getServiceRegistry().getService( ClassLoaderService.class );
for ( MetadataContributor contributor : classLoaderService.loadJavaServices( MetadataContributor.class ) ) {
contributor.contribute( metadataCollector, jandexView );
}
final List<BindResult> bindResults = new ArrayList<BindResult>();
final AdditionalJaxbRootProducerContext jaxbRootProducerContext = new AdditionalJaxbRootProducerContext() {
@Override
public IndexView getJandexIndex() {
return jandexView;
}
@Override
public StandardServiceRegistry getServiceRegistry() {
return options.getServiceRegistry();
}
};
for ( AdditionalJaxbRootProducer producer : classLoaderService.loadJavaServices( AdditionalJaxbRootProducer.class ) ) {
bindResults.addAll( producer.produceRoots( metadataCollector, jaxbRootProducerContext ) );
}
secondPass( rootBindingContext );
return metadataCollector.buildMetadataInstance();
}
private static JandexInitManager buildJandexInitializer(
MetadataBuildingOptions options,
ClassLoaderAccess classLoaderAccess) {
final boolean autoIndexMembers = ConfigurationHelper.getBoolean(
org.hibernate.cfg.AvailableSettings.ENABLE_AUTO_INDEX_MEMBER_TYPES,
options.getServiceRegistry().getService( ConfigurationService.class ).getSettings(),
false
);
return new JandexInitManager( options.getJandexView(), classLoaderAccess, autoIndexMembers );
}
private static final Class[] SINGLE_ARG = new Class[] { ArchiveDescriptorFactory.class };
private static Scanner buildScanner(MetadataBuildingOptions options, ClassLoaderAccess classLoaderAccess) {
final Object scannerSetting = options.getScanner();
final ArchiveDescriptorFactory archiveDescriptorFactory = options.getArchiveDescriptorFactory();
if ( scannerSetting == null ) {
// No custom Scanner specified, use the StandardScanner
if ( archiveDescriptorFactory == null ) {
return new StandardScanner();
}
else {
return new StandardScanner( archiveDescriptorFactory );
}
}
else {
if ( Scanner.class.isInstance( scannerSetting ) ) {
if ( archiveDescriptorFactory != null ) {
throw new IllegalStateException(
"A Scanner instance and an ArchiveDescriptorFactory were both specified; please " +
"specify one or the other, or if you need to supply both, Scanner class to use " +
"(assuming it has a constructor accepting a ArchiveDescriptorFactory). " +
"Alternatively, just pass the ArchiveDescriptorFactory during your own " +
"Scanner constructor assuming it is statically known."
);
}
return (Scanner) scannerSetting;
}
final Class<? extends Scanner> scannerImplClass;
if ( Class.class.isInstance( scannerSetting ) ) {
scannerImplClass = (Class<? extends Scanner>) scannerSetting;
}
else {
scannerImplClass = classLoaderAccess.classForName( scannerSetting.toString() );
}
if ( archiveDescriptorFactory != null ) {
// find the single-arg constructor - its an error if none exists
try {
final Constructor<? extends Scanner> constructor = scannerImplClass.getConstructor( SINGLE_ARG );
try {
return constructor.newInstance( archiveDescriptorFactory );
}
catch (Exception e) {
throw new IllegalStateException(
"Error trying to instantiate custom specified Scanner [" +
scannerImplClass.getName() + "]",
e
);
}
}
catch (NoSuchMethodException e) {
throw new IllegalArgumentException(
"Configuration named a custom Scanner and a custom ArchiveDescriptorFactory, but " +
"Scanner impl did not define a constructor accepting ArchiveDescriptorFactory"
);
}
}
else {
// could be either ctor form...
// find the single-arg constructor - its an error if none exists
try {
final Constructor<? extends Scanner> constructor = scannerImplClass.getConstructor( SINGLE_ARG );
try {
return constructor.newInstance( StandardArchiveDescriptorFactory.INSTANCE );
}
catch (Exception e) {
throw new IllegalStateException(
"Error trying to instantiate custom specified Scanner [" +
scannerImplClass.getName() + "]",
e
);
}
}
catch (NoSuchMethodException e) {
try {
final Constructor<? extends Scanner> constructor = scannerImplClass.getConstructor();
try {
return constructor.newInstance();
}
catch (Exception e2) {
throw new IllegalStateException(
"Error trying to instantiate custom specified Scanner [" +
scannerImplClass.getName() + "]",
e2
);
}
}
catch (NoSuchMethodException ignore) {
throw new IllegalArgumentException(
"Configuration named a custom Scanner, but we were unable to locate " +
"an appropriate constructor"
);
}
}
}
}
}
private static void addScanResultsToSources(ScanResult scanResult, MetadataSources sources) {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Add mapping files found as a result of scanning
for ( MappingFileDescriptor mappingFileDescriptor : scanResult.getLocatedMappingFiles() ) {
final InputStream stream = mappingFileDescriptor.getStreamAccess().accessInputStream();
try {
sources.addInputStream( stream );
}
finally {
try {
stream.close();
}
catch ( IOException ignore ) {
log.trace( "Was unable to close input stream" );
}
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Add packages found as a result of scanning
for ( PackageDescriptor packageDescriptor : scanResult.getLocatedPackages() ) {
sources.addPackage( packageDescriptor.getName() );
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Add classes found as a result of scanning
for ( ClassDescriptor classDescriptor : scanResult.getLocatedClasses() ) {
sources.addAnnotatedClassName( classDescriptor.getName() );
}
}
private static IndexView augmentJandexFromMappings(
IndexView baseJandexIndex,
MetadataSources sources,
MetadataBuildingOptions options) {
final List<BindResult<JaxbEntityMappings>> jpaXmlBindings = new ArrayList<BindResult<JaxbEntityMappings>>();
for ( BindResult bindResult : sources.getBindResultList() ) {
if ( JaxbEntityMappings.class.isInstance( bindResult.getRoot() ) ) {
// todo : this will be checked after hbm transformation is in place.
//noinspection unchecked
jpaXmlBindings.add( bindResult );
}
}
return Unifier.unify( baseJandexIndex, jpaXmlBindings, options.getServiceRegistry() );
}
private static BasicTypeRegistry handleTypes(MetadataBuildingOptions options) {
final ClassLoaderService classLoaderService = options.getServiceRegistry().getService( ClassLoaderService.class );
// ultimately this needs to change a little bit to account for HHH-7792
final BasicTypeRegistry basicTypeRegistry = new BasicTypeRegistry();
final TypeContributions typeContributions = new TypeContributions() {
@Override
public void contributeType(org.hibernate.type.BasicType type) {
basicTypeRegistry.register( type );
}
@Override
public void contributeType(UserType type, String[] keys) {
basicTypeRegistry.register( type, keys );
}
@Override
public void contributeType(CompositeUserType type, String[] keys) {
basicTypeRegistry.register( type, keys );
}
};
// add Dialect contributed types
final Dialect dialect = options.getServiceRegistry().getService( JdbcServices.class ).getDialect();
dialect.contributeTypes( typeContributions, options.getServiceRegistry() );
// add TypeContributor contributed types.
for ( TypeContributor contributor : classLoaderService.loadJavaServices( TypeContributor.class ) ) {
contributor.contribute( typeContributions, options.getServiceRegistry() );
}
// add explicit application registered types
for ( org.hibernate.type.BasicType basicType : options.getBasicTypeRegistrations() ) {
basicTypeRegistry.register( basicType );
}
return basicTypeRegistry;
}
private static void processTypeDefinitions(
AnnotationMetadataSourceProcessor processor,
RootBindingContextImpl bindingContext) {
final ClassLoaderService cls = bindingContext.getBuildingOptions().getServiceRegistry().getService( ClassLoaderService.class );
for ( TypeDescriptorSource typeDescriptorSource : processor.extractTypeDefinitionSources() ) {
bindingContext.getMetadataCollector().addTypeDefinition(
new TypeDefinition(
typeDescriptorSource.getName(),
cls.classForName( typeDescriptorSource.getTypeImplementationClassName() ),
typeDescriptorSource.getRegistrationKeys(),
typeDescriptorSource.getParameters()
)
);
}
}
private static void processFilterDefinitions(
AnnotationMetadataSourceProcessor processor,
RootBindingContextImpl bindingContext) {
for ( FilterDefinitionSource filterDefinitionSource : processor.extractFilterDefinitionSources() ) {
bindingContext.getMetadataCollector().addFilterDefinition(
new FilterDefinition(
filterDefinitionSource.getName(),
filterDefinitionSource.getCondition(),
resolveFilterDefinitionParamType(
filterDefinitionSource.getParameterSources(),
bindingContext
)
)
);
}
}
private static Map<String, org.hibernate.type.Type> resolveFilterDefinitionParamType(
Iterable<FilterParameterSource> filterParameterSources,
RootBindingContextImpl bindingContext){
if ( CollectionHelper.isEmpty( filterParameterSources ) ) {
return Collections.emptyMap();
}
Map<String, org.hibernate.type.Type> params = new HashMap<String, org.hibernate.type.Type>( );
for(final FilterParameterSource parameterSource : filterParameterSources){
final String name = parameterSource.getParameterName();
final String typeName = parameterSource.getParameterValueTypeName();
final org.hibernate.type.Type type = bindingContext.getMetadataCollector().getTypeResolver().heuristicType(
typeName
);
params.put( name, type );
}
return params;
}
private static void processIdentifierGenerators(
AnnotationMetadataSourceProcessor processor,
RootBindingContextImpl bindingContext) {
for ( IdentifierGeneratorSource identifierGeneratorSource : processor.extractGlobalIdentifierGeneratorSources() ) {
bindingContext.getMetadataCollector().addIdGenerator(
new IdentifierGeneratorDefinition(
identifierGeneratorSource.getGeneratorName(),
identifierGeneratorSource.getGeneratorImplementationName(),
identifierGeneratorSource.getParameters()
)
);
}
}
private static void processMappings(
AnnotationMetadataSourceProcessor processor,
RootBindingContextImpl bindingContext) {
final Binder binder = new Binder( bindingContext );
// Add all hierarchies first, before binding.
binder.addEntityHierarchies( processor.extractEntityHierarchies() );
binder.bindEntityHierarchies();
}
private static void bindMappingDependentMetadata(
AnnotationMetadataSourceProcessor processor,
RootBindingContextImpl bindingContext) {
// Create required back references, which are required for one-to-many associations with key bindings that are non-inverse,
// non-nullable, and unidirectional
for ( PluralAttributeBinding pluralAttributeBinding : bindingContext.getMetadataCollector().getCollectionBindings() ) {
// Find one-to-many associations with key bindings that are non-inverse and non-nullable
PluralAttributeKeyBinding keyBinding = pluralAttributeBinding.getPluralAttributeKeyBinding();
if ( keyBinding.isInverse() || keyBinding.isNullable() ||
pluralAttributeBinding.getPluralAttributeElementBinding().getNature() !=
PluralAttributeElementNature.ONE_TO_MANY ) {
continue;
}
// Ensure this isn't a bidirectional association by ensuring FK columns don't match relational columns of any
// many-to-one on opposite side
EntityBinding referencedEntityBinding = bindingContext.getMetadataCollector().getEntityBinding(
pluralAttributeBinding.getPluralAttributeElementBinding()
.getHibernateTypeDescriptor()
.getResolvedTypeMapping()
.getName()
);
List<RelationalValueBinding> keyValueBindings = keyBinding.getRelationalValueBindings();
boolean bidirectional = false;
for ( AttributeBinding attributeBinding : referencedEntityBinding.attributeBindings() ) {
if ( !(attributeBinding instanceof ManyToOneAttributeBinding ) ) {
continue;
}
// Check if the opposite many-to-one attribute binding references the one-to-many attribute binding being processed
ManyToOneAttributeBinding manyToOneAttributeBinding = ( ManyToOneAttributeBinding ) attributeBinding;
if ( !manyToOneAttributeBinding.getReferencedEntityBinding().equals(
pluralAttributeBinding.getContainer().seekEntityBinding() ) ) {
continue;
}
// Check if the many-to-one attribute binding's columns match the one-to-many attribute binding's FK columns
// (meaning this is a bidirectional association, and no back reference should be created)
List<RelationalValueBinding> valueBindings = manyToOneAttributeBinding.getRelationalValueBindings();
if ( keyValueBindings.size() != valueBindings.size() ) {
continue;
}
bidirectional = true;
for ( int ndx = valueBindings.size(); --ndx >= 0; ) {
if ( keyValueBindings.get(ndx) != valueBindings.get( ndx ) ) {
bidirectional = false;
break;
}
}
if ( bidirectional ) {
break;
}
}
if ( bidirectional ) continue;
// Create the synthetic back reference attribute
SingularAttribute syntheticAttribute =
referencedEntityBinding.getEntity().createSyntheticSingularAttribute(
SyntheticAttributeHelper.createBackRefAttributeName(
pluralAttributeBinding.getAttribute()
.getRole()
) );
// Create the back reference attribute binding.
BackRefAttributeBinding backRefAttributeBinding = referencedEntityBinding.makeBackRefAttributeBinding(
syntheticAttribute, pluralAttributeBinding, false
);
backRefAttributeBinding.getHibernateTypeDescriptor().copyFrom( keyBinding.getHibernateTypeDescriptor() );
backRefAttributeBinding.getAttribute().resolveType(
keyBinding.getReferencedAttributeBinding().getAttribute().getSingularAttributeType() );
if ( pluralAttributeBinding.hasIndex() ) {
SingularAttribute syntheticIndexAttribute =
referencedEntityBinding.getEntity().createSyntheticSingularAttribute(
SyntheticAttributeHelper.createIndexBackRefAttributeName( pluralAttributeBinding.getAttribute().getRole() ) );
BackRefAttributeBinding indexBackRefAttributeBinding = referencedEntityBinding.makeBackRefAttributeBinding(
syntheticIndexAttribute, pluralAttributeBinding, true
);
final PluralAttributeIndexBinding indexBinding =
( (IndexedPluralAttributeBinding) pluralAttributeBinding ).getPluralAttributeIndexBinding();
indexBackRefAttributeBinding.getHibernateTypeDescriptor().copyFrom(
indexBinding.getHibernateTypeDescriptor()
);
indexBackRefAttributeBinding.getAttribute().resolveType(
indexBinding.getPluralAttributeIndexType()
);
}
}
processor.processMappingDependentMetadata();
}
private static void secondPass(RootBindingContextImpl bindingContext) {
// This must be done outside of Table, rather than statically, to ensure
// deterministic alias names. See HHH-2448.
int uniqueInteger = 0;
for ( Schema schema : bindingContext.getMetadataCollector().getDatabase().getSchemas() ) {
for ( Table table : schema.getTables() ) {
table.setTableNumber( uniqueInteger++ );
}
}
if ( bindingContext.getBuildingOptions().getCacheRegionDefinitions() == null
|| bindingContext.getBuildingOptions().getCacheRegionDefinitions().isEmpty() ) {
return;
}
for ( CacheRegionDefinition override : bindingContext.getBuildingOptions().getCacheRegionDefinitions() ) {
final String role = override.getRole();
// NOTE : entity region overrides are already handled when building the
if ( override.getRegionType() == CacheRegionDefinition.CacheRegionType.ENTITY ) {
// final EntityBinding entityBinding = bindingContext.getMetadataCollector().getEntityBinding( role );
// if ( entityBinding != null ) {
// entityBinding.getHierarchyDetails().getCaching().setRegion( override.getRegion() );
// entityBinding.getHierarchyDetails().getCaching().setAccessType( AccessType.fromExternalName( override.getUsage() ) );
// entityBinding.getHierarchyDetails().getCaching().setCacheLazyProperties( override.isCacheLazy() );
// }
// else {
// //logging?
// throw new MappingException( "Can't find entitybinding for role " + role +" to apply cache configuration" );
// }
}
else if ( override.getRegionType() == CacheRegionDefinition.CacheRegionType.COLLECTION ) {
String collectionRole = role;
if ( !role.contains( "#" ) ) {
final int pivotPosition = role.lastIndexOf( '.' );
if ( pivotPosition > 0 ) {
collectionRole = role.substring( 0, pivotPosition ) + '#' + role.substring( pivotPosition + 1 );
}
}
final PluralAttributeBinding pluralAttributeBinding = bindingContext.getMetadataCollector().getCollection(
collectionRole
);
if ( pluralAttributeBinding != null ) {
pluralAttributeBinding.getCaching().overlay( override );
}
else {
//logging?
throw new MappingException( "Can't find entitybinding for role " + role +" to apply cache configuration" );
}
}
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// BindingContext impl
public static class RootBindingContextImpl implements BindingContext {
private final MetadataBuildingOptions options;
private final MappingDefaults mappingDefaults;
private final JavaTypeDescriptorRepository javaTypeDescriptorRepository;
private final JandexAccessImpl jandexAccess;
private final ClassLoaderAccess classLoaderAccess;
private final InFlightMetadataCollectorImpl metadataCollector;
private final MetaAttributeContext globalMetaAttributeContext = new MetaAttributeContext();
public RootBindingContextImpl(
MetadataBuildingOptions options,
MappingDefaultsImpl mappingDefaults,
JavaTypeDescriptorRepository javaTypeDescriptorRepository,
JandexAccessImpl jandexAccess,
ClassLoaderAccess classLoaderAccess,
InFlightMetadataCollectorImpl metadataCollector) {
this.options = options;
this.mappingDefaults = mappingDefaults;
this.javaTypeDescriptorRepository = javaTypeDescriptorRepository;
this.jandexAccess = jandexAccess;
this.classLoaderAccess = classLoaderAccess;
this.metadataCollector = metadataCollector;
}
@Override
public MetadataBuildingOptions getBuildingOptions() {
return options;
}
@Override
public MappingDefaults getMappingDefaults() {
return mappingDefaults;
}
@Override
public JandexAccess getJandexAccess() {
return jandexAccess;
}
@Override
public JavaTypeDescriptorRepository getJavaTypeDescriptorRepository() {
return javaTypeDescriptorRepository;
}
@Override
public String qualifyClassName(String name) {
// see comments on MappingDefaultsImpl.getPackageName()
return name;
}
@Override
public InFlightMetadataCollector getMetadataCollector() {
return metadataCollector;
}
@Override
public MetaAttributeContext getGlobalMetaAttributeContext() {
return globalMetaAttributeContext;
}
@Override
public ServiceRegistry getServiceRegistry() {
return options.getServiceRegistry();
}
@Override
public ClassLoaderAccess getClassLoaderAccess() {
return classLoaderAccess;
}
@Override
public boolean quoteIdentifiersInContext() {
return options.getDatabaseDefaults().isGloballyQuotedIdentifiers();
}
@Override
public JavaTypeDescriptor typeDescriptor(String name) {
return javaTypeDescriptorRepository.getType( javaTypeDescriptorRepository.buildName( qualifyClassName( name ) ) );
}
private final Map<JavaTypeDescriptor, Type> domainModelTypes = new HashMap<JavaTypeDescriptor, Type>();
@Override
public BasicType buildBasicDomainType(JavaTypeDescriptor typeDescriptor) {
final BasicType type = new BasicType( typeDescriptor.getName().toString(), typeDescriptor );
final Type old = domainModelTypes.put( typeDescriptor, type );
if ( old != null ) {
log.debugf( "Building basic domain type overrode existing entry: %s", old );
}
return type;
}
@Override
public MappedSuperclass buildMappedSuperclassDomainType(JavaTypeDescriptor typeDescriptor) {
return buildMappedSuperclassDomainType( typeDescriptor, null );
}
@Override
public MappedSuperclass buildMappedSuperclassDomainType(
JavaTypeDescriptor typeDescriptor,
Hierarchical superType) {
final MappedSuperclass type = new MappedSuperclass( typeDescriptor, superType );
final Type old = domainModelTypes.put( typeDescriptor, type );
if ( old != null ) {
log.debugf( "Building MappedSuperclass domain type overrode existing entry: %s", old );
}
return type;
}
@Override
public Aggregate buildComponentDomainType(JavaTypeDescriptor typeDescriptor) {
return buildComponentDomainType( typeDescriptor, null );
}
@Override
public Aggregate buildComponentDomainType(
JavaTypeDescriptor typeDescriptor
, Hierarchical superType) {
final Aggregate type = new Aggregate( typeDescriptor, superType );
final Type old = domainModelTypes.put( typeDescriptor, type );
if ( old != null ) {
log.debugf( "Building Aggregate domain type overrode existing entry: %s", old );
}
return type;
}
@Override
public Entity buildEntityDomainType(JavaTypeDescriptor typeDescriptor) {
return buildEntityDomainType( typeDescriptor, null );
}
@Override
public Entity buildEntityDomainType(
JavaTypeDescriptor typeDescriptor,
Hierarchical superType) {
final Entity type = new Entity( typeDescriptor, superType );
final Type old = domainModelTypes.put( typeDescriptor, type );
if ( old != null ) {
log.debugf( "Building Entity domain type overrode existing entry: %s", old );
}
return type;
}
@Override
public Type locateDomainType(JavaTypeDescriptor typeDescriptor) {
return domainModelTypes.get( typeDescriptor );
}
@Override
public Type locateOrBuildDomainType(JavaTypeDescriptor typeDescriptor, boolean isAggregate) {
Type type = domainModelTypes.get( typeDescriptor );
if ( type == null ) {
type = isAggregate
? buildComponentDomainType( typeDescriptor )
: buildBasicDomainType( typeDescriptor );
}
return type;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// BindingContext deprecated impls
@Override
public Type makeDomainType(String className) {
return buildBasicDomainType( typeDescriptor( className ) );
}
@Override
public Type makeDomainType(DotName typeName) {
return buildBasicDomainType( typeDescriptor( typeName.toString() ) );
}
}
public static class MappingDefaultsImpl implements MappingDefaults {
private static final String DEFAULT_IDENTIFIER_COLUMN_NAME = "id";
private static final String DEFAULT_TENANT_IDENTIFIER_COLUMN_NAME = "tenant_id";
private static final String DEFAULT_DISCRIMINATOR_COLUMN_NAME = "class";
private static final String DEFAULT_CASCADE = "none";
private static final String DEFAULT_PROPERTY_ACCESS = "property";
private final MetadataBuildingOptions options;
public MappingDefaultsImpl(MetadataBuildingOptions options) {
this.options = options;
}
@Override
public String getPackageName() {
// default package name is only relevant within processing XML mappings. Here
// at the root, there is no default
return null;
}
@Override
public String getSchemaName() {
return options.getDatabaseDefaults().getDefaultSchemaName();
}
@Override
public String getCatalogName() {
return options.getDatabaseDefaults().getDefaultCatalogName();
}
@Override
public String getIdColumnName() {
return DEFAULT_IDENTIFIER_COLUMN_NAME;
}
@Override
public String getTenantIdColumnName() {
return DEFAULT_TENANT_IDENTIFIER_COLUMN_NAME;
}
@Override
public String getDiscriminatorColumnName() {
return DEFAULT_DISCRIMINATOR_COLUMN_NAME;
}
@Override
public String getCascadeStyle() {
return DEFAULT_CASCADE;
}
@Override
public String getPropertyAccessorName() {
return DEFAULT_PROPERTY_ACCESS;
}
@Override
public boolean areAssociationsLazy() {
return true;
}
@Override
public AccessType getCacheAccessType() {
return options.getDefaultCacheAccessType();
}
}
public static class InFlightMetadataCollectorImpl implements InFlightMetadataCollector {
private final MetadataBuildingOptions options;
private final TypeResolver typeResolver;
private final UUID uuid;
private final Database database;
private final ObjectNameNormalizer nameNormalizer;
private final MutableIdentifierGeneratorFactory identifierGeneratorFactory;
private final Map<String, TypeDefinition> typeDefinitionMap = new HashMap<String, TypeDefinition>();
private final Map<String, FilterDefinition> filterDefinitionMap = new HashMap<String, FilterDefinition>();
private final Map<String, EntityBinding> entityBindingMap =
new HashMap<String, EntityBinding>();
private final Map<String, PluralAttributeBinding> collectionBindingMap =
new HashMap<String, PluralAttributeBinding>();
private final Map<String, FetchProfile> fetchProfiles =
new HashMap<String, FetchProfile>();
private final Map<String, String> imports =
new HashMap<String, String>();
private final Map<String, IdentifierGeneratorDefinition> idGenerators =
new HashMap<String, IdentifierGeneratorDefinition>();
private final Map<String, NamedQueryDefinition> namedQueryDefs =
new HashMap<String, NamedQueryDefinition>();
private final Map<String, NamedSQLQueryDefinition> namedNativeQueryDefs =
new HashMap<String, NamedSQLQueryDefinition>();
private final Map<String, NamedStoredProcedureQueryDefinition> namedStoredProcedureQueryDefinitionMap =
new HashMap<String, NamedStoredProcedureQueryDefinition>();
private final Map<String, ResultSetMappingDefinition> resultSetMappings =
new HashMap<String, ResultSetMappingDefinition>();
private final Map<String, NamedEntityGraphDefinition> namedEntityGraphMap =
new HashMap<String, NamedEntityGraphDefinition>( );
private final Map<Identifier, SecondaryTable> secondaryTableMap =
new HashMap<Identifier, SecondaryTable>();
public InFlightMetadataCollectorImpl(MetadataBuildingOptions options, TypeResolver typeResolver) {
this.uuid = UUID.randomUUID();
this.options = options;
this.typeResolver = typeResolver;
this.database = new Database(
options.getDatabaseDefaults(),
options.getServiceRegistry().getService( JdbcServices.class ).getJdbcEnvironment()
);
this.nameNormalizer = new ObjectNameNormalizer() {
@Override
protected NamingStrategy getNamingStrategy() {
return InFlightMetadataCollectorImpl.this.options.getNamingStrategy();
}
@Override
protected boolean isUseQuotedIdentifiersGlobally() {
return InFlightMetadataCollectorImpl.this.options.getDatabaseDefaults().isGloballyQuotedIdentifiers();
}
};
this.identifierGeneratorFactory = options.getServiceRegistry().getService( MutableIdentifierGeneratorFactory.class );
}
@Override
public Database getDatabase() {
return database;
}
@Override
public TypeResolver getTypeResolver() {
return typeResolver;
}
@Override
public ObjectNameNormalizer getObjectNameNormalizer() {
return nameNormalizer;
}
@Override