Hibernate中的getCurrentSession和openSession

本文介绍了一个简单的Hibernate使用案例,展示了如何通过SessionFactory获取当前Session,并利用Session进行数据持久化操作。同时,文中还对比了getCurrentSession与openSession的区别,并演示了在事务提交后Session的变化。

@Test public void T1() { Teacher t = new Teacher(); t.setGender(Gender.femal); t.setName("abc"); t.setId(2); t.setGood(true); Session session,session2; /** * getCurrentSession,如果当前上下文环境中有Session, * 则无须创建就会拿当前环境的Session,当commit时会自动 * close */ session = sf.getCurrentSession();//无须session.close(); /** * openSession用于是打开新的Session * 需要用session.close(); */ //Session session = sf.openSession(); session.beginTransaction(); session.save(t); session2 = sf.getCurrentSession(); System.out.println(session == session2);//true /** * 将会导致第一个Session消失, * 再次获取将导致新的Session产生 */ session.getTransaction().commit();// Session session3 = sf.getCurrentSession(); System.out.println(session2 == session3);//false }

转自:

http://xredman.javaeye.com/blog/783761

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值