您的位置:首页 > 其它

Hibernate事务的高级应用

2012-10-29 21:48 253 查看
第一步:创建静态成员
在HibernateUtil类中我们需要定义一个静态的成员变量用于保存当前线程共用的Session :

private static ThreadLocal<Session>sessionLocal = new
ThreadLocal<Session>();

第二步:修改获取session的方法
改造HibernateUtil类的获取Session方法:

/**
* @return获取当前线程容器中的SESSION
*/
public static Session getThreadLocalSession() {
// 获取当前线程中的SESSION
Session s = sessionLocal.get();
if (s == null) {
// 如果为空,则新建一个SESSION
s = getSessionFactory().getCurrentSession ();
// 需要将新的SESSION放入到当前线程容器中
sessionLocal.set(s);
}
return s;
}

第三步:配置Hibernate.cfg.xml
Hibernate.cfg.xml文件中添加配置:

<propertyname="current_session_context_class">thread</property>

第四步:添加监听器
添加OpenSessionInViewFilter过滤器
public void doFilter(ServletRequest request, ServletResponseresponse,
FilterChain filterChain) throws IOException, ServletException {
Session s =HibernateUtil.getThreadLocalSession();
Transaction t = null;
try {
// 开始事务
t = s.beginTransaction();
// 进入一系列的过滤链,处理相应的ACTION、业务逻辑及数据层
filterChain.doFilter(request, response);
// 提交事务
t.commit();
} catch (Exceptione) {
if (t != null)
t.rollback();
throw new RuntimeException(e.getMessage(), e);
} finally {
HibernateUtil.closeSession();
}
}

第五步:在web.xml中配置filter
关于getCurrentSession()方法:

sessionFactory.getCurrentSession()可以完成一系列的工作,当调用时,

hibernate将session绑定到当前线程,事务结束后,hibernate

将session从当前线程中释放,并且关闭session。当再次调用getCurrentSession

()时,将得到一个新的session,并重新开始这一系列工作。

这样调用方法如下:

Session session = HibernateUtil.getSessionFactory().getCurrentSession();

getCurrentSessionopenSession的区别:

getCurrentSession创建的session会和绑定到当前线程,而openSession不会。
getCurrentSession创建的线程会在事务回滚或事物提交后自动关闭,而openSession必须手动关闭

添加HibernateUtil类中清除线程容器Session的方法:(这个方法是使用openSession创建session时使用的)

/**
* 关闭当前线程容器中的SESSION
*/
public static void closeSession() {
Session s = sessionLocal.get();
if (s != null) {
// 清除当前线程容器中的SESSION
sessionLocal.set(null);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: