HIbernate中openSession和getCurrentSession
2015-07-14 17:00
363 查看
这两者的区别网上很多资源,我这里就copy一下了,然后有点问题的是今天遇到的问题。
openSession和getCurrentSession的根本区别在于有没有绑定当前线程,所以,使用方法有差异:
* openSession没有绑定当前线程,所以,使用完后必须关闭,
* currentSession和当前线程绑定,在事务结束后会自动关闭。
今天在复习Hibernate时,看到Hibernate检索方式的时候,写了一个小例子:
hibernate.cfg.xml中配置了
这里已经写了注释,我遇到的问题就是这个,在进行查询的时候使用getCurrentSession竟然抛出 createQuery is not valid without active transaction的异常,觉得很奇怪。
按照文档说:getCurrentSession()方法获取Session的机制应该是
“在getCurrentSession() 被调用的时候,实际被执行的方法是CurrentSessionContext.currentSession() 。在currentSession() 执行时,如果当前 Session为空,currentSession会调用 SessionFactory 的 openSession。”
现在的状态是符合Session为空的情况,那么就应该通过openSession()方法产生一个Session,但是却抛出了异常。
Google了一下,找到一篇博文:http://liusu.iteye.com/blog/380397
里面介绍了关于这个问题,英文有点水,理解就看自己了。
我的感觉就是出现这种情况感觉openSession相对来说还好用一些了。
可能比较片面,但是目前还没有到那个层面,慢慢来,就像之前看这两个的区别一样,一直看不懂,慢慢的积累到一定层度就会很好理解了。
openSession和getCurrentSession的根本区别在于有没有绑定当前线程,所以,使用方法有差异:
* openSession没有绑定当前线程,所以,使用完后必须关闭,
* currentSession和当前线程绑定,在事务结束后会自动关闭。
今天在复习Hibernate时,看到Hibernate检索方式的时候,写了一个小例子:
@Test public void query01() { SessionFactory sessionFactory = new Configuration().configure() .buildSessionFactory(); Session session = sessionFactory.getCurrentSession(); /* * 使用getCurrentSession()必须开启事物,否则抛出异常org.hibernate.HibernateException: * createQuery is not valid without active transaction */ session.beginTransaction(); Query query = session.createQuery("from Employee"); System.out.println(query.list()); }
hibernate.cfg.xml中配置了
<property name="current_session_context_class">thread</property>
这里已经写了注释,我遇到的问题就是这个,在进行查询的时候使用getCurrentSession竟然抛出 createQuery is not valid without active transaction的异常,觉得很奇怪。
按照文档说:getCurrentSession()方法获取Session的机制应该是
“在getCurrentSession() 被调用的时候,实际被执行的方法是CurrentSessionContext.currentSession() 。在currentSession() 执行时,如果当前 Session为空,currentSession会调用 SessionFactory 的 openSession。”
现在的状态是符合Session为空的情况,那么就应该通过openSession()方法产生一个Session,但是却抛出了异常。
Google了一下,找到一篇博文:http://liusu.iteye.com/blog/380397
里面介绍了关于这个问题,英文有点水,理解就看自己了。
我的感觉就是出现这种情况感觉openSession相对来说还好用一些了。
@Test public void query02() { SessionFactory sessionFactory = new Configuration().configure() .buildSessionFactory(); Session session = sessionFactory.openSession();; try { Query query = session.createQuery("from Employee"); System.out.println(query.list()); } catch (HibernateException e) { e.printStackTrace(); }finally{ session.close(); } }
可能比较片面,但是目前还没有到那个层面,慢慢来,就像之前看这两个的区别一样,一直看不懂,慢慢的积累到一定层度就会很好理解了。
相关文章推荐
- 每天一个linux命令day2【ss命令】
- 内部OA系统:Nginx+Keepalived实现站点高可用
- 使用ffmpeg进行图像格式转换以及图像缩放/sws_scale/linux/c++/c/rgb-yuv420
- nginx中的request
- Linux 安装jdk 以及部署 tomcat
- 在Ubuntu中通过update-alternatives切换软件版本
- open,write等基本系统IO的带缓冲与不带缓冲的差别
- mod_gsoap(gsoap与Apache服务器的集成)
- Shell脚本入门学习笔记
- 一步步构建大型网站架构
- linux中shell变量$#,$@,$0,$1,$2的含义解释
- nginx中connection概念
- 每天一个linux命令(12):more命令
- linux基础之spi驱动程序理解
- nginx----hash
- linux c获取mac
- linux系统中python导入其他的目录下的文件
- 解决nginx无法启动, bind() to 0.0.0.0:8080 failed的错误
- linux c获取IP地址
- linux ioctl函数