Session对象是Hibernate中数据库持久化操作的核心,它负责Hibernate所有的持久化操作,通过它开发人员可以实现数据库基本的增、删、查、改的操作。而Session对象又是通过SessionFactory对象获取的,可以通过Configuration对象创建SessionFactory,关健代码如下:
Configuration对象会加载Hibernate的基本配置信息,如果没有在configure()方法中指定加载配置XML文档的路径信息,Configuration对象会默认加载项目classpath根目录下的hibernate.cfg.xml文件。
创建HibernateUtil类,用于实现对Hibernate的初始化。代码如下:
public class HibernateUtil {
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory; //SessionFactory对象
private static String configFile = CONFIG_FILE_LOCATION;
static {
try {
configuration.configure(configFile);//加载Hibernate配置文件
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* 获取Session
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
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();
}
}
/**
* 获取SessionFactory对象
*/
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
/**
* 关闭Session
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
}