Spring与Hibernate集成中的session问题

[b]主要讨论Spring与Hibernate集成中的session问题[/b]

[size=medium][color=red][b]1.通过getSession()方法获得session进行操作[/b][/color][/size]
public class Test  extends HibernateDaoSupport{
public void save(User user){
this.getSession().save(user);
}
}

[b][color=red]利用这种方式获得的session在方法执行结束之后不会自动关闭连接[/color],也就是说我们必须通过session.close()或者releaseSession(session)来手动进行关闭,否则会造成内存泄露或者连接耗尽等问题。手动关闭:[/b]
public class Test  extends HibernateDaoSupport{
public void save(User user){
Session session = this.getSession();
session.save(user);
session.close();
// releaseSession(session);
}
}

[b]如果对上述方法进行事务控制,那么spring框架会自动为我们关闭session,此种情况下再执行上述代码,会抛出如下异常:[/b]
 org.springframework.orm.hibernate3.HibernateSystemException: Session is closed; nested exception is org.hibernate.SessionException: Session is closed

org.hibernate.SessionException: Session is closed

[b]提示session已经关闭。但是如果在代码中通过releaseSession(session)的方法来关闭session,则不会抛出异常。releaseSession(session)方法的代码如下:[/b]
	protected final void releaseSession(Session session) {
SessionFactoryUtils.releaseSession(session, getSessionFactory());
}

[b]也就是说它是通过SessionFactoryUtils的releaseSession方法来实现的:[/b]
public static void releaseSession( 
Session session,SessionFactory sessionFactory) {
if (session == null) {
return;
}
// Only close non-transactional Sessions.
if (!isSessionTransactional(session,sessionFactory)) {
closeSessionOrRegisterDeferredClose (session, sessionFactory);
}
}

[b]可见它内部会先进行判断。[/b]

[b]查看getSession()方法的源码:[/b]
protected final Session getSession()
throws DataAccessResourceFailureException, IllegalStateException {

return getSession(this.hibernateTemplate.isAllowCreate());
}

[b]getSession()方法内部通过它的一个重载方法getSession(boolean allowCreate )来实现,变量allowCreate是HibernateTemplate中的变量,默认值为true,也就是创建一个新的session。如果我们调用getSession(false)来获得session,那么必须对其进行事务控制,原因是:(spring文档)[/b]
protected  final  org.hibernate.Session  getSession() 
throws DataAccessResourceFailureException, IllegalStateException

Get a Hibernate Session, either from the current transaction or a new one. The latter is only allowed if the "allowCreate" setting of this bean's HibernateTemplate is true.

[b]也就是说,getSession()方法从当前事务或者一个新的事务中获得session,如果想从一个新的事务中获得session(也就意味着当其不存在事务控制),则必须使HibernateTemplate中的allowCreate变量的值为”true”,而现在设置allowCreate变量的值为”false”就意味着无法从新的事务中获得session,也就是只能从当前事务中获取,所以必须对当前方法进行事务控制,否则会抛出如下异常:[/b]
java.lang.IllegalStateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here ...

[b]同时,如果对getSession()所在的方法进行事务控制,那么类似如下的代码:[/b]
		Session session = null;
for(int m =0;m<5;m++){
Admin admin = new Admin();
admin.setName("test");
admin.setPassword("098");
session = this.getSession();
session.save(admin);
}

[b]只会打开一个session,因为事务控制必须确保是同一个连接,spring会确保在整个相关方法中只存在一个session。Spring在方法开始时会打开一个session(即使进行事务控制的方法内部不执行数据库操作),之后在请求session时,如果在事务中存在一个未commit的session就返回,以此确保同一个session。[/b]

[size=medium][color=red][b]2.getCurrentSession()与openSession()[/b][/color][/size]
[b]getCurrentSession()与openSession()方法通过Hibernate的SessionFactory获得,两者的区别网上有很多文章已经介绍过,即:[/b]
①getCurrentSession创建的session会和绑定到当前线程,而openSession不会。 
②getCurrentSession创建的线程会在事务回滚或事物提交后自动关闭,而openSession必须手动关闭


