博为峰小博老师:数据库
Session对象是Hibernate中数据库持久化操做的核心,它负责Hibernate全部的持久化操做,经过它开发人员能够实现数据库基本的增、删、查、改的操做。而Session对象又是经过SessionFactory对象获取的,能够经过Configuration对象建立SessionFactory,关健代码以下:session
Configuration对象会加载Hibernate的基本配置信息,若是没有在configure()方法中指定加载配置XML文档的路径信息,Configuration对象会默认加载项目classpath根目录下的hibernate.cfg.xml文件。ui
建立HibernateUtil类,用于实现对Hibernate的初始化。代码以下:spa
public class HibernateUtil {hibernate
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";code
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();xml
private static Configuration configuration = new Configuration(); 对象
private static org.hibernate.SessionFactory sessionFactory; //SessionFactory对象blog
private static String configFile = CONFIG_FILE_LOCATION;ip
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();
}
}
}