Hibernate-学习笔记03-getCurrentSession和openSession区别
SessionFactory得到Session的方法有两种getCurrentSession和openSession两种
?
?
更据Hibernate文档说明,在Hibernate3.2之后不再建议使用openSession,推荐使用getCurrentSession方法来获得Session对象。分别来说下两种获得Session的区别:
?
openSession:
表示创建一个Session,使用后需要关闭这个Session
getCurrentSession:
表示当前环境没有Session时,则创建一个,否则不用创建
?
?
上下文:
所指的上下文是指hibernate配置文件(hibernate.cfg.xml)中的“current_session_context_class”所指的值:(可取值:jta|thread|managed|custom.Class)
???常用的是:
①、thread:是从上下文找、只有当前没有Session时,才创建一个新的Session,主要从数据界定事务
②、jta:主要从分布式界定事务,运行时需要Application Server来支持(Tomcat不支持 )
?
?
③、managed:不常用
④、custom.Class:不常用
?
?
?
?
SessionFactory sf = new Configuration().configure().buildSessionFactory();//拿到当前session ,若是没有则创建一个session,若存在则拿当前的sessionSession session = sf.getCurrentSession();session.beginTransaction();session.save(student);session.getTransaction().commit();
?
?