java - Spring 中有多个事务管理器并在运行时选择一个

标签 java spring transactions spring-transactions transactionmanager

对于每个客户端,我都有单独的数据库,但每个客户端的业务逻辑和表都是相同的。我想要为每个客户端提供公共(public)服务和 dao 层。在 dao 中,我根据登录的用户客户端选择数据源。在@Transactional中,我必须传递事务管理器的bean id。如何使用@Transactional注解制作公共(public)服务层。

同样的问题在这里

  1. Multiple transaction managers - Selecting a one at runtime - Spring

  2. Choose between muliple transaction managers at runtime

但是没有人回复

最佳答案

如果您想动态创建数据库连接,请查看 this所以帖子。

From the post linked : Basically in JDBC most of these properties are not configurable in the API like that, rather they depend on implementation. The way JDBC handles this is by allowing the connection URL to be different per vendor.

So what you do is register the driver so that the JDBC system can know what to do with the URL:

DriverManager.registerDriver((Driver)
Class.forName("com.mysql.jdbc.Driver").newInstance());

Then you form the URL:

String url =
 "jdbc:mysql://[host][,failoverhost...][:port]/[database][?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]"

And finally, use it to get a connection:

Connection c = DriverManager.getConnection(url);

In more sophisticated JDBC, you get involved with connection pools and the like, and application servers often have their own way of registering drivers in JNDI and you look up a DataSource from there, and call getConnection on it.

In terms of what properties MySQL supports, see here (The link is dead).

EDIT: One more thought, technically just having a line of code which does Class.forName("com.mysql.jdbc.Driver") should be enough, as the class should have its own static initializer which registers a version, but sometimes a JDBC driver doesn't, so if you aren't sure, there is little harm in registering a second one, it just creates a duplicate object in memeory.

I don't know if this will work, since I have not tested it, but you could try.

现在您可以做的是,在 DAO 顶部使用 @Transactional 注释,而不指定任何值(可行)。现在,在您的 DAO 类中,不要注入(inject)任何 DataSource bean,而是按照上面链接中的指定动态创建您自己的 dataSource,然后在运行时注入(inject)该依赖项、使用 getter setter 方法,或者仅使用 new 关键字。我希望这能成功。

注意:我还没有亲自测试过,所以如果这有效,请告诉我。

关于java - Spring 中有多个事务管理器并在运行时选择一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37116625/

相关文章:

java - 如何禁用 JFileChooser 中的文件输入字段?

java - 尝试在 Jenkins 上运行 Selenium 时出现 NoSuchSession 异常

java - 运行在 Jenkins 下运行 JVM 的批处理文件时的堆大小

java - 将数据库中的值添加到 logback 日志消息

java - Spring ReadOnly Transaction with Propagation.SUPPORTS with WebSphere 和 Oracle

php - 如果在获得网站 paypal api 的 paykey 后,交易将由用户使用他们的 paypal 帐户完成怎么办?

java - 如何处理@Transactional注解引发的异常

java - 我应该仅仅因为添加了一个变量就扩展一个类吗?

java - 我们如何在HandlerInterceptorAdapter中处理异常?

java - 在WebLogic中获取JTA事务超时值