1.在hibernate.cfg.xml中加入:
<property name="hibernate.current_session_context_class">thread</property>
2.在sessionFactory方法中获取
在UserUntil.java中加入
//返回与本地线程绑定的session的方法
public static Session getSessionobj(){
return sessionFactory.getCurrentSession();
}
3.UserTrans.java
package cn.hiber;
import org.hibernate.Session;
/*import org.hibernate.SessionFactory;*/
import org.hibernate.Transaction;
import org.junit.Test;
public class UserTrans {
@Test
public void testTx(){
/*SessionFactory sessionFactory=null;*/
Session session=null;
Transaction tx=null;
try {
/* sessionFactory=UserUntil.getSessionFactory();
session=sessionFactory.openSession();*/
//获取本地线程绑定的session
session=UserUntil.getSessionobj();
//开始事务
tx=session.beginTransaction();
//添加
User user=new User();
user.setUsername("qqqqeww");
user.setPassword("12345");
session.save(user);
//提交事务
tx.commit();
} catch (Exception e) {
tx.rollback();
}/*finally{
session.close();
sessionFactory.close();
}*/
}
}
本文介绍如何在Hibernate中使用本地线程绑定的Session进行事务管理。通过配置hibernate.current_session_context_class属性为'thread'实现Session与线程的绑定,并通过UserUntil类提供获取当前线程绑定的Session的方法。最后,在UserTrans类中演示了事务的开始、提交及回滚。
1049

被折叠的 条评论
为什么被折叠?



