Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ajfmo
Created February 16, 2018 12:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajfmo/15cdc4bed75f6d3adc19511aa5ee783d to your computer and use it in GitHub Desktop.
Save ajfmo/15cdc4bed75f6d3adc19511aa5ee783d to your computer and use it in GitHub Desktop.
Hibernate singleton class
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