個人的には、これにはLift の Mapper ライブラリが好みで、Lift Web アプリケーションのコンテキスト外で使用することもあります。sbt
以下は、完全に機能する例です。たとえば、次のものを として実行できますbuild.sbt
。
libraryDependencies ++= Seq(
"net.liftweb" %% "lift-mapper" % "2.4" % "compile->default",
"com.h2database" % "h2" % "1.2.127"
)
まずモデルについて:
import net.liftweb.common._, net.liftweb.mapper._
object Student extends Student with LongKeyedMetaMapper[Student]
class Student extends LongKeyedMapper[Student] with IdPK with ManyToMany {
def getSingleton = Student
object name extends MappedString(this, 40)
object rooms extends MappedManyToMany(
StudentRoom, StudentRoom.student, StudentRoom.room, Room
)
}
object Room extends Room with LongKeyedMetaMapper[Room]
class Room extends LongKeyedMapper[Room] with IdPK with ManyToMany {
def getSingleton = Room
object subject extends MappedString(this, 40)
object students extends MappedManyToMany(
StudentRoom, StudentRoom.room, StudentRoom.student, Student
)
}
object StudentRoom extends StudentRoom with LongKeyedMetaMapper[StudentRoom] {
override def dbIndexes = Index(student, room) :: super.dbIndexes
}
class StudentRoom extends LongKeyedMapper[StudentRoom] with IdPK {
def getSingleton = StudentRoom
object student extends MappedLongForeignKey(this, Student)
object room extends MappedLongForeignKey(this, Room)
}
そしていくつかのデータベース設定:
DB.defineConnectionManager(
DefaultConnectionIdentifier,
new StandardDBVendor("org.h2.Driver", "jdbc:h2:mem:example", Empty, Empty)
)
Schemifier.schemify(true, Schemifier.infoF _, Student, Room, StudentRoom)
そしていくつかのデータ:
val m = Student.create.name("Mary"); m.save
val j = Student.create.name("John"); j.save
val physics = Room.create.subject("Physics"); physics.save
StudentRoom.create.student(m).room(physics).save
StudentRoom.create.student(j).room(physics).save
これで準備完了です:
scala> Room.findAll(By(Room.subject, "Physics")).flatMap(_.students)
res7: List[Student] = List(Student={name=Mary,id=2}, Student={name=John,id=3})