Skip to content

Instantly share code, notes, and snippets.

@deffence1776
Last active Aug 11, 2019
Embed
What would you like to do?
package main
import com.zaxxer.hikari.HikariDataSource
import org.apache.ibatis.annotations.Insert
import org.apache.ibatis.annotations.Select
import org.apache.ibatis.mapping.Environment
import org.apache.ibatis.session.Configuration
import org.apache.ibatis.session.SqlSession
import org.apache.ibatis.session.SqlSessionFactory
import org.apache.ibatis.session.SqlSessionFactoryBuilder
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory
import org.jetbrains.ktor.application.call
import org.jetbrains.ktor.application.install
import org.jetbrains.ktor.host.embeddedServer
import org.jetbrains.ktor.netty.Netty
import org.jetbrains.ktor.response.respondText
import org.jetbrains.ktor.routing.Routing
import org.jetbrains.ktor.routing.get
/**
Ktor(corutine)使ったマイクロWebフレームワークで試す
MyBatisでDBアクセス、トランザクション管理
*/
fun main(args: Array<String>): Unit {
val sessionFactory: SqlSessionFactory = createSessionFactory()
embeddedServer(Netty, 8080) {
install(Routing) {
get("/") {
withSession(sessionFactory.openSession()) {
val mapper = getMapper(PersonMapper::class.java)
val str =dao.selectAll()
.map{it.toString()}
.reduceRight{first:String,second:String -> first +":" + second}
call.respondText(str)
}
}
get("/insert") {
withSession(sessionFactory.openSession()) {
val mapper = getMapper(PersonMapper::class.java)
val name = call.request.queryParameters["name"]
val id = call.request.queryParameters["id"]
if(null != id && null != name){
val p =Person(id.toInt(), name)
dao.insert(p)
call.respondText("OK!"+p)
}else{
call.respondText("NG!")
}
}
}
}
}.start(wait = true)
}
/**
corutinから呼べるようにsuspendファンクションとして定義
パフォーマンス的にどこまでcorutineのメリット生かせるのかは?
*/
suspend fun withSession(session: SqlSession, block: suspend SqlSession.() -> Unit) {
session.use {
try {
block.invoke(session)
session.commit()
}catch (e:Exception){
session.rollback()
throw e
}
}
}
data class Person(val id: Int, val name: String)
interface PersonMapper {
@Select("""
SELECT *
FROM person
""")
fun selectAll(): List<Person>
@Insert("""
INSERT into person
VALUES(#{id},#{name})
""")
fun insert(person: Person): Int
}
fun createSessionFactory(): SqlSessionFactory {
val dataSource = HikariDataSource()
dataSource.jdbcUrl = "jdbc:h2:mem:hello"
dataSource.username = "user"
dataSource.password = "pass"
val transactionFactory = JdbcTransactionFactory()
val environment = Environment("development", transactionFactory, dataSource)
val configuration = Configuration(environment)
dataSource.connection.use { connection ->
val st = connection.createStatement()
st.execute("create table person (id int primary key, name varchar(100))")
st.execute("insert into person(id, name) values (1, 'Boy')")
}
configuration.addMapper(PersonMapper::class.java)
return SqlSessionFactoryBuilder().build(configuration)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment