我的所有表都有一些列共享,所以我想为所有表提供默认列。以下是我到目前为止所尝试的。我正在使用 Slick 3.0。
// created_at and updated_at are the columns every table share
abstract class BaseTable[T](tag: Tag, tableName: String)
extends Table[T](tag, tableName) {
def currentWhenInserting = new Timestamp((new Date).getTime)
def createdAt = column[Timestamp]("created_at", O.Default(currentWhenInserting))
def updatedAt = column[Timestamp]("updated_at", O.Default(currentWhenInserting))
}
实现这一点的简单方法如下所示。
case class Student(
name: String, age: Int,
created_at: Timestamp, updated_at: Timestamp
)
class Students(tag: Tag) extends BaseTable[Student](tag, "students"){
def name = column[String]("name")
def age = column[Int]("age")
override def * : ProvenShape[Student] =
(name, age, createdAt, updatedAt).shaped <>
(Student.tupled, Student.unapply _)
}
但这是不可取的。
首先,强制每个表行案例类包含 created_at 和 updated_at。如果我有更多从 API 设计角度完全无法接受的字段。
其次,在(name, age, createdAt, updatedAt) 中显式写入两个createdAt 、updatedAt 。这不是我对默认行的期望。
我解决这个问题的理想方法如下:
case class Student(name: String, age: Int)
class Students(tag: Tag) extends BaseTable[Student](tag, "students"){
def name = column[String]("name")
def age = column[Int]("age")
override def * : ProvenShape[Student] =
(name, age).shaped <>
(Student.tupled, Student.unapply _)
}
即在 BaseTable 或 Define BaseCaseClass 中编写一些方法,以避免在表定义中显式编写额外的两个字段,如 Student 和行案例类定义 Student。
不过,经过一番痛苦的挣扎,还是可以做到的。任何帮助将不胜感激。