[b]对于getCurrentSession()方法:
(1)其所在方法必须进行事务控制
(2)Session在第一次被使用的时候,或者第一次调用getCurrentSession()的时候,其生命周期就开始。然后它被Hibernate绑定到当前线程。当事务结束的时候,不管是提交还是回滚,Hibernate也会把Session从当前线程剥离,并且关闭它。假若你再次调用getCurrentSession(),你会得到一个新的Session,并且开始一个新的工作单元。

对于openSession()方法:
这个方法一般在spring与Hibernate的集成中不直接使用,它就是打开一个session,并且这个session与上下文无关,如果对其所在方法进行事务控制,会发现不起作用,原因就是前面提到的,事务控制必须确保是同一个连接,而openSession()打开的session与上下文无关。这个方法与getSession(),getCurrentSession()以及getHibernateTemplate()等方法的区别在于:后面的几个方法spring可以对其进行控制,如果对它们所在的方法进行事务控制,spring可以确保是同一个连接,而openSession()方法,spring无法对其进行控制,所以事务也不会起作用。[/b]

[size=medium][color=red][b]3.OpenSessionInView[/b][/color][/size]
[b]OpenSessionInView的主要功能是用来把一个Hibernate Session和一次完整的请求过程对应的线程相绑定。Open Session In View在request把session绑定到当前thread期间一直保持hibernate session在open状态,使session在request的整个期间都可以使用,如在View层里PO也可以lazy loading数据,如 ${ company.employees }。当View 层逻辑完成后,才会通过Filter的doFilter方法或Interceptor的postHandle方法自动关闭session。[/b]
public class Group implements Serializable{ 
private int id;
private String name;
private Set users;
...
}

[b]在业务方法中加载Group对象并将其保存到HttpSession对象中[/b]
List groups = ht.find("from Group");
Group group = (Group)groups.get(0);
HttpSession session = ServletActionContext.getRequest().getSession();
session.setAttribute("group", group);

[b]注意Group采用默认的延迟加载机制,即此时返回的只是一个Group代理对象,
在jsp页面中显示group对象的users属性,如下:
[/b]
<%  
Group group = (Group)session.getAttribute("group");
out.println(group.getUsers());
%>

[b]此时会抛出如下异常:[/b]
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: entity.Group.users, no session or session was closed

[b]延迟加载机制使得在业务方法执行结束之后仅仅返回Group的一个代理对象,在jsp页面中使用到group对象的值时,才发出sql语句加载,但此时session已经关闭。解决方法是采用OpenSessionInView机制,在web.xml页面中配置如下过滤器:[/b]
<filter>  
<filter-name>hibernateFilter</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</filter-class>
</filter>


[size=medium][color=red][b]总结:[/b][/color][/size]
[b](1) 对于getSession(),getSession(false),getCurrentSession()以及getHibernateTemplate()方法而言,如果对其所在方法进行事务控制,那么可以确保在整个方法中只存在一个session,无论你执行了几次CRUD操作,并且所打开的session会在事务结束时自动关闭。
(2) 必须对getSession(false)以及getCurrentSession()所在的方法进行事务控制(原因见上述分析)
(3) 如果没有对getSession()以及getHibernateTemplate()所在方法进行事务控制,那么如果在方法中进行N次CRUD操作,就会打开N个session,即每次调用getSession()和getHibernateTemplate()方法都会打开新的session。这两个方法的区别在于:getHibernateTemplate()方法结束时会自动关闭连接,而getSession()方法必须手动关闭。
(4) 如果在方法中采用SessionFactory的openSession()方法获得连接进行操作,那么无法对其进行事务控制。
(5) 一般的开发中,通常采用getHibernateTemplate()方法进行数据库操作, getHibernateTemplate()方法采用模板+回调的机制,进行数据库操作很方便,可以查看(其中session的打开与关闭都是在doExecute方法中进行的):[/b]
[url]http://lijiejava.iteye.com/blog/667644[/url]
[url]http://lijiejava.iteye.com/blog/727249[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值