seratch's weblog in Japanese

About Scala, Java and Ruby programming in Japaense. If you need English information, go to http://blog.seratch.net/

ScalikeJDBC に新しい API を追加しました

ScalikeJDBC という Scala のシンプルな JDBC ラッパーを開発しているのですが、今回新しい API を追加してみました。

https://github.com/seratch/scalikejdbc

経緯

元々の DBSession を使った API は、当時 Twitter の Querulous というライブラリが気に入っていたので、これのコンセプトを参考にしつつ実装したものでした。

https://github.com/twitter/querulous

今回の API は Play20 の Anorm の API デザインについては割と気に入っているので、それを自分なりにアレンジしてみたものです。

http://www.playframework.org/documentation/2.0/ScalaAnorm

使い方

Anorm は apply メソッドだけでなく、as(...) の呼び出しでもクエリが発行されたりするのですが、ScalikeJDBC の SQL では apply メソッドを呼ばない限りはクエリを発行しません。

row parser はシンプルにと思い、今まで通り (WrappedResultSet) =>A の関数のままにしました。

import scalikejdbc._
import scala.Option

DB autoCommit { implicit session =>

  case class Emp(id: Int, name: Option[String])
  val empMapper = (rs: WrappedResultSet) => Emp(rs.int("id"), Option(rs.string("name")))

  val emps: List[Emp] = SQL("select * from emp order by id limit 10").map(empMapper).list.apply() // or toList.apply()
  val firstEmp: Option[Emp] = SQL("select * from emp order by id limit 10").map(empMapper).first.apply() // or headOption.apply()
  val andy: Option[Emp] = SQL("select * from emp where id = ? and name = ?").bind(1, "Andy").map(empMapper).single.apply() // or toOption.apply()

  val result: Boolean = SQL("create table company (id integer primary key, name varchar(30))").execute.apply()
  val count: Int = SQL("insert into company values (?, ?)").bind(1,"Typesafe").executeUpdate.apply()
}