创建Session类
- 在辅助类中从Configuration得到SessionFactory
- 通过辅助类创建Session类的实例
- 使用Session类的各个方法来完成持久化的工作
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class HibernateSessionFactory {
// 设定配置文件hibernate.cfg.xml的路径,本例直接设定在classpath下
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
// 保持一个单例的Session所使用的ThreadLocal
private static final ThreadLocal threadLocal = new ThreadLocal();
// 一个单例的Configuration类实例
private static Configuration configuration = new Configuration();
// 一个单例的SessionFactory类实例
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;
private HibernateSessionFactory() {
}
// 返回一个Session实例的单例方法,它将保持永远只返回一个Session实例
public static Session getSession() throws HibernateException {
// 从ThreadLocal类中取得一个Session实例
// ThreadLocal类保证每个实例都有自己的数据库连接
Session session = (Session) threadLocal.get();
// 若该Session实例为null则创建一个新的Session实例;否则就会直接返回已存在的Session实例
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
// 将创建的Session实例放入当前线程中
threadLocal.set(session);
}
return session;
}
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
//关闭一个单例Session实例
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}
public static Configuration getConfiguration() {
return configuration;
}
}(我这个HibernateSessionFactory是由MyEclipse自动生成的)

1679

被折叠的 条评论
为什么被折叠?



