光滑:嵌套(嵌入)类DRY

时间:2014-05-20 12:04:47

标签: slick slick-2.0

如果可以在learning slick2之后定义嵌套类(嵌入在JPA中),如下所示:

case class Person(name: Name, address: Address)
case class Name(given: String, family: String)
case class Address(street: String, city: String)

class Directory(tag: Tag) extends Table[Person](tag, "directory") {
  def givenName   = column["String"] ( "given_name" )
  def familyName  = column["String"] ( "family_name" )
  def street      = column["String"] ( "street" )
  def city        = column["String"] ( "city" )

  def * = (name, address) <> (Person.tupled, Person.unapply)
  def name = (givenName, familyName) <> (Name.tupled, Name.unapply)
  def address = (street, city) <> (Address.tupled, Address.unapply)
}

我不想在我嵌入地址的每个表格中写出街道,城市和地址的定义。我想写下面的内容,但由于显而易见的原因,这不能编译,因为列是表等上的方法...是否有可能以某种方式重用列定义?

object Adresses {
    def street      = column["String"] ( "street" )
    def city        = column["String"] ( "city" )
    def address = (street, city) <> (Address.tupled, Address.unapply)
}

class Directory(tag: Tag) extends Table[Person](tag, "directory") {
      def givenName   = column["String"] ( "given_name" )
      def familyName  = column["String"] ( "family_name" )


      def * = (name, Adresses.address) <> (Person.tupled, Person.unapply)  //address from Adresses
      def name = (givenName, familyName) <> (Name.tupled, Name.unapply)
}

1 个答案:

答案 0 :(得分:3)

你可以让Adresses成为一个继承自Table类的特性(是的,有效)。

trait Adresses[T] extends Table[T]{
    def street      = column["String"] ( "street" )
    def city        = column["String"] ( "city" )
    def address = (street, city) <> (Address.tupled, Address.unapply)
}

class Directory(tag: Tag) extends Table[Person](tag, "directory") with Adresses[Person] {
      def givenName   = column["String"] ( "given_name" )
      def familyName  = column["String"] ( "family_name" )


      def * = (name, address) <> (Person.tupled, Person.unapply)  //address from Adresses
      def name = (givenName, familyName) <> (Name.tupled, Name.unapply)
}