SessionUtil class :-
- When there are some common method or logic is repeating multiple times, it is better to make this method to a util class.if this method is required then we can use this SessionUtil class.
- SessionFactory is heavy weight class and it’s not singleton, so we should make one SessionFactory per database.
- Using Util class we read the configuration file only once and we create one SesisonFactory.
- we are get the session object from SessionFactory and after complete the work then close the session object.
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public final class SessionUtil {
private final SessionFactory sessionFactory;
private static SessionUtil instance;
private SessionUtil() {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
StandardServiceRegistryBuilder serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
public synchronized static SessionUtil getInstance() {
if (instance == null) {
instance = new SessionUtil();
}
return instance;
}
public static Session getSession() {
return getInstance().sessionFactory.openSession();
}
}