简体   繁体   English

如何使用jOOQ获取事务内部的基础连接?

[英]How to get the underlying connection inside a transaction using jOOQ?

I'm using jOOQ inside an existing project which also uses some custom JDBC code. 我在现有项目中使用jOOQ,该项目也使用一些自定义JDBC代码。 Inside a jOOQ transaction I need to call some other JDBC code and I need to pass through the active connection so everything gets inside the same transaction. jOOQ事务中,我需要调用其他JDBC代码,并且需要通过活动连接,以便所有内容都进入同一事务中。

I don't know how to retrieve the underlying connection inside a jOOQ transaction. 我不知道如何在jOOQ事务中检索基础连接。

create.transaction(configuration -> {
    DSLContext ctx = DSL.using(configuration);

    // standard jOOQ code
    ctx.insertInto(...);

    // now I need a Connection
    Connection c = ctx.activeConnection(); // not real, this is what I need
    someOtherCode(c, ...);
});

Reading the docs and peeking a bit on the source code my best bet is this: 阅读文档并窥视一下源代码,我最好的选择是:

configuration.connectionProvider().acquire()

But the name is a bit misleading in this particular use case. 但是在这个特定的用例中,名称有点误导。 I don't want a new connection, just the current one. 我不希望有新连接,而只是当前连接。 I think this is the way to go because the configuration is derived and I will always get the same connection, but I'm not sure and I can't find the answer in the documentation. 我认为这是可行的方法,因为配置是派生的,并且我将始终获得相同的连接,但是我不确定,也无法在文档中找到答案。

jOOQ's API makes no assumptions about the existence of a "current" connection. jOOQ的API不对“当前”连接的存在做出任何假设。 Depending on your concrete implementations of ConnectionProvider , TransactionProvider , etc., this may or may not be possible. 根据您的ConnectionProviderTransactionProvider等的具体实现,这可能或不可能。

Your workaround is generally fine, though. 不过,您的解决方法通常很好。 Just make sure you follow the ConnectionProvider 's SPI contract: 只要确保您遵守ConnectionProvider的SPI合同:

Connection c = null;
try {
    c = configuration.connectionProvider().acquire();
    someOtherCode(c, ...);
}
finally {
    configuration.connectionProvider().release(c);
}

The above is fine when you're using jOOQ's DefaultTransactionProvider , for instance. 例如,当您使用jOOQ的DefaultTransactionProvider ,上面的方法就很好。

Note there is a pending feature request #4552 that will allow you to run code in the context of a ConnectionProvider and its calls to acquire() and release() . 请注意,有一个待处理的功能请求#4552 ,该请求将允许您在ConnectionProvider的上下文中运行代码,并且可以在其对acquire()release()调用中运行。 This is what it will look like: 它将是这样的:

DSL.using(configuration)
   .connection(c -> someOtherCode(c, ...));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM