---
title: "Hibernate中openSession 和 getCurrentSession"
author: "Spring_g"
date: "2013-03-12T19:22:25Z"
tags: []
categories: ["编程语言"]
slug: "hibernate-opensession-getcurrentsession"
draft: false
lastmod: "2013-03-12T19:22:25Z"
id: 1828351
url: "https://isource.iteye.com/blog/1828351"
---

Hibernate openSession() 和 getCurrentSession的区别:
①.采用getCurrentSession()创建的Session会绑定到当前的线程当中，openSession不会
②.采用getCurrentSession()创建的Session在commit或rollback后会自动关闭，采用OpenSession()必须手动关闭。 
③.采用getCurrentSession()需要在Hibernate.cfg.xml配置文件中加入如下配置： 
    具体的配置也要根据不同的事务进行不同的配置。
④、MyEclipse生成的是没有和事务相关的操作的，进行数据库查找操作时，openSession是不需要提交事务的。getCurrentSession则必须要打开一个新的事务，否则会报createQuery is not valid without active transaction错误。这也是MyEclipse自动生成的Hibernate DAO类中在对session的获取中，都使用的getSession（MyEclipse8.5之前的版本都是如此）的原因。
注：getSession调用的是openSession，其实也就是openSession和getCurrentSession的区别。