📄 hibernateutil.java
字号:
/*
* description: 对sessionFactory的初始化设置与使用;从SessionFactory获取一个Hibernate的工作单元session。
*
* Created on 2005-7-4
* @author WuQiaoYun
*
* Modified on
*/
package com.common.util;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* 对sessionFactory的初始化设置与使用;从SessionFactory获取一个Hibernate的工作单元session。
* @author WuQiaoYun
*/
public class HibernateUtil {
/**
* sessionFactory对象
*/
public static final SessionFactory sessionFactory;
/**
* 静态块,初始化sessionFactory
*/
static {
try {
sessionFactory=new Configuration().configure().buildSessionFactory();
}catch(Throwable te) {
System.err.println("Initial SessionFactory creation failed."+te);
throw new ExceptionInInitializerError(te);
}
}
/**
* 初始化ThreadLocal对象
*/
public static final ThreadLocal session = new ThreadLocal();
/**
* function:获取一个当前的hibernate的工作单元session,并返回
*
* @return Session 返回hibernate的工作单元session
*/
public static Session currentSession() throws HibernateException{
Session s = (Session)session.get();
if (s==null) {
s = sessionFactory.openSession();
session.set(s);
}
return s;
}
/**
* function: close 当前的hibernate的工作单元session
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException{
Session s = (Session)session.get();
if (s!=null) {
s.close();
}
session.set(null);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -