gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:37:57 26 4
gpt4 key购买 nike

对于每个客户端,我都有单独的数据库,但每个客户端的业务逻辑和表都是相同的。我想要为每个客户端提供公共(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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com