|
| 1 | +package com.baeldung.hibernate.onetoone; |
| 2 | + |
| 3 | +import com.baeldung.hibernate.customtypes.LocalDateStringType; |
| 4 | +import org.hibernate.SessionFactory; |
| 5 | +import org.hibernate.boot.Metadata; |
| 6 | +import org.hibernate.boot.MetadataSources; |
| 7 | +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; |
| 8 | +import org.hibernate.service.ServiceRegistry; |
| 9 | + |
| 10 | +import java.io.FileInputStream; |
| 11 | +import java.io.IOException; |
| 12 | +import java.net.URL; |
| 13 | +import java.util.Properties; |
| 14 | + |
| 15 | +public class HibernateUtil { |
| 16 | + private static SessionFactory sessionFactory; |
| 17 | + |
| 18 | + private HibernateUtil() { |
| 19 | + } |
| 20 | + |
| 21 | + public static SessionFactory getSessionFactory(Strategy strategy) { |
| 22 | + if (sessionFactory == null) { |
| 23 | + sessionFactory = buildSessionFactory(strategy); |
| 24 | + } |
| 25 | + return sessionFactory; |
| 26 | + } |
| 27 | + |
| 28 | + private static SessionFactory buildSessionFactory(Strategy strategy) { |
| 29 | + try { |
| 30 | + ServiceRegistry serviceRegistry = configureServiceRegistry(); |
| 31 | + |
| 32 | + MetadataSources metadataSources = new MetadataSources(serviceRegistry); |
| 33 | + |
| 34 | + for (Class<?> entityClass : strategy.getEntityClasses()) { |
| 35 | + metadataSources.addAnnotatedClass(entityClass); |
| 36 | + } |
| 37 | + |
| 38 | + Metadata metadata = metadataSources.getMetadataBuilder() |
| 39 | + .applyBasicType(LocalDateStringType.INSTANCE) |
| 40 | + .build(); |
| 41 | + |
| 42 | + return metadata.getSessionFactoryBuilder() |
| 43 | + .build(); |
| 44 | + } catch (IOException ex) { |
| 45 | + throw new ExceptionInInitializerError(ex); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + |
| 50 | + private static ServiceRegistry configureServiceRegistry() throws IOException { |
| 51 | + Properties properties = getProperties(); |
| 52 | + return new StandardServiceRegistryBuilder().applySettings(properties) |
| 53 | + .build(); |
| 54 | + } |
| 55 | + |
| 56 | + private static Properties getProperties() throws IOException { |
| 57 | + Properties properties = new Properties(); |
| 58 | + URL propertiesURL = Thread.currentThread() |
| 59 | + .getContextClassLoader() |
| 60 | + .getResource("hibernate.properties"); |
| 61 | + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { |
| 62 | + properties.load(inputStream); |
| 63 | + } |
| 64 | + return properties; |
| 65 | + } |
| 66 | +} |
0 commit comments