Search code examples
scalascalaqueryslick

Slick, how to map a query to an inheritance table model?


Slick, how to map a query to an inheritance table model? i.e,

I have table A, B, C A is the "parent" table and B & C are "child" tables What I would like to know is how should I model this using slick so A will be abstract and B & C concrete types, and querying for a row in A will result in a B or C object

Something like JPA's InheritanceType.TABLE_PER_CLASS.


Solution

  • We need to do couple of things. First find a way to map the hierarchy to an table. In this case I am using a column that stores the type. But you can use some other tricks as well.

    trait Base {
      val a: Int
      val b: String
    }
    
    case class ChildOne(val a: Int, val b: String, val c: String) extends Base
    case class ChildTwo(val a: Int, val b: String, val d: Int) extends Base
    
    class MyTable extends Table[Base]("SOME_TABLE") {
      def a = column[Int]("a")
      def b = column[String]("b")
      def c = column[String]("c", O.Nullable)
      def d = column[Int]("d", O.Nullable)
      def e = column[String]("model_type")
    
      //mapping based on model type column
      def * = a ~ b ~ c.? ~ d.? ~ e <> ({ t => t match {
        case (a, b, Some(c), _, "ChildOne") => ChildOne(a, b, c)
        case (a, b, _, Some(d), "ChildTwo") => ChildTwo(a, b, d)
      }}, {
        case ChildOne(a, b, c) => Some((a, b, Some(c), None, "ChildOne"))
        case ChildTwo(a, b, d) => Some((a, b, None, Some(d), "ChildTwo"))
      })
    }
    } 
    

    Now to determine specific sub type you can do following:

    Query(new MyTable).foreach { 
         case ChildOne(a, b, c) => //childone
         case ChildTwo(a, b, d) => childtwo
    }