1
+ package com .baeldung .hibernate .exception ;
2
+
3
+ import java .io .FileInputStream ;
4
+ import java .io .IOException ;
5
+ import java .net .URL ;
6
+ import java .util .Properties ;
7
+
8
+ import org .apache .commons .lang3 .StringUtils ;
9
+ import org .hibernate .SessionFactory ;
10
+ import org .hibernate .boot .Metadata ;
11
+ import org .hibernate .boot .MetadataSources ;
12
+ import org .hibernate .boot .registry .StandardServiceRegistryBuilder ;
13
+ import org .hibernate .service .ServiceRegistry ;
14
+
15
+ public class HibernateUtil {
16
+ private static SessionFactory sessionFactory ;
17
+ private static String PROPERTY_FILE_NAME ;
18
+
19
+ public static SessionFactory getSessionFactory () throws IOException {
20
+ return getSessionFactory (null );
21
+ }
22
+
23
+ public static SessionFactory getSessionFactory (String propertyFileName )
24
+ throws IOException {
25
+ PROPERTY_FILE_NAME = propertyFileName ;
26
+ if (sessionFactory == null ) {
27
+ ServiceRegistry serviceRegistry = configureServiceRegistry ();
28
+ sessionFactory = makeSessionFactory (serviceRegistry );
29
+ }
30
+ return sessionFactory ;
31
+ }
32
+
33
+ private static SessionFactory makeSessionFactory (
34
+ ServiceRegistry serviceRegistry ) {
35
+ MetadataSources metadataSources = new MetadataSources (serviceRegistry );
36
+ metadataSources .addAnnotatedClass (Product .class );
37
+ Metadata metadata = metadataSources .getMetadataBuilder ()
38
+ .build ();
39
+ return metadata .getSessionFactoryBuilder ()
40
+ .build ();
41
+
42
+ }
43
+
44
+ private static ServiceRegistry configureServiceRegistry ()
45
+ throws IOException {
46
+ Properties properties = getProperties ();
47
+ return new StandardServiceRegistryBuilder ().applySettings (properties )
48
+ .build ();
49
+ }
50
+
51
+ private static Properties getProperties () throws IOException {
52
+ Properties properties = new Properties ();
53
+ URL propertiesURL = Thread .currentThread ()
54
+ .getContextClassLoader ()
55
+ .getResource (StringUtils .defaultString (PROPERTY_FILE_NAME ,
56
+ "hibernate-exception.properties" ));
57
+ try (FileInputStream inputStream = new FileInputStream (
58
+ propertiesURL .getFile ())) {
59
+ properties .load (inputStream );
60
+ }
61
+ return properties ;
62
+ }
63
+ }
0 commit comments