你如何以不那么冗长的方式使用Slick?我的做法真的很糟糕吗?我喜欢使用我正在处理的数据库行的对象表示。
这只是彼此相关的2个实体,它花了:
import java.sql._
import scala.slick.driver.H2Driver.simple._
import scala.slick.lifted.ForeignKeyQuery
object Schema {
val models = TableQuery[Models]
val users = TableQuery[Users]
val db = Database.forURL("jdbc:h2:mem:hello", driver = "org.h2.Driver")
}
object CaseClassMapping
extends App {
Schema.db.withSession { implicit session =>
Schema.models.ddl.create
Schema.users.ddl.create
var m1 = Model(new Timestamp(new java.util.Date().getTime))
val id = Schema.models.returning(Schema.models.map(_.id)).insert(m1)
m1 = m1.copy(id = Some(id))
Schema.users += User("John Doe", m1.id.get)
val q = for {
u <- Schema.users if u.id === 1
m <- u.model
} yield m
println(Schema.users.list)
println(q.list)
}
}
trait _Model {
def modelID: Int
def model: Model
def created = model.created
}
case class Model(created: Timestamp, id: Option[Int] = None)
class Models(tag: Tag) extends Table[Model](tag, "MODELS") {
def id = column[Int]("ID", O.PrimaryKey, O.AutoInc)
def created = column[Timestamp]("NAME", O.NotNull)
def * = (created, id.?) <> (Model.tupled, Model.unapply)
}
case class User(var name: String, modelID: Int, id: Option[Int] = None)
extends _Model {
lazy val model = Schema.db.withSession { implicit session =>
(for {
u <- Schema.users if u.id === id
m <- u.model
} yield m).first
}
}
class Users(tag: Tag) extends Table[User](tag, "USERS") {
def id = column[Int]("ID", O.PrimaryKey, O.AutoInc)
def modelID: Column[Int] = column[Int]("MODEL_ID", O.NotNull)
def name = column[String]("NAME", O.NotNull)
def * = (name, modelID, id.?) <> (User.tupled, User.unapply)
def model: ForeignKeyQuery[Models, Model] =
foreignKey("MODEL_FK", modelID, TableQuery[Models])(_.id)
}
答案 0 :(得分:2)
您可以从架构自动生成模型。看一下这个: http://slick.typesafe.com/doc/3.0.0-RC1/code-generation.html