67,514
社区成员
发帖
与我相关
我的任务
分享
public class HibernateUtil {
private static Configuration config;
private static SessionFactory sessionFactory;
private static Session session;
private static Transaction tx;
private static final ThreadLocal local = new ThreadLocal();
/**
* 初始化配置文件,放在静态代码块中,表示只执行一次
*/
static {
config = new Configuration().configure();
sessionFactory = config.buildSessionFactory();
}
/**
* 获取Session
*
*/
public static Session getSession() {
session = (Session) local.get();
if (session == null) {
session = sessionFactory.openSession();
}
tx = session.beginTransaction();
return session;
}
/**
* 关闭Session
*/
public static void close() {
if (session != null) {
tx.commit();
session.close();
}
}
}
package util;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
public static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration config = new Configuration().configure();
sessionFactory = config.buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static final ThreadLocal session = new ThreadLocal();
public static Session currentSession() throws HibernateException {
Session s = (Session) session.get();
// Open a new Session, if this thread has none yet
if (s == null) {
s = sessionFactory.openSession();
// Store it in the ThreadLocal variable
session.set(s);
}
return s;
}
public static void closeSession() throws HibernateException {
Session s = (Session) session.get();
if (s != null)
s.close();
session.set(null);
}
}