HibernateTemplate和Spring @Transactional是如何协同工作的? [英] How does HibernateTemplate and Spring @Transactional work together?

查看:363
本文介绍了HibernateTemplate和Spring @Transactional是如何协同工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在我们的DAO中使用HibernateTemplate进行所有CRUD操作。



我的问题是,我们在服务上使用spring @Transactional ,因为spring是管理事务, HibernateTemplate 是否在更新多个DAO的Senario中运行?当使用Spring @Transactional 时,的意义是不同的DAO使用相同的会话?

  @Transactional 
public boolean testService(SObject test)[

dao1.save(test.getOne());
dao2.save(test.gettwo());

}





这就是DAO class look:


  public class GenericHibernateDao< T,PK extends Serializable>扩展HibernateDaoSupport 



public PK save(T newInstance){
return(PK)getHibernateTemplate()。save(newInstance);


解决方案 HibernateTransactionManager javadoc 对此非常清楚:


这个事务管理器适用于使用单个Hibernate SessionFactory用于事务性数据访问,但它也支持事务内的直接DataSource访问(即使用相同DataSource的普通JDBC代码)。这允许混合使用Hibernate的服务和使用普通JDBC的服务(不需要知道Hibernate)!应用程序代码需要遵循与org.springframework.jdbc.datasource.DataSourceTransactionManager(即DataSourceUtils.getConnection或经历TransactionAwareDataSourceProxy)相同的简单Connection查找模式。


只要您通过帮助程序类访问连接,就可以知道连接代理,如 DataSourceUtils (以及 JdbcTemplate 在引擎盖后面使用它)


We use HibernateTemplate in our DAOs for all the CRUD operations.

My question is, we use spring @Transactional on the services, Because the spring is managing the transactions, how does the HibernateTemplate behave in the senario where I update multiple DAOs. Meaning does HibernateTemplate use same session across different DAOs when Spring @Transactional is used?

@Transactional
public boolean testService(SObject test)[

     dao1.save(test.getOne());
     dao2.save(test.gettwo());

}


This is how the DAO class looks:

public class GenericHibernateDao<T, PK extends Serializable> extends HibernateDaoSupport
.
.
.
public PK save(T newInstance) {
    return (PK) getHibernateTemplate().save(newInstance);
}

解决方案

The HibernateTransactionManager javadoc is pretty clear about this:

This transaction manager is appropriate for applications that use a single Hibernate SessionFactory for transactional data access, but it also supports direct DataSource access within a transaction (i.e. plain JDBC code working with the same DataSource). This allows for mixing services which access Hibernate and services which use plain JDBC (without being aware of Hibernate)! Application code needs to stick to the same simple Connection lookup pattern as with org.springframework.jdbc.datasource.DataSourceTransactionManager (i.e. DataSourceUtils.getConnection or going through a TransactionAwareDataSourceProxy).

You're fine as long as you are accessing the connection through helper classes that are aware of the connection proxy such as DataSourceUtils (and the JdbcTemplate uses that behind the hood)

这篇关于HibernateTemplate和Spring @Transactional是如何协同工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