前回の内容にHikariCPを適用してみる。
HikariCPの設定
build.gradleに以下を追加する。
dependencies { // 省略 runtimeOnly 'io.micronaut.configuration:micronaut-jdbc-hikari' }
application.ymlに以下を追加する。
datasources: default: url: jdbc:postgresql://localhost:5432/dvdrental username: postgres password: password
DomaのConfig設定
micronaut-jdbc-hikariが設定するDataSourceを利用したいので、LocalTransactionDataSourceとLocalTransactionManagerをFactoryで生成する。
@Factory class DomaConfigFactory { @Bean fun localTransactionDataSource(dataSource: DataSource) = LocalTransactionDataSource(dataSource) @Bean fun localTransactionManager(dataSource: LocalTransactionDataSource) = LocalTransactionManager(dataSource.getLocalTransaction(ConfigSupport.defaultJdbcLogger)) }
DIしたいので、Configクラスはobjectではなくclassで作成する。
@Singleton class DomaConfig : Config { private val dialect = PostgresDialect() @Inject private lateinit var dataSource: LocalTransactionDataSource @Inject private lateinit var transactionManager: LocalTransactionManager override fun getDialect() = dialect override fun getDataSource() = dataSource override fun getTransactionManager() = transactionManager override fun getNaming() = Naming.SNAKE_LOWER_CASE!! }
Daoの設定
作成したConfigクラスをDIしたいので Annotation(target = AnnotationTarget.CONSTRUCTOR, type = Inject::class)
を追加する。
@Dao @AnnotateWith(annotations = [ Annotation(target = AnnotationTarget.CLASS, type = Singleton::class), Annotation(target = AnnotationTarget.CONSTRUCTOR, type = Inject::class) ]) interface CountryDao { @Select fun findAll(): List<Country> }
Factoryクラスが苦しいが致し方なし。