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