import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory
sessionFactory = new Configuration().configure("/hibernate.cfg.xml")
.buildSessionFactory();
} catch (Throwable ex) {
ex.printStackTrace();
System.out.println("Initial SessionFactory creation failed.");
throw new ExceptionInInitializerError(ex);
}
}
public static final ThreadLocal tLocalsess = new ThreadLocal();
public static final ThreadLocal tLocaltx = new ThreadLocal();
/*
* getting the thread-safe session for using
*/
public static Session currentSession() {
Session session = (Session) tLocalsess.get();
//open a new one, if none can be found.
try {
if (session == null || !session.isOpen()) {
session = openSession();
tLocalsess.set(session);
}
} catch (HibernateException e) {
//throw new HibernateException(e);
e.printStackTrace();
}
return session;
}
/*
* closing the thread-safe session
*/
public static void closeSession() {
Session session = (Session) tLocalsess.get();
tLocalsess.set(null);
try {
if (session != null && session.isOpen()) {
session.close();
}
} catch (HibernateException e) {
//throw new InfrastructureException(e);
}
}
/*
* begin the transaction
*/
public static void beginTransaction() {
System.out.println("begin tx");
Transaction tx = (Transaction) tLocaltx.get();
try {
if (tx == null) {
tx = currentSession().beginTransaction();
tLocaltx.set(tx);
}
} catch (HibernateException e) {
//throw new InfrastructureException(e);
}
}
/*
* close the transaction
*/
public static void commitTransaction() {
Transaction tx = (Transaction) tLocaltx.get();
try {
if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack())
tx.commit();
tLocaltx.set(null);
} catch (HibernateException e) {
//throw new InfrastructureException(e);
}
}
/*
* for rollbacking
*/
public static void rollbackTransaction() {
Transaction tx = (Transaction) tLocaltx.get();
try {
tLocaltx.set(null);
if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
tx.rollback();
}
} catch (HibernateException e) {
//throw new InfrastructureException(e);
}
}
private static Session openSession() throws HibernateException {
return getSessionFactory().openSession();
}
private static SessionFactory getSessionFactory() throws HibernateException {
return sessionFactory;//SingletonSessionFactory.getInstance();
}
}
在Dao中:
打开一个session后,不关闭这个session,否则在级联的情况下可能会产生org.hibernate.LazyInitializationException:
所以定义一个过滤器:
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class CloseSessionFilter implements Filter {
Log logger = LogFactory.getLog(this.getClass());
/* (non-Javadoc)
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
protected FilterConfig config;
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
this.config = arg0;
}
/* (non-Javadoc)
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
// TODO Auto-generated method stub
try{
chain.doFilter((HttpServletRequest)request, (HttpServletResponse)response);
}
finally{
try{
HibernateUtil.commitTransaction();
}catch (Exception e){
HibernateUtil.rollbackTransaction();
}finally{
HibernateUtil.closeSession();
}
}
}
/* (non-Javadoc)
* @see javax.servlet.Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
this.config = null;
}
}
在web.xml中配置:
<filter>
<filter-name>closeSessionFilter</filter-name>
<filter-class>
utils.CloseSessionFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>closeSessionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
而到了spring 中,在web.xml配置:
<filter>
<filter-name>openSession</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</filter-class>
</filter>
分享到:
相关推荐
HibernateUtil 分页 增删改查 封装 HibernateUtil 分页 增删改查 封装 HibernateUtil 分页 增删改查 封装
HibernateUtil分装完整版HQL查询HibernateUtil分装完整版HQL查询
06_传智播客hibernate教程_完善HibernateUtil类及hql查询入门
hibernate入门实例封装了HibernateUtil,完成数据库的添加操作,和查询操作。 Session的save方法和get方法。
HibernateUtil工具类
Hibernate5.2.1 的工具类 创建session 和 sessionFactory
HibernateUtil.java HibernateUtils.java HttpRequester.java HttpRespons.java HttpUtil.java MD5Util.java Pagination.java PropertiesUtil.java RegUtil.java StringUtil.java UploadUtil.java UUIDUtils.java
欢迎大家咨询,我会尽量去与大家讲解,希望对你们有所帮助
} <br> public String createPasswordTicket(User user) { HibernateUtil.executeUpdate( "delete from PasswordTicket as pt where pt.user=?", new Object[] { user } ); String ...
SessionFactory factory = HibernateUtil.getSessionFactory(); Session session = factory.openSession(); Serializable id = null; Transaction tran = null; try{ tran = session.beginTransaction(); ...
生成HibernateSessionFactory工具类(HibernateUtil) ===利用Myeclipse根据表生成实体类和映射文件=== g.进入DB Browser窗口,找到数据表 h.数据表右键,选择Hibernate reverse Engin... i.选择要生成的文件hbm....
2、采用Jsp->Action->Service->Dao的编码方式,封装了HibernateUtil、SpringUtil、HqlUtil等工具,以及简化了增删查改操作。 3、此底层包含泛型DAO、Proxool连接池、国际化语言、DateUtil工具、ExcelUtil报表工具、...
06_完善HibernateUtil类及hql查询入门 07_实体类或属性名与数据库关键字冲突问题 10_使用Hibernate完成CRUD实验的步骤说明 11_完成CRUD实验并回顾和补充细节知识(上) 12_完成CRUD实验并回顾和补充细节知识(下...
(2)dao 使用了公共的GenricDao接口及实现类GenricHibernateDao 并使用了泛型 com.chen.common 包中的CopyOfGenericHibernateDao.java HibernateUtil.java两个是在集成Spring前使用的 可以当做参考吧; (3) ...
│ │ HibernateUtil.java │ │ UsersDAO.java │ │ │ └─entity │ BillEntity.java │ GoodsListEntity.java │ └─WebRoot │ index.jsp │ ├─img │ dn1.jpg │ dn2.jpg │ dn3.jpg │...
HibernateUtil タ・ <br>ミツスィメサタ・HibernateUtil」ャモヲクテハヌクコヤテ hibernate マ犹リイルラ」 ユ簑・メハヌエモヤュタエオトケ、ウフヨミスォホトシヨアスモソスアエタエモテ。」 ...
hibernate 一对多测试工程,博客介绍请参照: http://blog.csdn.net/smilefyx/article/details/48596665