Jooq连接生命周期

Jooq connection lifecycle

我正在评估 Jooq,我想确认我对 JDBC 连接生命周期的理解。

我正在使用连接池 (Hikari) 并使用数据源配置 DSLContext。

据我了解:

  1. 我可以安全地创建一个 DSLContext,我可以在多个线程中跨我的应用程序重复使用它吗?如果我不修改配置,这样做有什么负面影响吗?争等?

  2. 每次访问数据库时,Jooq是否从池中获取连接,访问数据库,然后提交并释放?例如:

Result<Record> result = context.select().from(AUTHOR).fetch();
Result<Record> otherResult = context.select().from(BOOKS).fetch();

这些查询中的每一个都会从池中获取和释放一个新连接?

  1. 像这样使用事务API时:
context.transaction(ctx -> {
        DSLContext trans = DSL.using(ctx);
   ...
});

将从池中获取一个连接并重新用于使用 trans 上下文的所有访问?

谢谢!

I am safe to create one DSLContext that I can reuse across my application in many threads?

可以,前提是在初始化后,您不再修改 Configuration 及其组件,例如Settings.

Is there any negative to doing this provided I don't modify the config? Contention etc?

相反,这是使用 DSLContext 的推荐方式。通过重用它,您将从缓存中受益,例如如果您使用 Result.into(MyDto.class) 方法等进行反思

Each time I do a database access, does Jooq obtain a connection from the pool, do the DB access and then commit and release it?

是的,如果您的 DataSource 有矿池支持,这就是它的工作原理。当然,池每次都可以免费为 jOOQ 提供相同的连接,这取决于在 jOOQ 之外管理的事务上下文。 jOOQ 不在乎。

When using the transaction API like this: [...] A connection would be obtained from the pool and reused for all accesses using the trans context?

transaction() 方法获取连接并在您传递给它的 TransactionalRunnable 期间保持连接(即 lambda)。您的嵌套 DSLContext trans 实例现在将与 "cached" Connection 一起使用,并且不会从您的 DataSource.

获取新连接