hibernate4 spring3 整合

hibernate4 spring3 整合

 
原文地址:http://loushi135.iteye.com/blog/1420309  原文提供了例子下载

由于hibernate4已经完全可以实现事务了 与spring3.1中的hibernatedao,hibernateTemplete等有冲突,所以spring3.1里已经不提供hibernatedaosupport,hibernateTemplete了,只能用hibernate原始的方式用session

Session session = sessionFactory.openSession();
Session session = sessionFactory.getCurrentSession();
在basedao里可以用注入的sessionFactory获取session

Session session = sessionFactory.getCurrentSession();
注意 配置事务的时候必须将父类baseServiceImpl也配上,要不然会出现错误:No Session found for currentthread          以前不需要的

SessionFactory.getCurrentSession()的后台实现是可拔插的。因此,引入了新的扩展接口 (org.hibernate.context.spi.CurrentSessionContext)和

新的配置参数(hibernate.current_session_context_class),以便对什么是“当前session”的范围和上下文(scope and context)的定义进行拔插。

 

它定义 了单一的方法,currentSession(),特定的实现用它来负责跟踪当前的上下文session。

 

首先我们看看org.hibernate.context.spi.CurrentSessionContext

这个接口仅有一个方法:

SessioncurrentSession()

                       throws HibernateException

Retrieve thecurrent session according to the scoping defined by this implementation.

 

currentSession()表示 根据当前CurrentSessionContext的实现及定义返回”当前的Session”

 

这个接口…Hibernate中有3个类实现了这个接口

All Known Implementing Classes:

JTASessionContext, ManagedSessionContext, ThreadLocalSessionContext

 

1: org.hibernate.context.internal.ThreadLocalSessionContext - 当前session通过当前执行的线程来跟踪和界定。

 

2: org.hibernate.context.internal.JTASessionContext- 当前session根据JTA来跟踪和界定。这和以前的仅支持JTA的方法是完全一样的。

 

3: org.hibernate.context.internal.ManagedSessionContext..

 

Spring为事务管理,也实现了此接口:

1: org.springframework.orm.hibernate4.SpringSessionContext– 当前Session根据Spring和事务管理器来跟踪和界定.

 

 

这几种实现都提供了“每数据库事务对应一个session”的编程模型,也称作每次请求一个session。Hibernatesession的起始和终结由数据库事务的生存来控制。

 

 

hibernate.current_session_context_class 配置参数定义了应该采用哪个org.hibernate.context.spi.CurrentSessionContext实现。

 

一般而言,此参数的值指明了要使用的实 现类的全名,但那两个内置的实现可以使用简写,即"jta"和"thread"。

 

hibernate.current_session_context_class=thread

实质是:

hibernate.current_session_context_class= org.hibernate.context.internal.ThreadLocalSessionContext

 

同理:

hibernate.current_session_context_class=jta

实质是:

hibernate.current_session_context_class= org.hibernate.context.internal.JTASessionContext

 

 

 

而在Spring @Transactional声明式事务管理,”currentSession”的定义为: 当前被 Spring事务管理器 管理的Session,此时应配置:

hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值