Skip to content

Instantly share code, notes, and snippets.

@seratch
Created April 17, 2014 05:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seratch/10954977 to your computer and use it in GitHub Desktop.
Save seratch/10954977 to your computer and use it in GitHub Desktop.
ScalikeJDBC 2.0.0-beta1 for Scala 2.11.0
scalaVersion := "2.11.0"
libraryDependencies ++= Seq(
"org.scalikejdbc" %% "scalikejdbc" % "2.0.0-beta1",
"org.scalikejdbc" %% "scalikejdbc-interpolation" % "2.0.0-beta1",
"com.h2database" % "h2" % "[1.3,)",
"ch.qos.logback" % "logback-classic" % "[1.0,)"
)
resolvers += "sonatype releases" at "https://oss.sonatype.org/content/repositories/releases"
import scalikejdbc._, SQLInterpolation._
// initialize JDBC driver & connection pool
Class.forName("org.h2.Driver")
ConnectionPool.singleton("jdbc:h2:mem:hello", "user", "pass")
// ad-hoc session provider on the REPL
implicit val session = AutoSession
// table creation, you can run DDL by using #execute as same as JDBC
sql"""
create table members (
id serial not null primary key,
name varchar(64),
created_at timestamp not null
)
""".execute.apply()
// insert initial data
Seq("Alice", "Bob", "Chris") foreach { name =>
sql"insert into members (name, created_at) values (${name}, current_timestamp)".update.apply()
}
// for now, retrieves all data as Map value
val entities: List[Map[String, Any]] = sql"select * from members".map(_.toMap).list.apply()
// defines entity object and extractor
import org.joda.time._
case class Member(id: Long, name: Option[String], createdAt: DateTime)
object Member extends SQLSyntaxSupport[Member] {
override val tableName = "members"
def apply(rs: WrappedResultSet) = new Member(
rs.long("id"), rs.stringOpt("name"), rs.dateTime("created_at"))
}
// find all members
val members: List[Member] = sql"select * from members".map(rs => Member(rs)).list.apply()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment