package com.cym.model;
import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;
public class HibernateSessionFactory { public static ThreadLocal thread_var=new ThreadLocal(); private static final SessionFactory sessionfactory; static { try { Configuration config = new Configuration(); config.configure("/hibernate.cfg.xml"); sessionfactory = config.buildSessionFactory(); //sessionfactory=new Configuration().configure("/hibernate.cfg.xml").buildSessionFactory(); } catch (Exception e) { throw new RuntimeException("Exception Building SessionFactory" + e.getMessage(), e); } }
public static Session getSession() { Session session =(Session)thread_var.get(); try { if(session==null){ session = sessionfactory.openSession(); thread_var.set(session); } } catch (Exception e) { e.printStackTrace(); } return session; }
public static void closeSession() { Session session=(Session)thread_var.get(); if (session != null) { session.close(); } thread_var.set(null); }}
