相変わらずsbtと言わずにMavenでインストール(Scala2.9用)
<dependency>
<groupId>net.liftweb</groupId>
<artifactId>lift-mapper_2.9.0-1</artifactId>
<version>2.4-M2</version>
</dependency>
最新情報はレポジトリなどで確認。
http://scala-tools.org/repo-releases/net/liftweb/
とりあえずModelを作成する
package jp.mwsoft.sample
import net.liftweb.mapper._
class ModelSample extends LongKeyedMapper[ModelSample] with IdPK {
def getSingleton = ModelSample
object name extends MappedString(this, 64)
object text extends MappedString(this, 256)
}
object ModelSample extends ModelSample with LongKeyedMetaMapper[ModelSample] {
override def fieldOrder = List(name)
}
MySQLで繋ぐ場合の例。こんだけ書けば一応動いた。
import net.liftweb.common.Box
import net.liftweb.http.{ LiftRules }
import net.liftweb.mapper.{ DB, Schemifier, DefaultConnectionIdentifier, StandardDBVendor }
import jp.mwsoft.sample.model.ModelSample
val vendor = new StandardDBVendor("com.mysql.jdbc.Driver", "jdbc:mysql://localhost/dbname", Box("user"), Box("password"))
LiftRules.unloadHooks.append(vendor.closeAllConnections_! _)
DB.defineConnectionManager(DefaultConnectionIdentifier, vendor)
Schemifier.schemify(true, Schemifier.infoF _, ModelSample)
// 試しに検索してみる
ModelSample.findAll
//=> List()
上記を実行するとModelの記述内容に従ってテーブルが自動生成される。
テーブル名はクラス名ModelSampleに従いmodelsampleに。LongKeyedMapper with IdPKを指定しているので、bigint(20) unsignedでauto_incrementなIDが付加されている。
// CREATE
ModelSample.create name ("名前") text ("テスト") save
// キーで検索
ModelSample.find(1)
// 全レコードをSELECT
ModelSample.findAll
// レコード数
ModelSmaple.count
// IDで検索
ModelSample findAll By(ModelSample.id, 1)
// nameで検索
ModelSample findAll By(ModelSample.name, "名前")
トランザクション処理をどうしてるかとか内部的なとこは見てないので、これで長時間ちゃんと使えるかは不明。簡単なバッチでDBに何度か繋ぎに行く用途では耐えてくれた。