diff --git a/src/main/java/com/example/cosmos_serversb/models/SessionFactoryManager.java b/src/main/java/com/example/cosmos_serversb/models/SessionFactoryManager.java new file mode 100644 index 0000000..c0a0e56 --- /dev/null +++ b/src/main/java/com/example/cosmos_serversb/models/SessionFactoryManager.java @@ -0,0 +1,52 @@ +package com.example.cosmos_serversb.models; + +import org.hibernate.SessionFactory; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistry; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; + +import javax.inject.Singleton; + + +@Singleton +public class SessionFactoryManager { + private static SessionFactoryManager theInstance = null; + private static SessionFactory sessionFactory; + + private SessionFactoryManager(){ + setUp(); + } + + public static SessionFactoryManager getInstance(){ + if(theInstance == null){ + theInstance = new SessionFactoryManager(); + } + return theInstance; + } + + public static void setUp() { + // A SessionFactory is set up once for an application! + final StandardServiceRegistry registry = new StandardServiceRegistryBuilder() + .configure() // configures settings from hibernate.cfg.xml + .build(); + try { + sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory(); + } + catch (Exception e) { + // The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory + // so destroy it manually. + StandardServiceRegistryBuilder.destroy( registry ); + } + } + + public static void tearDown() { + try { + if ( sessionFactory != null ) { + sessionFactory.close(); + } + } catch (Exception e) { + System.out.println("Exception!"); + } + } + +}