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

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



