-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
InFlightMetadataCollectorImpl.java
2271 lines (1932 loc) · 74.3 KB
/
InFlightMetadataCollectorImpl.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.boot.internal;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import javax.persistence.AttributeConverter;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.MapsId;
import org.hibernate.AnnotationException;
import org.hibernate.AssertionFailure;
import org.hibernate.DuplicateMappingException;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.SessionFactory;
import org.hibernate.annotations.AnyMetaDef;
import org.hibernate.annotations.common.reflection.XClass;
import org.hibernate.boot.CacheRegionDefinition;
import org.hibernate.boot.SessionFactoryBuilder;
import org.hibernate.boot.model.IdentifierGeneratorDefinition;
import org.hibernate.boot.model.TypeDefinition;
import org.hibernate.boot.model.convert.internal.AttributeConverterManager;
import org.hibernate.boot.model.convert.internal.ClassBasedConverterDescriptor;
import org.hibernate.boot.model.convert.spi.ConverterAutoApplyHandler;
import org.hibernate.boot.model.convert.spi.ConverterDescriptor;
import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.naming.ImplicitForeignKeyNameSource;
import org.hibernate.boot.model.naming.ImplicitIndexNameSource;
import org.hibernate.boot.model.naming.ImplicitUniqueKeyNameSource;
import org.hibernate.boot.model.relational.AuxiliaryDatabaseObject;
import org.hibernate.boot.model.relational.Database;
import org.hibernate.boot.model.relational.ExportableProducer;
import org.hibernate.boot.model.relational.Namespace;
import org.hibernate.boot.model.relational.QualifiedTableName;
import org.hibernate.boot.model.source.internal.ImplicitColumnNamingSecondPass;
import org.hibernate.boot.model.source.spi.LocalMetadataBuildingContext;
import org.hibernate.boot.spi.BootstrapContext;
import org.hibernate.boot.spi.InFlightMetadataCollector;
import org.hibernate.boot.spi.MetadataBuildingContext;
import org.hibernate.boot.spi.MetadataBuildingOptions;
import org.hibernate.boot.spi.NaturalIdUniqueKeyBinder;
import org.hibernate.cfg.AnnotatedClassType;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.CreateKeySecondPass;
import org.hibernate.cfg.FkSecondPass;
import org.hibernate.cfg.IdGeneratorResolverSecondPass;
import org.hibernate.cfg.JPAIndexHolder;
import org.hibernate.cfg.PropertyData;
import org.hibernate.cfg.QuerySecondPass;
import org.hibernate.cfg.RecoverableException;
import org.hibernate.cfg.SecondPass;
import org.hibernate.cfg.SecondaryTableSecondPass;
import org.hibernate.cfg.SetSimpleValueTypeSecondPass;
import org.hibernate.cfg.UniqueConstraintHolder;
import org.hibernate.cfg.annotations.NamedEntityGraphDefinition;
import org.hibernate.cfg.annotations.NamedProcedureCallDefinition;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.function.SQLFunction;
import org.hibernate.engine.ResultSetMappingDefinition;
import org.hibernate.engine.spi.FilterDefinition;
import org.hibernate.engine.spi.NamedQueryDefinition;
import org.hibernate.engine.spi.NamedSQLQueryDefinition;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.id.factory.IdentifierGeneratorFactory;
import org.hibernate.id.factory.spi.MutableIdentifierGeneratorFactory;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.SessionFactoryImpl;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.collections.CollectionHelper;
import org.hibernate.mapping.Collection;
import org.hibernate.mapping.Column;
import org.hibernate.mapping.DenormalizedTable;
import org.hibernate.mapping.FetchProfile;
import org.hibernate.mapping.ForeignKey;
import org.hibernate.mapping.IdentifierCollection;
import org.hibernate.mapping.Index;
import org.hibernate.mapping.Join;
import org.hibernate.mapping.KeyValue;
import org.hibernate.mapping.MappedSuperclass;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
import org.hibernate.mapping.RootClass;
import org.hibernate.mapping.SimpleValue;
import org.hibernate.mapping.Table;
import org.hibernate.mapping.UniqueKey;
import org.hibernate.query.spi.NamedQueryRepository;
import org.hibernate.type.Type;
import org.hibernate.type.TypeResolver;
import org.hibernate.type.spi.TypeConfiguration;
/**
* The implementation of the in-flight Metadata collector contract.
*
* The usage expectation is that this class is used until all Metadata info is
* collected and then {@link #buildMetadataInstance} is called to generate
* the complete (and immutable) Metadata object.
*
* @author Steve Ebersole
*/
public class InFlightMetadataCollectorImpl implements InFlightMetadataCollector {
private static final CoreMessageLogger log = CoreLogging.messageLogger( InFlightMetadataCollectorImpl.class );
private final BootstrapContext bootstrapContext;
private final MetadataBuildingOptions options;
private final AttributeConverterManager attributeConverterManager = new AttributeConverterManager();
private final UUID uuid;
private final MutableIdentifierGeneratorFactory identifierGeneratorFactory;
private final Map<String,PersistentClass> entityBindingMap = new HashMap<>();
private final Map<String,Collection> collectionBindingMap = new HashMap<>();
private final Map<String, TypeDefinition> typeDefinitionMap = new HashMap<>();
private final Map<String, FilterDefinition> filterDefinitionMap = new HashMap<>();
private final Map<String, String> imports = new HashMap<>();
private Database database;
private final Map<String, NamedQueryDefinition> namedQueryMap = new HashMap<>();
private final Map<String, NamedSQLQueryDefinition> namedNativeQueryMap = new HashMap<>();
private final Map<String, NamedProcedureCallDefinition> namedProcedureCallMap = new HashMap<>();
private final Map<String, ResultSetMappingDefinition> sqlResultSetMappingMap = new HashMap<>();
private final Map<String, NamedEntityGraphDefinition> namedEntityGraphMap = new HashMap<>();
private final Map<String, FetchProfile> fetchProfileMap = new HashMap<>();
private final Map<String, IdentifierGeneratorDefinition> idGeneratorDefinitionMap = new HashMap<>();
private Map<String, SQLFunction> sqlFunctionMap;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// All the annotation-processing-specific state :(
private final Set<String> defaultIdentifierGeneratorNames = new HashSet<>();
private final Set<String> defaultNamedQueryNames = new HashSet<>();
private final Set<String> defaultNamedNativeQueryNames = new HashSet<>();
private final Set<String> defaultSqlResultSetMappingNames = new HashSet<>();
private final Set<String> defaultNamedProcedureNames = new HashSet<>();
private Map<String, AnyMetaDef> anyMetaDefs;
private Map<Class, MappedSuperclass> mappedSuperClasses;
private Map<XClass, Map<String, PropertyData>> propertiesAnnotatedWithMapsId;
private Map<XClass, Map<String, PropertyData>> propertiesAnnotatedWithIdAndToOne;
private Map<String, String> mappedByResolver;
private Map<String, String> propertyRefResolver;
private Set<DelayedPropertyReferenceHandler> delayedPropertyReferenceHandlers;
private Map<Table, List<UniqueConstraintHolder>> uniqueConstraintHoldersByTable;
private Map<Table, List<JPAIndexHolder>> jpaIndexHoldersByTable;
public InFlightMetadataCollectorImpl(
BootstrapContext bootstrapContext,
MetadataBuildingOptions options) {
this.bootstrapContext = bootstrapContext;
this.uuid = UUID.randomUUID();
this.options = options;
this.identifierGeneratorFactory = options.getServiceRegistry()
.getService( MutableIdentifierGeneratorFactory.class );
for ( Map.Entry<String, SQLFunction> sqlFunctionEntry : bootstrapContext.getSqlFunctions().entrySet() ) {
if ( sqlFunctionMap == null ) {
// we need this to be a ConcurrentHashMap for the one we ultimately pass along to the SF
// but is this the reference that gets passed along?
sqlFunctionMap = new ConcurrentHashMap<>( 16, .75f, 1 );
}
sqlFunctionMap.put( sqlFunctionEntry.getKey(), sqlFunctionEntry.getValue() );
}
bootstrapContext.getAuxiliaryDatabaseObjectList().forEach( getDatabase()::addAuxiliaryDatabaseObject );
}
@Override
public UUID getUUID() {
return null;
}
@Override
public MetadataBuildingOptions getMetadataBuildingOptions() {
return options;
}
@Override
public BootstrapContext getBootstrapContext() {
return bootstrapContext;
}
@Override
public TypeConfiguration getTypeConfiguration() {
return bootstrapContext.getTypeConfiguration();
}
/**
* Retrieve the {@link Type} resolver associated with this factory.
*
* @return The type resolver
*
* @deprecated (since 5.3) No replacement, access to and handling of Types will be much different in 6.0
*/
@Deprecated
public TypeResolver getTypeResolver() {
return bootstrapContext.getTypeConfiguration().getTypeResolver();
}
@Override
public Database getDatabase() {
// important to delay this instantiation until as late as possible.
if ( database == null ) {
this.database = new Database( options );
}
return database;
}
@Override
public NamedQueryRepository buildNamedQueryRepository(SessionFactoryImpl sessionFactory) {
throw new UnsupportedOperationException( "#buildNamedQueryRepository should not be called on InFlightMetadataCollector" );
}
@Override
public Map<String, SQLFunction> getSqlFunctionMap() {
return sqlFunctionMap;
}
@Override
public void validate() throws MappingException {
// nothing to do
}
@Override
public Set<MappedSuperclass> getMappedSuperclassMappingsCopy() {
return new HashSet<>( mappedSuperClasses.values() );
}
@Override
public void initSessionFactory(SessionFactoryImplementor sessionFactory) {
throw new UnsupportedOperationException(
"You should not be building a SessionFactory from an in-flight metadata collector; and of course " +
"we should better segment this in the API :)"
);
}
@Override
public IdentifierGeneratorFactory getIdentifierGeneratorFactory() {
return identifierGeneratorFactory;
}
@Override
public SessionFactoryBuilder getSessionFactoryBuilder() {
throw new UnsupportedOperationException(
"You should not be building a SessionFactory from an in-flight metadata collector; and of course " +
"we should better segment this in the API :)"
);
}
@Override
public SessionFactory buildSessionFactory() {
throw new UnsupportedOperationException(
"You should not be building a SessionFactory from an in-flight metadata collector; and of course " +
"we should better segment this in the API :)"
);
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Entity handling
@Override
public java.util.Collection<PersistentClass> getEntityBindings() {
return entityBindingMap.values();
}
@Override
public Map<String, PersistentClass> getEntityBindingMap() {
return entityBindingMap;
}
@Override
public PersistentClass getEntityBinding(String entityName) {
return entityBindingMap.get( entityName );
}
@Override
public void addEntityBinding(PersistentClass persistentClass) throws DuplicateMappingException {
final String entityName = persistentClass.getEntityName();
final String jpaEntityName = persistentClass.getJpaEntityName();
if ( entityBindingMap.containsKey( entityName ) ) {
throw new DuplicateMappingException( DuplicateMappingException.Type.ENTITY, entityName );
}
PersistentClass matchingPersistentClass = entityBindingMap.values()
.stream()
.filter( existingPersistentClass -> existingPersistentClass.getJpaEntityName().equals( jpaEntityName ) )
.findFirst()
.orElse( null );
if ( matchingPersistentClass != null ) {
throw new DuplicateMappingException(
String.format(
"The [%s] and [%s] entities share the same JPA entity name: [%s] which is not allowed!",
matchingPersistentClass.getClassName(),
persistentClass.getClassName(),
jpaEntityName
),
DuplicateMappingException.Type.ENTITY,
jpaEntityName
);
}
entityBindingMap.put( entityName, persistentClass );
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Collection handling
@Override
public java.util.Collection<Collection> getCollectionBindings() {
return collectionBindingMap.values();
}
@Override
public Collection getCollectionBinding(String role) {
return collectionBindingMap.get( role );
}
@Override
public void addCollectionBinding(Collection collection) throws DuplicateMappingException {
final String collectionRole = collection.getRole();
if ( collectionBindingMap.containsKey( collectionRole ) ) {
throw new DuplicateMappingException( DuplicateMappingException.Type.COLLECTION, collectionRole );
}
collectionBindingMap.put( collectionRole, collection );
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Hibernate Type handling
@Override
public TypeDefinition getTypeDefinition(String registrationKey) {
return typeDefinitionMap.get( registrationKey );
}
@Override
public void addTypeDefinition(TypeDefinition typeDefinition) {
if ( typeDefinition == null ) {
throw new IllegalArgumentException( "Type definition is null" );
}
// Need to register both by name and registration keys.
if ( !StringHelper.isEmpty( typeDefinition.getName() ) ) {
addTypeDefinition( typeDefinition.getName(), typeDefinition );
}
if ( typeDefinition.getRegistrationKeys() != null ) {
for ( String registrationKey : typeDefinition.getRegistrationKeys() ) {
addTypeDefinition( registrationKey, typeDefinition );
}
}
}
private void addTypeDefinition(String registrationKey, TypeDefinition typeDefinition) {
final TypeDefinition previous = typeDefinitionMap.put(
registrationKey, typeDefinition );
if ( previous != null ) {
log.debugf(
"Duplicate typedef name [%s] now -> %s",
registrationKey,
typeDefinition.getTypeImplementorClass().getName()
);
}
}
@Override
public ClassmateContext getClassmateContext() {
return bootstrapContext.getClassmateContext();
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// attribute converters
@Override
public void addAttributeConverter(Class<? extends AttributeConverter> converterClass) {
attributeConverterManager.addConverter(
new ClassBasedConverterDescriptor( converterClass, getBootstrapContext().getClassmateContext() )
);
}
@Override
public void addAttributeConverter(ConverterDescriptor descriptor) {
attributeConverterManager.addConverter( descriptor );
}
@Override
public ConverterAutoApplyHandler getAttributeConverterAutoApplyHandler() {
return attributeConverterManager;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// filter definitions
@Override
public Map<String, FilterDefinition> getFilterDefinitions() {
return filterDefinitionMap;
}
@Override
public FilterDefinition getFilterDefinition(String name) {
return filterDefinitionMap.get( name );
}
@Override
public void addFilterDefinition(FilterDefinition filterDefinition) {
if ( filterDefinition == null || filterDefinition.getFilterName() == null ) {
throw new IllegalArgumentException( "Filter definition object or name is null: " + filterDefinition );
}
filterDefinitionMap.put( filterDefinition.getFilterName(), filterDefinition );
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// fetch profiles
@Override
public java.util.Collection<FetchProfile> getFetchProfiles() {
return fetchProfileMap.values();
}
@Override
public FetchProfile getFetchProfile(String name) {
return fetchProfileMap.get( name );
}
@Override
public void addFetchProfile(FetchProfile profile) {
if ( profile == null || profile.getName() == null ) {
throw new IllegalArgumentException( "Fetch profile object or name is null: " + profile );
}
FetchProfile old = fetchProfileMap.put( profile.getName(), profile );
if ( old != null ) {
log.warn( "Duplicated fetch profile with same name [" + profile.getName() + "] found." );
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// identifier generators
@Override
public IdentifierGeneratorDefinition getIdentifierGenerator(String name) {
if ( name == null ) {
throw new IllegalArgumentException( "null is not a valid generator name" );
}
return idGeneratorDefinitionMap.get( name );
}
@Override
public java.util.Collection<Table> collectTableMappings() {
ArrayList<Table> tables = new ArrayList<>();
for ( Namespace namespace : getDatabase().getNamespaces() ) {
tables.addAll( namespace.getTables() );
}
return tables;
}
@Override
public void addIdentifierGenerator(IdentifierGeneratorDefinition generator) {
if ( generator == null || generator.getName() == null ) {
throw new IllegalArgumentException( "ID generator object or name is null." );
}
if ( defaultIdentifierGeneratorNames.contains( generator.getName() ) ) {
return;
}
final IdentifierGeneratorDefinition old = idGeneratorDefinitionMap.put( generator.getName(), generator );
if ( old != null && !old.equals( generator ) ) {
if ( bootstrapContext.getJpaCompliance().isGlobalGeneratorScopeEnabled() ) {
throw new IllegalArgumentException( "Duplicate generator name " + old.getName() + " you will likely want to set the property " + AvailableSettings.JPA_ID_GENERATOR_GLOBAL_SCOPE_COMPLIANCE + " to false " );
}
else {
log.duplicateGeneratorName( old.getName() );
}
}
}
@Override
public void addDefaultIdentifierGenerator(IdentifierGeneratorDefinition generator) {
this.addIdentifierGenerator( generator );
defaultIdentifierGeneratorNames.add( generator.getName() );
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Named EntityGraph handling
@Override
public NamedEntityGraphDefinition getNamedEntityGraph(String name) {
return namedEntityGraphMap.get( name );
}
@Override
public Map<String, NamedEntityGraphDefinition> getNamedEntityGraphs() {
return namedEntityGraphMap;
}
@Override
public void addNamedEntityGraph(NamedEntityGraphDefinition definition) {
final String name = definition.getRegisteredName();
final NamedEntityGraphDefinition previous = namedEntityGraphMap.put( name, definition );
if ( previous != null ) {
throw new DuplicateMappingException(
DuplicateMappingException.Type.NAMED_ENTITY_GRAPH, name );
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Named query handling
public NamedQueryDefinition getNamedQueryDefinition(String name) {
if ( name == null ) {
throw new IllegalArgumentException( "null is not a valid query name" );
}
return namedQueryMap.get( name );
}
@Override
public java.util.Collection<NamedQueryDefinition> getNamedQueryDefinitions() {
return namedQueryMap.values();
}
@Override
public void addNamedQuery(NamedQueryDefinition def) {
if ( def == null ) {
throw new IllegalArgumentException( "Named query definition is null" );
}
else if ( def.getName() == null ) {
throw new IllegalArgumentException( "Named query definition name is null: " + def.getQueryString() );
}
if ( defaultNamedQueryNames.contains( def.getName() ) ) {
return;
}
applyNamedQuery( def.getName(), def );
}
private void applyNamedQuery(String name, NamedQueryDefinition query) {
checkQueryName( name );
namedQueryMap.put( name.intern(), query );
}
private void checkQueryName(String name) throws DuplicateMappingException {
if ( namedQueryMap.containsKey( name ) || namedNativeQueryMap.containsKey( name ) ) {
throw new DuplicateMappingException( DuplicateMappingException.Type.QUERY, name );
}
}
@Override
public void addDefaultQuery(NamedQueryDefinition queryDefinition) {
applyNamedQuery( queryDefinition.getName(), queryDefinition );
defaultNamedQueryNames.add( queryDefinition.getName() );
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Named native-query handling
@Override
public NamedSQLQueryDefinition getNamedNativeQueryDefinition(String name) {
return namedNativeQueryMap.get( name );
}
@Override
public java.util.Collection<NamedSQLQueryDefinition> getNamedNativeQueryDefinitions() {
return namedNativeQueryMap.values();
}
@Override
public void addNamedNativeQuery(NamedSQLQueryDefinition def) {
if ( def == null ) {
throw new IllegalArgumentException( "Named native query definition object is null" );
}
if ( def.getName() == null ) {
throw new IllegalArgumentException( "Named native query definition name is null: " + def.getQueryString() );
}
if ( defaultNamedNativeQueryNames.contains( def.getName() ) ) {
return;
}
applyNamedNativeQuery( def.getName(), def );
}
private void applyNamedNativeQuery(String name, NamedSQLQueryDefinition query) {
checkQueryName( name );
namedNativeQueryMap.put( name.intern(), query );
}
@Override
public void addDefaultNamedNativeQuery(NamedSQLQueryDefinition query) {
applyNamedNativeQuery( query.getName(), query );
defaultNamedNativeQueryNames.add( query.getName() );
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Named stored-procedure handling
@Override
public java.util.Collection<NamedProcedureCallDefinition> getNamedProcedureCallDefinitions() {
return namedProcedureCallMap.values();
}
@Override
public void addNamedProcedureCallDefinition(NamedProcedureCallDefinition definition) {
if ( definition == null ) {
throw new IllegalArgumentException( "Named query definition is null" );
}
final String name = definition.getRegisteredName();
if ( defaultNamedProcedureNames.contains( name ) ) {
return;
}
final NamedProcedureCallDefinition previous = namedProcedureCallMap.put( name, definition );
if ( previous != null ) {
throw new DuplicateMappingException( DuplicateMappingException.Type.PROCEDURE, name );
}
}
@Override
public void addDefaultNamedProcedureCallDefinition(NamedProcedureCallDefinition definition) {
addNamedProcedureCallDefinition( definition );
defaultNamedProcedureNames.add( definition.getRegisteredName() );
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// result-set mapping handling
@Override
public Map<String, ResultSetMappingDefinition> getResultSetMappingDefinitions() {
return sqlResultSetMappingMap;
}
@Override
public ResultSetMappingDefinition getResultSetMapping(String name) {
return sqlResultSetMappingMap.get( name );
}
@Override
public void addResultSetMapping(ResultSetMappingDefinition resultSetMappingDefinition) {
if ( resultSetMappingDefinition == null ) {
throw new IllegalArgumentException( "Result-set mapping was null" );
}
final String name = resultSetMappingDefinition.getName();
if ( name == null ) {
throw new IllegalArgumentException( "Result-set mapping name is null: " + resultSetMappingDefinition );
}
if ( defaultSqlResultSetMappingNames.contains( name ) ) {
return;
}
applyResultSetMapping( resultSetMappingDefinition );
}
public void applyResultSetMapping(ResultSetMappingDefinition resultSetMappingDefinition) {
final ResultSetMappingDefinition old = sqlResultSetMappingMap.put(
resultSetMappingDefinition.getName(),
resultSetMappingDefinition
);
if ( old != null ) {
throw new DuplicateMappingException(
DuplicateMappingException.Type.RESULT_SET_MAPPING,
resultSetMappingDefinition.getName()
);
}
}
@Override
public void addDefaultResultSetMapping(ResultSetMappingDefinition definition) {
final String name = definition.getName();
if ( !defaultSqlResultSetMappingNames.contains( name ) && sqlResultSetMappingMap.containsKey( name ) ) {
sqlResultSetMappingMap.remove( name );
}
applyResultSetMapping( definition );
defaultSqlResultSetMappingNames.add( name );
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// imports
@Override
public Map<String,String> getImports() {
return imports;
}
@Override
public void addImport(String importName, String entityName) {
if ( importName == null || entityName == null ) {
throw new IllegalArgumentException( "Import name or entity name is null" );
}
log.tracev( "Import: {0} -> {1}", importName, entityName );
String old = imports.put( importName, entityName );
if ( old != null ) {
log.debug( "import name [" + importName + "] overrode previous [{" + old + "}]" );
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Table handling
@Override
public Table addTable(
String schemaName,
String catalogName,
String name,
String subselectFragment,
boolean isAbstract) {
final Namespace namespace = getDatabase().locateNamespace(
getDatabase().toIdentifier( catalogName ),
getDatabase().toIdentifier( schemaName )
);
// annotation binding depends on the "table name" for @Subselect bindings
// being set into the generated table (mainly to avoid later NPE), but for now we need to keep that :(
final Identifier logicalName;
if ( name != null ) {
logicalName = getDatabase().toIdentifier( name );
}
else {
logicalName = null;
}
if ( subselectFragment != null ) {
return new Table( namespace, logicalName, subselectFragment, isAbstract );
}
else {
Table table = namespace.locateTable( logicalName );
if ( table != null ) {
if ( !isAbstract ) {
table.setAbstract( false );
}
return table;
}
return namespace.createTable( logicalName, isAbstract );
}
}
@Override
public Table addDenormalizedTable(
String schemaName,
String catalogName,
String name,
boolean isAbstract,
String subselectFragment,
Table includedTable) throws DuplicateMappingException {
final Namespace namespace = getDatabase().locateNamespace(
getDatabase().toIdentifier( catalogName ),
getDatabase().toIdentifier( schemaName )
);
// annotation binding depends on the "table name" for @Subselect bindings
// being set into the generated table (mainly to avoid later NPE), but for now we need to keep that :(
final Identifier logicalName;
if ( name != null ) {
logicalName = getDatabase().toIdentifier( name );
}
else {
logicalName = null;
}
if ( subselectFragment != null ) {
return new DenormalizedTable( namespace, logicalName, subselectFragment, isAbstract, includedTable );
}
else {
Table table = namespace.locateTable( logicalName );
if ( table != null ) {
throw new DuplicateMappingException( DuplicateMappingException.Type.TABLE, logicalName.toString() );
}
else {
table = namespace.createDenormalizedTable( logicalName, isAbstract, includedTable );
}
return table;
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Mapping impl
@Override
public org.hibernate.type.Type getIdentifierType(String entityName) throws MappingException {
final PersistentClass pc = entityBindingMap.get( entityName );
if ( pc == null ) {
throw new MappingException( "persistent class not known: " + entityName );
}
return pc.getIdentifier().getType();
}
@Override
public String getIdentifierPropertyName(String entityName) throws MappingException {
final PersistentClass pc = entityBindingMap.get( entityName );
if ( pc == null ) {
throw new MappingException( "persistent class not known: " + entityName );
}
if ( !pc.hasIdentifierProperty() ) {
return null;
}
return pc.getIdentifierProperty().getName();
}
@Override
public org.hibernate.type.Type getReferencedPropertyType(String entityName, String propertyName) throws MappingException {
final PersistentClass pc = entityBindingMap.get( entityName );
if ( pc == null ) {
throw new MappingException( "persistent class not known: " + entityName );
}
Property prop = pc.getReferencedProperty( propertyName );
if ( prop == null ) {
throw new MappingException(
"property not known: " +
entityName + '.' + propertyName
);
}
return prop.getType();
}
private Map<Identifier,Identifier> logicalToPhysicalTableNameMap = new HashMap<>();
private Map<Identifier,Identifier> physicalToLogicalTableNameMap = new HashMap<>();
@Override
public void addTableNameBinding(Identifier logicalName, Table table) {
logicalToPhysicalTableNameMap.put( logicalName, table.getNameIdentifier() );
physicalToLogicalTableNameMap.put( table.getNameIdentifier(), logicalName );
}
@Override
public void addTableNameBinding(String schema, String catalog, String logicalName, String realTableName, Table denormalizedSuperTable) {
final Identifier logicalNameIdentifier = getDatabase().toIdentifier( logicalName );
final Identifier physicalNameIdentifier = getDatabase().toIdentifier( realTableName );
logicalToPhysicalTableNameMap.put( logicalNameIdentifier, physicalNameIdentifier );
physicalToLogicalTableNameMap.put( physicalNameIdentifier, logicalNameIdentifier );
}
@Override
public String getLogicalTableName(Table ownerTable) {
final Identifier logicalName = physicalToLogicalTableNameMap.get( ownerTable.getNameIdentifier() );
if ( logicalName == null ) {
throw new MappingException( "Unable to find physical table: " + ownerTable.getName() );
}
return logicalName.render();
}
@Override
public String getPhysicalTableName(Identifier logicalName) {
final Identifier physicalName = logicalToPhysicalTableNameMap.get( logicalName );
return physicalName == null ? null : physicalName.render();
}
@Override
public String getPhysicalTableName(String logicalName) {
return getPhysicalTableName( getDatabase().toIdentifier( logicalName ) );
}
/**
* Internal struct used to maintain xref between physical and logical column
* names for a table. Mainly this is used to ensure that the defined NamingStrategy
* is not creating duplicate column names.
*/
private class TableColumnNameBinding implements Serializable {
private final String tableName;
private Map<Identifier, String> logicalToPhysical = new HashMap<>();
private Map<String, Identifier> physicalToLogical = new HashMap<>();
private TableColumnNameBinding(String tableName) {
this.tableName = tableName;
}
public void addBinding(Identifier logicalName, Column physicalColumn) {
final String physicalNameString = physicalColumn.getQuotedName( getDatabase().getJdbcEnvironment().getDialect() );
bindLogicalToPhysical( logicalName, physicalNameString );
bindPhysicalToLogical( logicalName, physicalNameString );
}
private void bindLogicalToPhysical(Identifier logicalName, String physicalName) throws DuplicateMappingException {
final String existingPhysicalNameMapping = logicalToPhysical.put( logicalName, physicalName );
if ( existingPhysicalNameMapping != null ) {
final boolean areSame = logicalName.isQuoted()
? physicalName.equals( existingPhysicalNameMapping )
: physicalName.equalsIgnoreCase( existingPhysicalNameMapping );
if ( !areSame ) {
throw new DuplicateMappingException(
String.format(
Locale.ENGLISH,
"Table [%s] contains logical column name [%s] referring to multiple physical " +
"column names: [%s], [%s]",
tableName,
logicalName,
existingPhysicalNameMapping,
physicalName
),
DuplicateMappingException.Type.COLUMN_BINDING,
tableName + "." + logicalName
);
}
}
}
private void bindPhysicalToLogical(Identifier logicalName, String physicalName) throws DuplicateMappingException {
final Identifier existingLogicalName = physicalToLogical.put( physicalName, logicalName );
if ( existingLogicalName != null && ! existingLogicalName.equals( logicalName ) ) {
throw new DuplicateMappingException(
String.format(
Locale.ENGLISH,
"Table [%s] contains physical column name [%s] referred to by multiple logical " +
"column names: [%s], [%s]",
tableName,
physicalName,
logicalName,
existingLogicalName
),
DuplicateMappingException.Type.COLUMN_BINDING,
tableName + "." + physicalName
);
}
}
}
private Map<Table,TableColumnNameBinding> columnNameBindingByTableMap;
@Override
public void addColumnNameBinding(Table table, String logicalName, Column column) throws DuplicateMappingException {
addColumnNameBinding( table, getDatabase().toIdentifier( logicalName ), column );
}
@Override
public void addColumnNameBinding(Table table, Identifier logicalName, Column column) throws DuplicateMappingException {
TableColumnNameBinding binding = null;
if ( columnNameBindingByTableMap == null ) {
columnNameBindingByTableMap = new HashMap<>();
}
else {
binding = columnNameBindingByTableMap.get( table );
}
if ( binding == null ) {
binding = new TableColumnNameBinding( table.getName() );
columnNameBindingByTableMap.put( table, binding );
}
binding.addBinding( logicalName, column );
}
@Override
public String getPhysicalColumnName(Table table, String logicalName) throws MappingException {
return getPhysicalColumnName( table, getDatabase().toIdentifier( logicalName ) );
}
@Override
public String getPhysicalColumnName(Table table, Identifier logicalName) throws MappingException {
if ( logicalName == null ) {
throw new MappingException( "Logical column name cannot be null" );
}
Table currentTable = table;
String physicalName = null;
while ( currentTable != null ) {
final TableColumnNameBinding binding = columnNameBindingByTableMap.get( currentTable );
if ( binding != null ) {
physicalName = binding.logicalToPhysical.get( logicalName );
if ( physicalName != null ) {
break;
}