您的位置:首页 > 其它

hibernate 本地线程绑定session

2017-03-31 11:39 465 查看
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