hibernateutil.java
来自「《基于Eclipse的开源框架技术与实战》[第8章]随书源码」· Java 代码 · 共 52 行
JAVA
52 行
package com.free.hibernate.util;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* <p>Title: Eclipse Plugin Development</p>
* <p>Description: Free download</p>
* <p>Copyright: Copyright (c) 2006</p>
* <p>Company: Free</p>
* @author gan.shu.man
* @version 1.0
*/
public class HibernateUtil {
public static SessionFactory sessionFactory;
public static final ThreadLocal session = new ThreadLocal();
/**
* 创建SessionFactory对象
*/
public static void buildSessionFactory() {
try {
// 从hibernate.cfg.xml创建SessionFactory
sessionFactory = new Configuration().configure()
.buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
/**
* 从SessionFactory
*/
public static Session currentSession() throws HibernateException {
// 从ThreadLocal取出Session对象
Session s = (Session) session.get();
// 如果ThreadLocal中Session对象为空,则创建Session
if (s == null) {
s = sessionFactory.openSession();
// 把Session保存,做为ThreadLocal的变量副本
session.set(s);
}
return s;
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?