mirage-scala is the simple and powerful library to access RDBMS from Scala. I introduce how to use mirage-scala with sbt.
At first, add the following dependency into your build.sbt:
resolvers += "amateras-repo" at "http://amateras.sourceforge.jp/mvn/" | |
libraryDependencies += "jp.sf.amateras.mirage" %% "mirage-scala" % "0.0.3" % "compile" |
And create the jdbc.properties and put it on the root of classpath.
jdbc.driver=org.h2.Driver | |
jdbc.url=jdbc:h2:tcp://localhost:9092/test | |
jdbc.user=sa | |
jdbc.password= |
Next, you have to create the entity class. mirage-scala supports both of mutable and immutable style as entity class. This is the example of immutable style entity class:
case class Book( | |
@(PrimaryKey @field)(generationType = IDENTITY) bookId: Option[Long], | |
bookName: String, | |
author: String, | |
price: Option[Int]) { | |
// default constructor | |
def this() = this(None, null, null, None) | |
} |
Ready for mirage-scala. Let's try to use it!
import jp.sf.amateras.mirage.scala._ | |
Session.withTransaction { session => | |
val sqlManager = session.sqlManager | |
// insert | |
sqlManager.insertEntity(Book(None, "Mirage in Action", "Naoki Takezoe", Some(20))) | |
// select by the primary key | |
val key: Long = 1 | |
val book: Option[Book] = sqlManager.findEntity(classOf[book], key) | |
... | |
} |
You can insert, update and delete a record using SqlManager and entity classes. And also you can select a record by the primary key.
When you must select records by the more complex query, you can do it using 2way-SQL which is the powerful feature of mirage-scala. I would like to write about it in the next entiry.