/
Configuration.java
3814 lines (3335 loc) · 131 KB
/
Configuration.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) 2010, 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.cfg;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.io.StringReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import javax.persistence.AttributeConverter;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.MapsId;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.hibernate.AnnotationException;
import org.hibernate.AssertionFailure;
import org.hibernate.DuplicateMappingException;
import org.hibernate.EmptyInterceptor;
import org.hibernate.HibernateException;
import org.hibernate.Interceptor;
import org.hibernate.InvalidMappingException;
import org.hibernate.MappingException;
import org.hibernate.MappingNotFoundException;
import org.hibernate.SessionFactory;
import org.hibernate.SessionFactoryObserver;
import org.hibernate.annotations.AnyMetaDef;
import org.hibernate.annotations.common.reflection.MetadataProvider;
import org.hibernate.annotations.common.reflection.MetadataProviderInjector;
import org.hibernate.annotations.common.reflection.ReflectionManager;
import org.hibernate.annotations.common.reflection.XClass;
import org.hibernate.annotations.common.reflection.java.JavaReflectionManager;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
import org.hibernate.boot.registry.internal.StandardServiceRegistryImpl;
import org.hibernate.cfg.annotations.NamedEntityGraphDefinition;
import org.hibernate.cfg.annotations.NamedProcedureCallDefinition;
import org.hibernate.cfg.annotations.reflection.JPAMetadataProvider;
import org.hibernate.context.spi.CurrentTenantIdentifierResolver;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.MySQLDialect;
import org.hibernate.dialect.function.SQLFunction;
import org.hibernate.engine.ResultSetMappingDefinition;
import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.engine.spi.FilterDefinition;
import org.hibernate.engine.spi.Mapping;
import org.hibernate.engine.spi.NamedQueryDefinition;
import org.hibernate.engine.spi.NamedSQLQueryDefinition;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.id.IdentifierGeneratorAggregator;
import org.hibernate.id.PersistentIdentifierGenerator;
import org.hibernate.id.factory.IdentifierGeneratorFactory;
import org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory;
import org.hibernate.id.factory.spi.MutableIdentifierGeneratorFactory;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.SessionFactoryImpl;
import org.hibernate.internal.util.ClassLoaderHelper;
import org.hibernate.internal.util.ConfigHelper;
import org.hibernate.internal.util.ReflectHelper;
import org.hibernate.internal.util.SerializationHelper;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.collections.ArrayHelper;
import org.hibernate.internal.util.collections.CollectionHelper;
import org.hibernate.internal.util.collections.JoinedIterator;
import org.hibernate.internal.util.config.ConfigurationHelper;
import org.hibernate.internal.util.xml.ErrorLogger;
import org.hibernate.internal.util.xml.MappingReader;
import org.hibernate.internal.util.xml.Origin;
import org.hibernate.internal.util.xml.OriginImpl;
import org.hibernate.internal.util.xml.XMLHelper;
import org.hibernate.internal.util.xml.XmlDocument;
import org.hibernate.internal.util.xml.XmlDocumentImpl;
import org.hibernate.mapping.AuxiliaryDatabaseObject;
import org.hibernate.mapping.Collection;
import org.hibernate.mapping.Column;
import org.hibernate.mapping.Constraint;
import org.hibernate.mapping.DenormalizedTable;
import org.hibernate.mapping.FetchProfile;
import org.hibernate.mapping.ForeignKey;
import org.hibernate.mapping.IdGenerator;
import org.hibernate.mapping.IdentifierCollection;
import org.hibernate.mapping.Index;
import org.hibernate.mapping.Join;
import org.hibernate.mapping.MappedSuperclass;
import org.hibernate.mapping.MetadataSource;
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.TypeDef;
import org.hibernate.mapping.UniqueKey;
import org.hibernate.metamodel.spi.TypeContributions;
import org.hibernate.metamodel.spi.TypeContributor;
import org.hibernate.proxy.EntityNotFoundDelegate;
import org.hibernate.secure.spi.GrantedPermission;
import org.hibernate.secure.spi.JaccPermissionDeclarations;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.tool.hbm2ddl.DatabaseMetadata;
import org.hibernate.tool.hbm2ddl.IndexMetadata;
import org.hibernate.tool.hbm2ddl.SchemaUpdateScript;
import org.hibernate.tool.hbm2ddl.TableMetadata;
import org.hibernate.tool.hbm2ddl.UniqueConstraintSchemaUpdateStrategy;
import org.hibernate.tuple.entity.EntityTuplizerFactory;
import org.hibernate.type.BasicType;
import org.hibernate.type.SerializationException;
import org.hibernate.type.Type;
import org.hibernate.type.TypeResolver;
import org.hibernate.usertype.CompositeUserType;
import org.hibernate.usertype.UserType;
import org.jboss.logging.Logger;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
/**
* An instance of <tt>Configuration</tt> allows the application
* to specify properties and mapping documents to be used when
* creating a <tt>SessionFactory</tt>. Usually an application will create
* a single <tt>Configuration</tt>, build a single instance of
* <tt>SessionFactory</tt> and then instantiate <tt>Session</tt>s in
* threads servicing client requests. The <tt>Configuration</tt> is meant
* only as an initialization-time object. <tt>SessionFactory</tt>s are
* immutable and do not retain any association back to the
* <tt>Configuration</tt>.<br>
* <br>
* A new <tt>Configuration</tt> will use the properties specified in
* <tt>hibernate.properties</tt> by default.
* <p/>
* NOTE : This will be replaced by use of {@link org.hibernate.boot.registry.StandardServiceRegistryBuilder} and
* {@link org.hibernate.metamodel.MetadataSources} instead after the 4.0 release at which point this class will become
* deprecated and scheduled for removal in 5.0. See
* <a href="http://opensource.atlassian.com/projects/hibernate/browse/HHH-6183">HHH-6183</a>,
* <a href="http://opensource.atlassian.com/projects/hibernate/browse/HHH-2578">HHH-2578</a> and
* <a href="http://opensource.atlassian.com/projects/hibernate/browse/HHH-6586">HHH-6586</a> for details
*
* @author Gavin King
* @see org.hibernate.SessionFactory
*/
@SuppressWarnings( {"UnusedDeclaration"})
public class Configuration implements Serializable {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, Configuration.class.getName());
public static final String DEFAULT_CACHE_CONCURRENCY_STRATEGY = AvailableSettings.DEFAULT_CACHE_CONCURRENCY_STRATEGY;
public static final String USE_NEW_ID_GENERATOR_MAPPINGS = AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS;
public static final String ARTEFACT_PROCESSING_ORDER = "hibernate.mapping.precedence";
/**
* Class name of the class needed to enable Search.
*/
private static final String SEARCH_STARTUP_CLASS = "org.hibernate.search.event.EventListenerRegister";
/**
* Method to call to enable Search.
*/
private static final String SEARCH_STARTUP_METHOD = "enableHibernateSearch";
protected MetadataSourceQueue metadataSourceQueue;
private transient ReflectionManager reflectionManager;
protected Map<String, PersistentClass> classes;
protected Map<String, String> imports;
protected Map<String, Collection> collections;
protected Map<String, Table> tables;
protected List<AuxiliaryDatabaseObject> auxiliaryDatabaseObjects;
protected Map<String, NamedQueryDefinition> namedQueries;
protected Map<String, NamedSQLQueryDefinition> namedSqlQueries;
protected Map<String, NamedProcedureCallDefinition> namedProcedureCallMap;
protected Map<String, ResultSetMappingDefinition> sqlResultSetMappings;
protected Map<String, NamedEntityGraphDefinition> namedEntityGraphMap;
protected Map<String, TypeDef> typeDefs;
protected Map<String, FilterDefinition> filterDefinitions;
protected Map<String, FetchProfile> fetchProfiles;
protected Map tableNameBinding;
protected Map columnNameBindingPerTable;
protected List<SecondPass> secondPasses;
protected List<Mappings.PropertyReference> propertyReferences;
protected Map<ExtendsQueueEntry, ?> extendsQueue;
protected Map<String, SQLFunction> sqlFunctions;
private TypeResolver typeResolver = new TypeResolver();
private List<TypeContributor> typeContributorRegistrations = new ArrayList<TypeContributor>();
private EntityTuplizerFactory entityTuplizerFactory;
// private ComponentTuplizerFactory componentTuplizerFactory; todo : HHH-3517 and HHH-1907
private Interceptor interceptor;
private Properties properties;
private EntityResolver entityResolver;
private EntityNotFoundDelegate entityNotFoundDelegate;
protected transient XMLHelper xmlHelper;
protected NamingStrategy namingStrategy;
private SessionFactoryObserver sessionFactoryObserver;
protected final SettingsFactory settingsFactory;
private transient Mapping mapping = buildMapping();
private MutableIdentifierGeneratorFactory identifierGeneratorFactory;
private Map<Class<?>, org.hibernate.mapping.MappedSuperclass> mappedSuperClasses;
private Map<String, IdGenerator> namedGenerators;
private Map<String, Map<String, Join>> joins;
private Map<String, AnnotatedClassType> classTypes;
private Set<String> defaultNamedQueryNames;
private Set<String> defaultNamedNativeQueryNames;
private Set<String> defaultSqlResultSetMappingNames;
private Set<String> defaultNamedProcedure;
private Set<String> defaultNamedGenerators;
private Map<String, Properties> generatorTables;
private Map<Table, List<UniqueConstraintHolder>> uniqueConstraintHoldersByTable;
private Map<Table, List<JPAIndexHolder>> jpaIndexHoldersByTable;
private Map<String, String> mappedByResolver;
private Map<String, String> propertyRefResolver;
private Map<String, AnyMetaDef> anyMetaDefs;
private List<CacheHolder> caches;
private boolean inSecondPass = false;
private boolean isDefaultProcessed = false;
private boolean isValidatorNotPresentLogged;
private Map<XClass, Map<String, PropertyData>> propertiesAnnotatedWithMapsId;
private Map<XClass, Map<String, PropertyData>> propertiesAnnotatedWithIdAndToOne;
private CurrentTenantIdentifierResolver currentTenantIdentifierResolver;
private boolean specjProprietarySyntaxEnabled;
private ConcurrentHashMap<Class,AttributeConverterDefinition> attributeConverterDefinitionsByClass;
protected Configuration(SettingsFactory settingsFactory) {
this.settingsFactory = settingsFactory;
reset();
}
public Configuration() {
this( new SettingsFactory() );
}
protected void reset() {
metadataSourceQueue = new MetadataSourceQueue();
createReflectionManager();
classes = new HashMap<String,PersistentClass>();
imports = new HashMap<String,String>();
collections = new HashMap<String,Collection>();
tables = new TreeMap<String,Table>();
namedQueries = new HashMap<String,NamedQueryDefinition>();
namedSqlQueries = new HashMap<String,NamedSQLQueryDefinition>();
sqlResultSetMappings = new HashMap<String, ResultSetMappingDefinition>();
namedEntityGraphMap = new HashMap<String, NamedEntityGraphDefinition>();
namedProcedureCallMap = new HashMap<String, NamedProcedureCallDefinition>( );
typeDefs = new HashMap<String,TypeDef>();
filterDefinitions = new HashMap<String, FilterDefinition>();
fetchProfiles = new HashMap<String, FetchProfile>();
auxiliaryDatabaseObjects = new ArrayList<AuxiliaryDatabaseObject>();
tableNameBinding = new HashMap();
columnNameBindingPerTable = new HashMap();
secondPasses = new ArrayList<SecondPass>();
propertyReferences = new ArrayList<Mappings.PropertyReference>();
extendsQueue = new HashMap<ExtendsQueueEntry, String>();
xmlHelper = new XMLHelper();
interceptor = EmptyInterceptor.INSTANCE;
properties = Environment.getProperties();
entityResolver = XMLHelper.DEFAULT_DTD_RESOLVER;
sqlFunctions = new HashMap<String, SQLFunction>();
entityTuplizerFactory = new EntityTuplizerFactory();
// componentTuplizerFactory = new ComponentTuplizerFactory();
identifierGeneratorFactory = new DefaultIdentifierGeneratorFactory();
mappedSuperClasses = new HashMap<Class<?>, MappedSuperclass>();
metadataSourcePrecedence = Collections.emptyList();
namedGenerators = new HashMap<String, IdGenerator>();
joins = new HashMap<String, Map<String, Join>>();
classTypes = new HashMap<String, AnnotatedClassType>();
generatorTables = new HashMap<String, Properties>();
defaultNamedQueryNames = new HashSet<String>();
defaultNamedNativeQueryNames = new HashSet<String>();
defaultSqlResultSetMappingNames = new HashSet<String>();
defaultNamedProcedure = new HashSet<String>( );
defaultNamedGenerators = new HashSet<String>();
uniqueConstraintHoldersByTable = new HashMap<Table, List<UniqueConstraintHolder>>();
jpaIndexHoldersByTable = new HashMap<Table,List<JPAIndexHolder>>( );
mappedByResolver = new HashMap<String, String>();
propertyRefResolver = new HashMap<String, String>();
caches = new ArrayList<CacheHolder>();
namingStrategy = EJB3NamingStrategy.INSTANCE;
setEntityResolver( new EJB3DTDEntityResolver() );
anyMetaDefs = new HashMap<String, AnyMetaDef>();
propertiesAnnotatedWithMapsId = new HashMap<XClass, Map<String, PropertyData>>();
propertiesAnnotatedWithIdAndToOne = new HashMap<XClass, Map<String, PropertyData>>();
specjProprietarySyntaxEnabled = System.getProperty( "hibernate.enable_specj_proprietary_syntax" ) != null;
}
public EntityTuplizerFactory getEntityTuplizerFactory() {
return entityTuplizerFactory;
}
public ReflectionManager getReflectionManager() {
return reflectionManager;
}
// public ComponentTuplizerFactory getComponentTuplizerFactory() {
// return componentTuplizerFactory;
// }
/**
* Iterate the entity mappings
*
* @return Iterator of the entity mappings currently contained in the configuration.
*/
public Iterator<PersistentClass> getClassMappings() {
return classes.values().iterator();
}
/**
* Iterate the collection mappings
*
* @return Iterator of the collection mappings currently contained in the configuration.
*/
public Iterator getCollectionMappings() {
return collections.values().iterator();
}
/**
* Iterate the table mappings
*
* @return Iterator of the table mappings currently contained in the configuration.
*/
public Iterator<Table> getTableMappings() {
return tables.values().iterator();
}
/**
* Iterate the mapped super class mappings
* EXPERIMENTAL Consider this API as PRIVATE
*
* @return iterator over the MappedSuperclass mapping currently contained in the configuration.
*/
public Iterator<MappedSuperclass> getMappedSuperclassMappings() {
return mappedSuperClasses.values().iterator();
}
/**
* Get the mapping for a particular entity
*
* @param entityName An entity name.
* @return the entity mapping information
*/
public PersistentClass getClassMapping(String entityName) {
return classes.get( entityName );
}
/**
* Get the mapping for a particular collection role
*
* @param role a collection role
* @return The collection mapping information
*/
public Collection getCollectionMapping(String role) {
return collections.get( role );
}
/**
* Set a custom entity resolver. This entity resolver must be
* set before addXXX(misc) call.
* Default value is {@link org.hibernate.internal.util.xml.DTDEntityResolver}
*
* @param entityResolver entity resolver to use
*/
public void setEntityResolver(EntityResolver entityResolver) {
this.entityResolver = entityResolver;
}
public EntityResolver getEntityResolver() {
return entityResolver;
}
/**
* Retrieve the user-supplied delegate to handle non-existent entity
* scenarios. May be null.
*
* @return The user-supplied delegate
*/
public EntityNotFoundDelegate getEntityNotFoundDelegate() {
return entityNotFoundDelegate;
}
/**
* Specify a user-supplied delegate to be used to handle scenarios where an entity could not be
* located by specified id. This is mainly intended for EJB3 implementations to be able to
* control how proxy initialization errors should be handled...
*
* @param entityNotFoundDelegate The delegate to use
*/
public void setEntityNotFoundDelegate(EntityNotFoundDelegate entityNotFoundDelegate) {
this.entityNotFoundDelegate = entityNotFoundDelegate;
}
/**
* Read mappings from a particular XML file
*
* @param xmlFile a path to a file
* @return this (for method chaining purposes)
* @throws org.hibernate.MappingException Indicates inability to locate or parse
* the specified mapping file.
* @see #addFile(java.io.File)
*/
public Configuration addFile(String xmlFile) throws MappingException {
return addFile( new File( xmlFile ) );
}
/**
* Read mappings from a particular XML file
*
* @param xmlFile a path to a file
* @return this (for method chaining purposes)
* @throws MappingException Indicates inability to locate the specified mapping file. Historically this could
* have indicated a problem parsing the XML document, but that is now delayed until after {@link #buildMappings}
*/
public Configuration addFile(final File xmlFile) throws MappingException {
LOG.readingMappingsFromFile( xmlFile.getPath() );
final String name = xmlFile.getAbsolutePath();
final InputSource inputSource;
try {
inputSource = new InputSource( new FileInputStream( xmlFile ) );
}
catch ( FileNotFoundException e ) {
throw new MappingNotFoundException( "file", xmlFile.toString() );
}
add( inputSource, "file", name );
return this;
}
private XmlDocument add(InputSource inputSource, String originType, String originName) {
return add( inputSource, new OriginImpl( originType, originName ) );
}
private XmlDocument add(InputSource inputSource, Origin origin) {
XmlDocument metadataXml = MappingReader.INSTANCE.readMappingDocument( entityResolver, inputSource, origin );
add( metadataXml );
return metadataXml;
}
public void add(XmlDocument metadataXml) {
if ( inSecondPass || !isOrmXml( metadataXml ) ) {
metadataSourceQueue.add( metadataXml );
}
else {
final MetadataProvider metadataProvider = ( (MetadataProviderInjector) reflectionManager ).getMetadataProvider();
JPAMetadataProvider jpaMetadataProvider = ( JPAMetadataProvider ) metadataProvider;
List<String> classNames = jpaMetadataProvider.getXMLContext().addDocument( metadataXml.getDocumentTree() );
for ( String className : classNames ) {
try {
metadataSourceQueue.add( reflectionManager.classForName( className, this.getClass() ) );
}
catch ( ClassNotFoundException e ) {
throw new AnnotationException( "Unable to load class defined in XML: " + className, e );
}
}
}
}
private static boolean isOrmXml(XmlDocument xmlDocument) {
return "entity-mappings".equals( xmlDocument.getDocumentTree().getRootElement().getName() );
}
/**
* Add a cached mapping file. A cached file is a serialized representation
* of the DOM structure of a particular mapping. It is saved from a previous
* call as a file with the name <tt>xmlFile + ".bin"</tt> where xmlFile is
* the name of the original mapping file.
* </p>
* If a cached <tt>xmlFile + ".bin"</tt> exists and is newer than
* <tt>xmlFile</tt> the <tt>".bin"</tt> file will be read directly. Otherwise
* xmlFile is read and then serialized to <tt>xmlFile + ".bin"</tt> for use
* the next time.
*
* @param xmlFile The cacheable mapping file to be added.
* @return this (for method chaining purposes)
* @throws MappingException Indicates problems reading the cached file or processing
* the non-cached file.
*/
public Configuration addCacheableFile(File xmlFile) throws MappingException {
File cachedFile = determineCachedDomFile( xmlFile );
try {
return addCacheableFileStrictly( xmlFile );
}
catch ( SerializationException e ) {
LOG.unableToDeserializeCache( cachedFile.getPath(), e );
}
catch ( FileNotFoundException e ) {
LOG.cachedFileNotFound( cachedFile.getPath(), e );
}
final String name = xmlFile.getAbsolutePath();
final InputSource inputSource;
try {
inputSource = new InputSource( new FileInputStream( xmlFile ) );
}
catch ( FileNotFoundException e ) {
throw new MappingNotFoundException( "file", xmlFile.toString() );
}
LOG.readingMappingsFromFile( xmlFile.getPath() );
XmlDocument metadataXml = add( inputSource, "file", name );
try {
LOG.debugf( "Writing cache file for: %s to: %s", xmlFile, cachedFile );
SerializationHelper.serialize( ( Serializable ) metadataXml.getDocumentTree(), new FileOutputStream( cachedFile ) );
}
catch ( Exception e ) {
LOG.unableToWriteCachedFile( cachedFile.getPath(), e.getMessage() );
}
return this;
}
private File determineCachedDomFile(File xmlFile) {
return new File( xmlFile.getAbsolutePath() + ".bin" );
}
/**
* <b>INTENDED FOR TESTSUITE USE ONLY!</b>
* <p/>
* Much like {@link #addCacheableFile(File)} except that here we will fail immediately if
* the cache version cannot be found or used for whatever reason
*
* @param xmlFile The xml file, not the bin!
*
* @return The dom "deserialized" from the cached file.
*
* @throws SerializationException Indicates a problem deserializing the cached dom tree
* @throws FileNotFoundException Indicates that the cached file was not found or was not usable.
*/
public Configuration addCacheableFileStrictly(File xmlFile) throws SerializationException, FileNotFoundException {
final File cachedFile = determineCachedDomFile( xmlFile );
final boolean useCachedFile = xmlFile.exists()
&& cachedFile.exists()
&& xmlFile.lastModified() < cachedFile.lastModified();
if ( ! useCachedFile ) {
throw new FileNotFoundException( "Cached file could not be found or could not be used" );
}
LOG.readingCachedMappings( cachedFile );
Document document = ( Document ) SerializationHelper.deserialize( new FileInputStream( cachedFile ) );
add( new XmlDocumentImpl( document, "file", xmlFile.getAbsolutePath() ) );
return this;
}
/**
* Add a cacheable mapping file.
*
* @param xmlFile The name of the file to be added. This must be in a form
* useable to simply construct a {@link java.io.File} instance.
* @return this (for method chaining purposes)
* @throws MappingException Indicates problems reading the cached file or processing
* the non-cached file.
* @see #addCacheableFile(java.io.File)
*/
public Configuration addCacheableFile(String xmlFile) throws MappingException {
return addCacheableFile( new File( xmlFile ) );
}
/**
* Read mappings from a <tt>String</tt>
*
* @param xml an XML string
* @return this (for method chaining purposes)
* @throws org.hibernate.MappingException Indicates problems parsing the
* given XML string
*/
public Configuration addXML(String xml) throws MappingException {
LOG.debugf( "Mapping XML:\n%s", xml );
final InputSource inputSource = new InputSource( new StringReader( xml ) );
add( inputSource, "string", "XML String" );
return this;
}
/**
* Read mappings from a <tt>URL</tt>
*
* @param url The url for the mapping document to be read.
* @return this (for method chaining purposes)
* @throws MappingException Indicates problems reading the URL or processing
* the mapping document.
*/
public Configuration addURL(URL url) throws MappingException {
final String urlExternalForm = url.toExternalForm();
LOG.debugf( "Reading mapping document from URL : %s", urlExternalForm );
try {
add( url.openStream(), "URL", urlExternalForm );
}
catch ( IOException e ) {
throw new InvalidMappingException( "Unable to open url stream [" + urlExternalForm + "]", "URL", urlExternalForm, e );
}
return this;
}
private XmlDocument add(InputStream inputStream, final String type, final String name) {
final InputSource inputSource = new InputSource( inputStream );
try {
return add( inputSource, type, name );
}
finally {
try {
inputStream.close();
}
catch ( IOException ignore ) {
LOG.trace( "Was unable to close input stream");
}
}
}
/**
* Read mappings from a DOM <tt>Document</tt>
*
* @param doc The DOM document
* @return this (for method chaining purposes)
* @throws MappingException Indicates problems reading the DOM or processing
* the mapping document.
*/
public Configuration addDocument(org.w3c.dom.Document doc) throws MappingException {
LOG.debugf( "Mapping Document:\n%s", doc );
final Document document = xmlHelper.createDOMReader().read( doc );
add( new XmlDocumentImpl( document, "unknown", null ) );
return this;
}
/**
* Read mappings from an {@link java.io.InputStream}.
*
* @param xmlInputStream The input stream containing a DOM.
* @return this (for method chaining purposes)
* @throws MappingException Indicates problems reading the stream, or
* processing the contained mapping document.
*/
public Configuration addInputStream(InputStream xmlInputStream) throws MappingException {
add( xmlInputStream, "input stream", null );
return this;
}
/**
* Read mappings as a application resource (i.e. classpath lookup).
*
* @param resourceName The resource name
* @param classLoader The class loader to use.
* @return this (for method chaining purposes)
* @throws MappingException Indicates problems locating the resource or
* processing the contained mapping document.
*/
public Configuration addResource(String resourceName, ClassLoader classLoader) throws MappingException {
LOG.readingMappingsFromResource( resourceName );
InputStream resourceInputStream = classLoader.getResourceAsStream( resourceName );
if ( resourceInputStream == null ) {
throw new MappingNotFoundException( "resource", resourceName );
}
add( resourceInputStream, "resource", resourceName );
return this;
}
/**
* Read mappings as a application resourceName (i.e. classpath lookup)
* trying different class loaders.
*
* @param resourceName The resource name
* @return this (for method chaining purposes)
* @throws MappingException Indicates problems locating the resource or
* processing the contained mapping document.
*/
public Configuration addResource(String resourceName) throws MappingException {
LOG.readingMappingsFromResource( resourceName );
ClassLoader contextClassLoader = ClassLoaderHelper.getContextClassLoader();
InputStream resourceInputStream = null;
if ( contextClassLoader != null ) {
resourceInputStream = contextClassLoader.getResourceAsStream( resourceName );
}
if ( resourceInputStream == null ) {
resourceInputStream = Environment.class.getClassLoader().getResourceAsStream( resourceName );
}
if ( resourceInputStream == null ) {
throw new MappingNotFoundException( "resource", resourceName );
}
add( resourceInputStream, "resource", resourceName );
return this;
}
/**
* Read a mapping as an application resource using the convention that a class
* named <tt>foo.bar.Foo</tt> is mapped by a file <tt>foo/bar/Foo.hbm.xml</tt>
* which can be resolved as a classpath resource.
*
* @param persistentClass The mapped class
* @return this (for method chaining purposes)
* @throws MappingException Indicates problems locating the resource or
* processing the contained mapping document.
*/
public Configuration addClass(Class persistentClass) throws MappingException {
String mappingResourceName = persistentClass.getName().replace( '.', '/' ) + ".hbm.xml";
LOG.readingMappingsFromResource( mappingResourceName );
return addResource( mappingResourceName, persistentClass.getClassLoader() );
}
/**
* Read metadata from the annotations associated with this class.
*
* @param annotatedClass The class containing annotations
*
* @return this (for method chaining)
*/
@SuppressWarnings({ "unchecked" })
public Configuration addAnnotatedClass(Class annotatedClass) {
XClass xClass = reflectionManager.toXClass( annotatedClass );
metadataSourceQueue.add( xClass );
return this;
}
/**
* Read package-level metadata.
*
* @param packageName java package name
*
* @return this (for method chaining)
*
* @throws MappingException in case there is an error in the mapping data
*/
public Configuration addPackage(String packageName) throws MappingException {
LOG.debugf( "Mapping Package %s", packageName );
try {
AnnotationBinder.bindPackage( packageName, createMappings() );
return this;
}
catch ( MappingException me ) {
LOG.unableToParseMetadata( packageName );
throw me;
}
}
/**
* Read all mappings from a jar file
* <p/>
* Assumes that any file named <tt>*.hbm.xml</tt> is a mapping document.
*
* @param jar a jar file
* @return this (for method chaining purposes)
* @throws MappingException Indicates problems reading the jar file or
* processing the contained mapping documents.
*/
public Configuration addJar(File jar) throws MappingException {
LOG.searchingForMappingDocuments( jar.getName() );
JarFile jarFile = null;
try {
try {
jarFile = new JarFile( jar );
}
catch (IOException ioe) {
throw new InvalidMappingException(
"Could not read mapping documents from jar: " + jar.getName(), "jar", jar.getName(),
ioe
);
}
Enumeration jarEntries = jarFile.entries();
while ( jarEntries.hasMoreElements() ) {
ZipEntry ze = (ZipEntry) jarEntries.nextElement();
if ( ze.getName().endsWith( ".hbm.xml" ) ) {
LOG.foundMappingDocument( ze.getName() );
try {
addInputStream( jarFile.getInputStream( ze ) );
}
catch (Exception e) {
throw new InvalidMappingException(
"Could not read mapping documents from jar: " + jar.getName(),
"jar",
jar.getName(),
e
);
}
}
}
}
finally {
try {
if ( jarFile != null ) {
jarFile.close();
}
}
catch (IOException ioe) {
LOG.unableToCloseJar( ioe.getMessage() );
}
}
return this;
}
/**
* Read all mapping documents from a directory tree.
* <p/>
* Assumes that any file named <tt>*.hbm.xml</tt> is a mapping document.
*
* @param dir The directory
* @return this (for method chaining purposes)
* @throws MappingException Indicates problems reading the jar file or
* processing the contained mapping documents.
*/
public Configuration addDirectory(File dir) throws MappingException {
File[] files = dir.listFiles();
if ( files != null ) {
for ( File file : files ) {
if ( file.isDirectory() ) {
addDirectory( file );
}
else if ( file.getName().endsWith( ".hbm.xml" ) ) {
addFile( file );
}
}
}
return this;
}
/**
* Create a new <tt>Mappings</tt> to add class and collection mappings to.
*
* @return The created mappings
*/
public Mappings createMappings() {
return new MappingsImpl();
}
@SuppressWarnings({ "unchecked" })
public Iterator<IdentifierGenerator> iterateGenerators(Dialect dialect) throws MappingException {
TreeMap generators = new TreeMap();
String defaultCatalog = properties.getProperty( Environment.DEFAULT_CATALOG );
String defaultSchema = properties.getProperty( Environment.DEFAULT_SCHEMA );
for ( PersistentClass pc : classes.values() ) {
if ( !pc.isInherited() ) {
IdentifierGenerator ig = pc.getIdentifier().createIdentifierGenerator(
getIdentifierGeneratorFactory(),
dialect,
defaultCatalog,
defaultSchema,
(RootClass) pc
);
if ( ig instanceof PersistentIdentifierGenerator ) {
generators.put( ( (PersistentIdentifierGenerator) ig ).generatorKey(), ig );
}
else if ( ig instanceof IdentifierGeneratorAggregator ) {
( (IdentifierGeneratorAggregator) ig ).registerPersistentGenerators( generators );
}
}
}
for ( Collection collection : collections.values() ) {
if ( collection.isIdentified() ) {
IdentifierGenerator ig = ( ( IdentifierCollection ) collection ).getIdentifier().createIdentifierGenerator(
getIdentifierGeneratorFactory(),
dialect,
defaultCatalog,
defaultSchema,
null
);
if ( ig instanceof PersistentIdentifierGenerator ) {
generators.put( ( (PersistentIdentifierGenerator) ig ).generatorKey(), ig );
}
}
}
return generators.values().iterator();
}
/**
* Generate DDL for dropping tables
*
* @param dialect The dialect for which to generate the drop script
* @return The sequence of DDL commands to drop the schema objects
* @throws HibernateException Generally indicates a problem calling {@link #buildMappings()}
* @see org.hibernate.tool.hbm2ddl.SchemaExport
*/
public String[] generateDropSchemaScript(Dialect dialect) throws HibernateException {
secondPassCompile();
String defaultCatalog = properties.getProperty( Environment.DEFAULT_CATALOG );
String defaultSchema = properties.getProperty( Environment.DEFAULT_SCHEMA );
ArrayList<String> script = new ArrayList<String>( 50 );
// drop them in reverse order in case db needs it done that way...
{
ListIterator itr = auxiliaryDatabaseObjects.listIterator( auxiliaryDatabaseObjects.size() );
while ( itr.hasPrevious() ) {
AuxiliaryDatabaseObject object = (AuxiliaryDatabaseObject) itr.previous();
if ( object.appliesToDialect( dialect ) ) {
script.add( object.sqlDropString( dialect, defaultCatalog, defaultSchema ) );
}
}
}
if ( dialect.dropConstraints() ) {
Iterator itr = getTableMappings();
while ( itr.hasNext() ) {
Table table = (Table) itr.next();
if ( table.isPhysicalTable() ) {
Iterator subItr = table.getForeignKeyIterator();
while ( subItr.hasNext() ) {
ForeignKey fk = (ForeignKey) subItr.next();
if ( fk.isPhysicalConstraint() ) {
script.add(
fk.sqlDropString(
dialect,
defaultCatalog,
defaultSchema
)
);
}
}
}
}
}
Iterator itr = getTableMappings();
while ( itr.hasNext() ) {