Hibernate openSession()和getCurrentSession()的区别


附Hibernate的session与本地线程绑定的方法:

1.在核心映射文件hibernate.cfg.xml里添加:

<!-- 在hibernate.cfg.xml中配置,也就是Hibernate核心配置文件中。配置部位是在第二部分。 -->
		<property name="hibernate.current_session_context_class">thread</property>

thread:Session对象的生命周期与本地线程绑定

jta:Session对象的生命周期与JTA事务绑定

managed:Hibernate委托程序来管理Session对象的生命周期

这里用thread。

2.在HibernateUtils.java添加用本地线程返回session的方法:

public static Session getCurrentSession(){//在工具类里面获取与本地线程绑定的session。
        return sf.getCurrentSession();//static SessionFactory sf = null;
    }

3.测试

Transaction tx=null;
    Session session=null;
	
	/**
	 * 添加
	 */
	@Test
	public void add(){
		//1.
		/*Configuration cfg = new Configuration();
		cfg.configure();*/
		//2.
		//SessionFactory sessionFactory = cfg.buildSessionFactory();
		
		
		
		
		//SessionFactory sessionFactory = HIbernateUtils.getSessionFactory();
		//3.
		//Session session = sessionFactory.openSession();
		
		
		//本地线程获取session
		try {
			session = HIbernateUtils.getCurrentSession();
			
			//4.
			tx = session.beginTransaction();
			//5.
			User user = new User();
			user.setAddress("gz");
			user.setPassword("887799");
			user.setUsername("iter");
			//6.
			session.save(user);
			//7.
			tx.commit();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//本地线程获取session不需要关闭session
		//session是绑定了本地线程的session,当本地线程被关闭后,session也就自然而然的被关闭了。
		
		//8.
		//session.close();
	    //sessionFactory.close();
注意事项见上面注释。

猜你喜欢

转载自blog.csdn.net/lihai755/article/details/80171842
今日推荐