ktor中进行数据库操作,想找个能自动建表的数据库框架用,貌似只有hibernatea能自动建表了。

1、引入Spring-data-jpahibernate-hikaricp

val springVersion = "2.6.0"
val hibernateVersion = "5.6.1.Final"

implementation("org.springframework.data:spring-data-jpa:$springVersion")
implementation("org.hibernate:hibernate-hikaricp:$hibernateVersion")

2、配置hibernate信息

新建一个jpa.properties文件

hibernate.connection.drive_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:./db/api;AUTO_SERVER=TRUE
hibernate.connection.username=api
hibernate.connection.password=api
hibernate.connection.provider_class=org.hibernate.hikaricp.internal.HikariCPConnectionProvider
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update

3、配置Spring-data-jpa

@Configuration
@ComponentScan(basePackages = ["me.kuku.api.entity"])
@EnableJpaRepositories(basePackages = ["me.kuku.api.entity"])
open class JpaConfig{

    @Bean
    open fun entityManagerFactory(): LocalContainerEntityManagerFactoryBean {
        val em = LocalContainerEntityManagerFactoryBean()
        em.setPackagesToScan("me.kuku.api.entity")
        em.jpaVendorAdapter = HibernateJpaVendorAdapter()
        val properties = Properties()
        properties.load(Thread.currentThread().contextClassLoader.getResourceAsStream("jpa.properties"))
        em.setJpaProperties(properties)
        return em
    }

    @Bean
    open fun transactionManager(emf: EntityManagerFactory): JpaTransactionManager {
        val transactionManager = JpaTransactionManager()
        transactionManager.entityManagerFactory = emf
        return transactionManager
    }

}    

ktor插件

lateinit var applicationContext: AnnotationConfigApplicationContext

lateinit var loLiConRepository: LoLiConRepository

fun Application.jpa() {
    applicationContext = AnnotationConfigApplicationContext(JpaConfig::class.java)
    loLiConRepository = applicationContext.getBean(LoLiConRepository::class.java)
}

repository添加为ApplicationCall的扩展属性

val AnnotationConfigApplicationContext.loLiConRepository: LoLiConRepository
    get() = this.getBean(LoLiConRepository::class.java)

4、事务

private lateinit var transactionManager: JpaTransactionManager

fun transaction(block: () -> Unit) {
    val transactionDefinition = DefaultTransactionDefinition()
    val ts = transactionManager.getTransaction(transactionDefinition)
    try {
        block()
        transactionManager.commit(ts);
    }catch (e: Exception) {
        transactionManager.rollback(ts)
    }
}
最后修改:2021 年 12 月 13 日
如果觉得我的文章对你有用,请随意赞赏