【问题标题】:implicit conversion of org.joda.time.DateTime to java.sql.Timestamp from a model to a slick Table[]org.joda.time.DateTime 到 java.sql.Timestamp 从模型到光滑表的隐式转换 []
【发布时间】:2016-11-06 19:59:45
【问题描述】:

我有一个采用 org.joda.time.DateTime 的模型 但是我传递了一个光滑对象 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?

显示的错误在这里:

未找到匹配的形状。 Slick 不知道如何映射给定的 类型。可能的原因: Table[T] 中的 T 与您的 * 不匹配 投影。或者您在查询中使用不受支持的类型(例如 scala 列表)。所需级别:slick.lifted.FlatShapeLevel 源类型: (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]) 解压类型:(Option[Long], 字符串,整数,字符串,字符串,字符串,字符串,长, org.joda.time.DateTime) 打包类型:Any

【问题讨论】:

    标签: scala datetime playframework slick


    【解决方案1】:

    您需要将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())
    )
    

    【讨论】:

      【解决方案2】:

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

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

      你可以在other StackOverflow question看到这个

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

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

      【讨论】:

        猜你喜欢
        • 2016-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-25
        • 2016-05-19
        相关资源
        最近更新 更多