Created
March 18, 2015 07:57
-
-
Save maji-KY/d2981f4f7935b6a18366 to your computer and use it in GitHub Desktop.
JDBI in Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.neco_labo.db | |
import java.sql.ResultSet | |
import com.zaxxer.hikari.{HikariDataSource, HikariConfig} | |
import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper | |
import org.skife.jdbi.v2.sqlobject.{BindBean, Bind, SqlQuery} | |
import org.skife.jdbi.v2.tweak.ResultSetMapper | |
import org.skife.jdbi.v2.{StatementContext, DefaultMapper, DBI} | |
import scala.beans.BeanProperty | |
import scala.collection.JavaConverters._ | |
object JDBI extends App { | |
val config = new HikariConfig() | |
config.setJdbcUrl("jdbc:mysql://localhost:3306/db?zeroDateTimeBehavior=round") | |
config.setUsername("user") | |
config.setPassword("pass") | |
config.addDataSourceProperty("dataSourceClassName", "com.mysql.jdbc.jdbc2.optional.MysqlDataSource") | |
config.addDataSourceProperty("autoCommit", "false") | |
config.addDataSourceProperty("useServerPrepStmts", "true") | |
config.addDataSourceProperty("cachePrepStmts", "true") | |
val ds = new HikariDataSource(config) | |
val dbi = new DBI(ds) | |
val dao = dbi.open(classOf[ApplicationDAO]) | |
val app = dao.finbByAppId("sample") | |
println(app)// Application(sample,サンプルアプリ) | |
val bean = Application("sample", "unknown") | |
val app2 = dao.finbByBean(bean) | |
println(app2)// Application(sample,サンプルアプリ) | |
ds.close() | |
} | |
@RegisterMapper(Array(classOf[ApplicationMapper])) | |
trait ApplicationDAO { | |
@SqlQuery("select * from application where id = :id") | |
def finbByAppId(@Bind("id")appId: String): Application | |
@SqlQuery("select * from application where id = :id") | |
def finbByBean(@BindBean app: Application): Application | |
} | |
case class Application(@BeanProperty id: String, @BeanProperty name: String) | |
class ApplicationMapper extends ResultSetMapper[Application] { | |
override def map(index: Int, r: ResultSet, ctx: StatementContext): Application = { | |
Application(r.getString("id"), r.getString("name")) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment