Slick 3.0.0 Mapping Existing Models

I have a model consisting of three case classes, as shown below:

case class MyModel(myId: MyIdType, name: MyNameType)

case class MyIdType(id: Long)
case class MyNameType(name: String)
object MyNameType(name: String) {
  val NAME1 = MyNameType("name1")
  val NAME2 = MyNameType("name2")
  val NAME3 = MyNameType("name3")
}

Say these are existing models. I have a Slick table mapping that looks like this:

  class MyTable(tag: Tag) extends Table[MyTableElem](tag, "myTable") {
    def id                  = column[Long]("id", O.PrimaryKey)
    def name                = column[String]("name")

    def * = (id, name) <> (MyTableElem.tupled, MyTableElem.unapply)
  }

As you can see, I have to have a different type in order to map my MyTable table to MyTableElem first, and then during each reading, I will convert MyTableElem to MyModel. Is there a way to avoid this and go directly to MyModel? I assume that I need to implement interleaved and unapply methods, or?

0
source share
1 answer

, , , . Slick 3.0 ,   MappedTo .

- ( case / ) , MappedTo, ColumnType .

.

import slick.lifted.Tag
// I am using PostgreSQL
import slick.driver.PostgresDriver.api._

case class MyModel(myId: MyIdType, name: MyNameType)

case class MyIdType(id: Long) extends MappedTo[Long] {
  override def value: Long = id
}
case class MyNameType(name: String) extends MappedTo[String] {
  override def value: String = name
}

class MyTable(tag: Tag) extends Table[MyModel](tag, "myTable") {
  def id                  = column[MyIdType]("id", O.PrimaryKey)
  def name                = column[MyNameType]("name")

  def * = (id, name) <> (MyModel.tupled, MyModel.unapply)
}

, , .

+1

Source: https://habr.com/ru/post/1544544/


All Articles