我正在使用slick 2.0.1(如果需要可以升级),我想从数据库中检索自动递增值(postgresql).
我已经在这方面看到了一些关于SO的问题,但它们相当陈旧,我希望有一个更好的方法,而不是做这个答案所暗示的:Scala&Play!&Slick&PostgreSQL自动增量
def autoInc = name ~ price ~ description returning id
def add(product: Product)(implicit s:Session): Long = {
Products.autoInc.insert(p.name, p.price, p.description)
}
Run Code Online (Sandbox Code Playgroud)
你必须在autoInc方法中重新输入模型的字段,这是重复我希望避免的事情.
有没有更好的方法,或者我应该这样做?
我选择的方法是让我的模型poso(普通的旧scala对象):
case class Product(.....)
Run Code Online (Sandbox Code Playgroud)
然后我的dao类看起来像:
class ProductDao extends ProductDao {
class Products(tag: Tag) extends Table[Product](tag, "products") {
def id = ...
def name = ..
def * = (id, name) <> (Product.tupled, Product.unapply)
}
val products = TableQuery()
}
Run Code Online (Sandbox Code Playgroud)
另外作为旁注,对于*方法,我是否必须输入所有类似的属性,还是有更好的方法呢?
我有这样的插入方法(权重为索引)
implicit def run[A](action: DBIOAction[A, NoStream, _ <: slick.dbio.Effect]): Future[A] = {
db.run(action)
}
def insert(newCategory: CategoryExtractor): Future[Either[String, CategoryResponse]] = {
category.map(_.weight).max.result.flatMap {
case Some(weight) =>
val temp = newCategory.copy(weight = weight+1)
(category += temp).andThen(DBIO.successful(Right(toCategoryExtractor(temp))))
case None =>
val temp = newCategory.copy(weight = 1)
(category += temp).andThen(DBIO.successful(Right(toCategoryExtractor(temp))))
}
}
Run Code Online (Sandbox Code Playgroud)
我叫它两次
insert(CategoryExtractor("1", "name", "scala every where", 0, 0, 0, None)) onComplete {
case Success(data) => println(data)
}
insert(CategoryExtractor("2", "name", "haskell every where", 0, 0, 0, None)) onComplete {
case Success(data) => …Run Code Online (Sandbox Code Playgroud)