Singleton SessionFactory doesn't work for Hibernate 4.3.1

145 Views Asked by At

i am building a product management system and i prepared my database pojos. After that i wanted to use singleton sessionFactory instead of using a new one in each class. When i create and build a Java class as;

package Controller;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class SFController {

private static SFController instance = null;

   private static SessionFactory sessionFactory;
   private static StandardServiceRegistry serviceRegistry;

   private SFController(){
        Configuration configuration = new Configuration();
        configuration.configure();
        serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
   }

   public static SFController getInstance(){
        if(instance == null){
            instance  = new SFController();
        }
        return instance;
   }

   public synchronized static SessionFactory getSessionFactory() {
        return sessionFactory;
   }

}

there is nothing wrong. But i couldn' figure out how to use it in my controller pages properly. That is how i try;

package Controller;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;


public class TryObject {
    
    SFController newObject = SFController.getInstance();
    Session session = newObject.getSessionFactory();
        
    
}

Second line of TryObject method says change Session to SessionFactory. Even if i do that, i can't reach session.save() or session.beginTransaction(); Tried a few more singleton examples but couldn't figure it out. I would be glad if you can tell me what am i doing wrong.

1

There are 1 best solutions below

2
Guillaume On

Your getSessionFactory() method returns a SessionFactory, not a Session. Once you have a SessionFactory you can open a new Session:

SFController newObject = SFController.getInstance();
SessionFactory factory = newObject.getSessionFactory();
Session session = factory.openSession();