`

hibernate4 spring3 整合

 
阅读更多

由于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 current thread          以前不需要的

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。Hibernate session的起始和终结由数据库事务的生存来控制。

 

 

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

分享到:
评论
3 楼 elliotann 2014-10-15  
说实话,没看明白标题与内容
2 楼 淹不死の鱼 2014-07-29  
zaq369cde 写道
这文章居然有2万多的访问量


期待你写个更好的
1 楼 zaq369cde 2014-05-13  
这文章居然有2万多的访问量

相关推荐

Global site tag (gtag.js) - Google Analytics