📄 hibernateutil.java
字号:
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 + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -