Connection Manager
Concept
In Jimmer, all executable statements and instructions support two execution modes:
-
Execute based on the JDBC connection specified by the user
-
Executed by Jimmer automatically determining based on a JDBC connection
Here, take Executable
(Java) or KExecutable
(Kotlin) interface as an example
- Java
- Kotlin
package org.babyfish.jimmer.sql.ast;
import java.sql.Connection;
public interface Executable<R> {
R execute();
R execute(Connection con);
}
package org.babyfish.jimmer.sql.kt
import java.sql.Connection
interface KExecutable<R> {
fun execute(con: Connection? = null): R
}
-
execute(Connection)
: Execute on the JDBC connection specified by the user.Take query as an example:
- Java
- Kotlin
BookTable book = Tables.BOOK_TABLE;
List<Book> books = sqlClient
.createQuery(book)
.select(book)
.execute(con);val books = sqlClient
.createQuery(Book::class) {
select(table)
}
.execute(con)infoFor this usage, no special configuration of SqlClient is required.
-
execute()
orexecute(null)
: Determined by Jimmer to execute on a JDBC connection.Take query as an example:
- Java
- Kotlin
BookTable book = Tables.BOOK_TABLE;
List<Book> books = sqlClient
.createQuery(book)
.select(book)
.execute();val books = sqlClient
.createQuery(Book::class) {
select(table)
}
.execute()infoFor this usage,
ConnectionManager
must be configured for SqlClient. Otherwise it will cause exceptions.Undoubtedly, the 2nd approach is more in line with the requirements of business system development, so it is recommended. So it is strongly recommended to configure
ConnectionManager
for SqlClient.
Simple ConnectionManager
- Java
- Kotlin
javax.sql.DataSource dataSource = ...;
JSqlClient sqlClient = JSqlClient
.newBuilder()
.setConnectionManager(
ConnectionManager
.simpleConnectionManager(dataSource)
)
.build();
val dataSource: javax.sql.DataSource = ...
val sqlClient = newKSqlClient {
setConnectionManager {
dataSource.connection.use {
proceed(it)
}
}
}
This way is only responsible for getting connections from DataSource and has no transaction management mechanism.
However, transactions are very important in actual projects. Therefore, except for learning and trying, it is not recommended to use this approach in actual projects.
ConnectionManager managed by Spring transaction
This topic has been discussed in detail in Spring Section/Integrate Spring Transaction. This article will not repeat the explanation.
Letting Jimmer be managed by Spring transaction is the recommended usage.