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



我有一个模型,它接受一个org.joda.time.DateTime然而,我正在传递一个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?

错误显示如下:

没有找到匹配的形状。斯利克不知道如何映射给定的类型。可能原因:表[T]中的T与您的*不匹配投影。或者在查询中使用不支持的类型(例如scala列表)。要求等级:slick.lifted. flatshapellevel(slick.lifted。代表[时间]][选项,slick.lifted.Rep(字符串),slick.lifted。代表(Int), slick.lifted.Rep(字符串),slick.lifted。代表(字符串),slick.lifted.Rep(字符串),slick.lifted。代表(字符串),slick.lifted.Rep(长)[java.sql.Timestamp])解压类型:(选项[长],String, Int, String, String, String, String, Long,打包类型: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放在同一个文件中,或者将它放在另一个文件中并导入它,则必须将它放在表定义之上。如果你不这样做,那么隐式解析将无法找到它。

你可以在另一个StackOverflow问题中看到

所以为了学究正确,你应该这样做:-

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)
}

最新更新