Hibernate各类概念-openSession与getCurrentSession的区别
2018-01-31 11:34
435 查看
Hibernate有两种方式获得session,分别是:
openSession和getCurrentSession
他们的区别在于
1. 获取的是否是同一个session对象
openSession每次都会得到一个新的Session对象
getCurrentSession在同一个线程中,每次都是获取相同的Session对象,但是在不同的线程中获取的是不同的Session对象
2. 事务提交的必要性
openSession只有在增加,删除,修改的时候需要事务,查询时不需要的
getCurrentSession是所有操作都必须放在事务中进行,并且提交事务后,session就自动关闭,不能够再进行关闭
OpenSession每次都会得到一个新的Session对象
OpenSession每次都会得到一个新的Session对象,所以System.out.println(s1==s2);会打印false
相同线程的getCurrentSession
如果是同一个线程(本例是在主线程里),每次获取的都是相同的Session
openSession和getCurrentSession
他们的区别在于
1. 获取的是否是同一个session对象
openSession每次都会得到一个新的Session对象
getCurrentSession在同一个线程中,每次都是获取相同的Session对象,但是在不同的线程中获取的是不同的Session对象
2. 事务提交的必要性
openSession只有在增加,删除,修改的时候需要事务,查询时不需要的
getCurrentSession是所有操作都必须放在事务中进行,并且提交事务后,session就自动关闭,不能够再进行关闭
OpenSession每次都会得到一个新的Session对象
OpenSession每次都会得到一个新的Session对象,所以System.out.println(s1==s2);会打印false
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class TestHibernate { public static void main(String[] args) { SessionFactory sf = new Configuration().configure().buildSessionFactory(); Session s1 = sf.openSession(); Session s2 = sf.openSession(); System.out.println(s1==s2); s1.close(); s2.close(); sf.close(); } }
相同线程的getCurrentSession
如果是同一个线程(本例是在主线程里),每次获取的都是相同的Session
相关文章推荐
- Hibernate各类概念-openSession和getCurrentSession的区别
- (hibernate之一)Sessionfactory的getCurrentSession与openSession的区别
- Hibernate 中 openSession()和getCurrentSession() 的区别
- 关于spring+hibernate中的OpenSession()和getCurrentSession()的区别
- Hibernate 之getCurrentSession 与 openSession() 的区别
- 【Hibernate】OpenSession和getCurrentSession的区别
- hibernate: openSession() 和getCurrentSession()的区别
- Hibernate的getCurrentSession()和openSession()的区别和使用
- hibernate 的SessionFactory的getCurrentSession 与 openSession() 的区别
- hibernate 的SessionFactory的getCurrentSession 与 openSession() 的区别
- (hibernate之一)Sessionfactory的getCurrentSession与openSession的区别
- 【Hibernate】SessionFactory中的getCurrentSession()和openSession()的区别
- Hibernate 之getCurrentSession 与 openSession() 的区别
- hibernate的SessionFactory的getCurrentSession 与 openSession() 的区别
- hibernate中getCurrentSession()和openSession()区别。
- hibernate 的openSession和getCurrentSession的区别
- hibernate 的SessionFactory的getCurrentSession 与 openSession() 的区别
- Hibernate 中的 openSession和getCurrentSession 方法的区别
- hibernate中openSession()跟getCurrentSession()方法之间的区别
- Hibernate中的openSession(),getSession() 和 getCurrentSession() 的区别