Created
February 16, 2018 12:56
-
-
Save ajfmo/15cdc4bed75f6d3adc19511aa5ee783d to your computer and use it in GitHub Desktop.
Hibernate singleton class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.hibernate.Session; | |
import org.hibernate.SessionFactory; | |
import org.hibernate.boot.MetadataSources; | |
import org.hibernate.boot.registry.StandardServiceRegistry; | |
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; | |
public class HibernateUtil { | |
private static SessionFactory factory; | |
private static StandardServiceRegistry registry; | |
public static synchronized Session getSessionFactory() { | |
if (factory == null) { | |
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder() | |
.configure("/config/hibernate.cfg.xml").build(); | |
try { | |
factory = new MetadataSources(registry).buildMetadata().buildSessionFactory(); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
if (registry != null) { | |
StandardServiceRegistryBuilder.destroy(registry); | |
} | |
} | |
} | |
return factory.openSession(); | |
} | |
public static void shutdown() { | |
if (registry != null && factory != null) { | |
factory.close(); | |
StandardServiceRegistryBuilder.destroy(registry); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment