org.joda.time.DateTime 到 java.sql.Timestamp 从模型到光滑 Table[] 的隐式转换

implicit conversion of org.joda.time.DateTime to java.sql.Timestamp from a model to a slick Table[]

我有一个模型需要 org.joda.time.DateTime 但是我传递了一个由 slick 对象 Table[] 使用的 java.sql.Timestamp,我尝试使用隐式转换但它不起作用

import models.Carros.convertDateToTimestamp // this has a parameter DateTime and a return Timestamp
def * = (id, name, year, description, img, keywords, state, model, datein) <>
((Carro.apply _).tupled, Carro.unapply) // so here when unpacking shouldn't the implicit conversion do it's job?

显示的错误在这里:

No matching Shape found. Slick does not know how to map the given types. Possible causes: T in Table[T] does not match your * projection. Or you use an unsupported type in a Query (e.g. scala List). Required level: slick.lifted.FlatShapeLevel Source type: (slick.lifted.Rep[Option[Long]], slick.lifted.Rep[String], slick.lifted.Rep[Int], slick.lifted.Rep[String], slick.lifted.Rep[String], slick.lifted.Rep[String], slick.lifted.Rep[String], slick.lifted.Rep[Long], slick.lifted.Rep[java.sql.Timestamp]) Unpacked type: (Option[Long], String, Int, String, String, String, String, Long, org.joda.time.DateTime) Packed type: Any

您需要将 datebin 的类型声明为 org.joda.DateTime,而不是 java.sql.Timestamp:

class CarroTable extends Table[Carro](tag: "carro") {
  ...
  val datebin = column[org.joda.DateTime]("datebin")

  def * = (id, name, year, description, img, keywords, state, model, datein) <> (Carro.tupled, Carro.unapply)

}

然后确保你有一个隐式类型映射器:

implicit val JodaDateTimeMapper = MappedColumnType.base[DateTime, Timestamp](
  dt => new Timestamp(dt.getMillis),
  ts => new DateTime(timestamp.getTime())
)

Roman 的回答是正确的,但有一个警告...

如果将隐式 MappedColumnType 放在同一文件中,则必须将其放在 Table 定义之上,或者将其放在另一个文件中并导入。如果您不这样做,则隐式解析将无法找到它。

你可以在这个

中看到

所以为了迂腐地正确,你应该这样做:-

object implicitDateTimeConverters {
  implicit val JodaDateTimeMapper = MappedColumnType.base[DateTime, Timestamp](
    dt => new Timestamp(dt.getMillis),
    ts => new DateTime(timestamp.getTime())
  )
}

import implicitDateTimeConverters._

class CarroTable extends Table[Carro](tag: "carro") {
  ...
  val datebin = column[org.joda.DateTime]("datebin")

  def * = (id, name, year, description, img, keywords, state, model, datein) <> (Carro.tupled, Carro.unapply)

}