通過getCurrentSession()創建的Session會綁定到當前線程上;openSession()不會。通過getCurrentSession()獲取Session,首先是從當前上下文中尋找舊的Session,如果沒有,則創建新的Session;而openSession()是每次都創建新的Session。getCurrentSession()創建的Session在事物提交時自動關閉;openSession()創建的Session需要手動關閉。 1 @Test
2 public void testTeacherSave() {
3
4 Teacher t = new Teacher();
5
6 t.setName("t1");
7 t.setTitle("middle");
8 t.setBirthDate(new Date());
9
10 Session session = sessionFactory.openSession();
11 //Session session = sessionFactory.getCurrentSession();
12
13 session.beginTransaction();
14 session.save(t);
15
16 Session session2 = sessionFactory.getCurrentSession();
17
18 System.out.println(session == session2);
19
20 session.getTransaction().commit();
21
22 Session session3 = sessionFactory.getCurrentSession();
23
24 System.out.println(session == session3);
25
26 }
輸出:Hibernate:
??? insert
??? into
??????? Teacher
??????? (birthDate, gender, good, name, title)
??? values
??????? (?, ?, ?, ?, ?)
false
false
1 @Test
2 public void testTeacherSave() {
3
4 Teacher t = new Teacher();
5
6 t.setName("t1");
7 t.setTitle("middle");
8 t.setBirthDate(new Date());
9
10 //Session session = sessionFactory.openSession();
11 Session session = sessionFactory.getCurrentSession();
12
13 session.beginTransaction();
14 session.save(t);
15
16 Session session2 = sessionFactory.getCurrentSession();
17
18 System.out.println(session == session2);
19
20 session.getTransaction().commit();
21
22 Session session3 = sessionFactory.getCurrentSession();
23
24 System.out.println(session == session3);
25
26 } 輸出:Hibernate:
??? insert
??? into
??????? Teacher
??????? (birthDate, gender, good, name, title)
??? values
??????? (?, ?, ?, ?, ?)
true
false
轉載于:https://www.cnblogs.com/ming-zi/p/5937961.html
總結
以上是生活随笔為你收集整理的Hibernate getCurrentSession()和openSession()的区别的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。