在ktor
中进行数据库操作,想找个能自动建表的数据库框架用,貌似只有hibernatea
能自动建表了。
1、引入Spring-data-jpa
和hibernate-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)
}
}
1 条评论
博主太厉害了!