如何配置事务管理以在 Spring 中使用 2 个不同的数据库? [英] How to configure transaction management for working with 2 different db in Spring?

查看:31
本文介绍了如何配置事务管理以在 Spring 中使用 2 个不同的数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个数据库(MySql 和 HSQLDB).我配置了 2 个数据源和 2 个 EntityManagerFactory bean.我还可以配置 2 个对应的 JpaTransactionManager bean.

I have 2 databases (MySql and HSQLDB). I configured 2 data sources and 2 EntityManagerFactory beans. I can also configure 2 correspondent JpaTransactionManager beans.

但我不知道如何指定它们中的哪些应该用于管理具体服务类的事务.我想为此使用 @Transactional 注释,但实际上我只能指定一个 txManagers:

But I don't know how to specify which of them should be used to manage transactions for concrete service-class. I want to use @Transactional annotation for that purpose, but I actually can specify only one of txManagers:

<tx:annotation-driven transaction-manager="manager"/>

摆脱这种局面的出路是什么?

What is the way out from this situation?

推荐答案

JpaTransactionManager 的 javadoc 对此有一些建议:

这个事务管理器是适用于使用单个 JPA EntityManagerFactory 用于交易数据访问.JTA(通常通过JtaTransactionManager) 是必要的用于访问多个事务同一事务中的资源.请注意,您需要配置您的JPA 提供程序相应地让它参与JTA交易.

This transaction manager is appropriate for applications that use a single JPA EntityManagerFactory for transactional data access. JTA (usually through JtaTransactionManager) is necessary for accessing multiple transactional resources within the same transaction. Note that you need to configure your JPA provider accordingly in order to make it participate in JTA transactions.

换句话说,如果您发现自己有多个实体管理器,以及相应的 tx 管理器,那么您应该考虑使用单个 JtaTransactionManager 代替.实体管理器应该能够参与 JTA 事务,这将为您提供跨两个实体管理器的完整事务性,而无需担心您在任何时候都在哪个实体管理器中.

In other words, if you find yourself with multiple entity managers, with corresponding tx managers, then you should consider using a single JtaTransactionManager instead. The entity managers should be able to participate in JTA transactions, and this will give you full transactionality across both entity managers, without hacving to worry about which entity manager you're in at any one time.

当然,JtaTransactionManager 确实需要一个完整的 JTA 支持应用服务器,而不是像 Tomcat 这样的普通 servlet 引擎.

Of course, JtaTransactionManager does require a full JTA-supporting application server, rather than a vanilla servlet engine like Tomcat.

这篇关于如何配置事务管理以在 Spring 中使用 2 个不同的数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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