I want to use HikariCP. I have a bunch of DAOs tha...
# getting-started
j
I want to use HikariCP. I have a bunch of DAOs that implement an interface for CRUD operations. What is the best way to pass around the DB connection to get the best use out of connection pooling?
😶 1
r
You should construct a single instance of
HikariDataSource
at application startup: https://github.com/brettwooldridge/HikariCP#rocket-initialization Pass that single instance as a constructor parameter (with type
javax.sql.DataSource
) to the DAOs. Then just use
dataSource.getConnection().use { connection -> TODO("your code using the connection here") }
inside the DAO - it will reuse a pooled connection as far as possible.
👍 1
(This is a bare metal description - are you not using some higher level abstraction than
java.sql.Connection
inside your DAOs? And are you wiring up your application by hand?)
One neat trick - if you build your data source like this:
Copy code
val dataSource = HikariDataSource(HikariConfig().apply {
        initializationFailTimeout = -1
        connectionTimeout = Duration.ofSeconds(1).toMillis()
    })
then it will not block on startup or blowup if the DB is inaccessible, only when you try to get a connection will you get an exception after 1 second. So your app will be resilient to the DB being there or not. The default connection timeout of 30 seconds is a bit long!
🆒 1
1
j
I am using ktorm. So I am constructing the datasource and passing it to ktorm. so should i still be passing in the datasource to my DAO classes or passing in the ktorm connection instance?
r
Reading the docs: https://www.ktorm.org/en/connect-to-databases.html#Connect-with-a-Pool It looks like you want to do this at application startup:
val database = Database.connect(HikariDataSource(HikariConfig())
and then pass in
database
to your DAO classes.
j
thank you