【问题标题】:Type mismatch error between Joda DateTime and sql Timestamp in Slick GetResultSlick GetResult 中 Joda DateTime 和 sql Timestamp 之间的类型不匹配错误
【发布时间】:2014-05-15 16:09:37
【问题描述】:

我想检索类型为 DateTime 的列的数据,我正在使用 jodatime。即使我有一个自定义 TypeMapper,我也会收到类型不匹配错误。

[error] C:\sample\modules\test\com\samp\user.scala:55: type mismatch;
[error]  found   : java.sql.Timestamp
[error]  required: org.joda.time.DateTime
[error]             result.nextTimestamp,
[error]                    ^
[error] one error found

这里是代码

import org.specs2.mutable.Specification
import scala.slick.session.Database
import Database.threadLocalSession
import scala.slick.jdbc.{GetResult, StaticQuery => Q}
import Q.interpolation
import org.joda.time.DateTime
import scala.slick.lifted.{MappedTypeMapper,TypeMapper}
import java.sql.Timestamp

class UserSpec
  extends Specification {

  "User tests " should {
    "get all the user data in db" in
      new WithServer() {

      val db = Database.forURL(url = "jdbc:h2:/path/to/db-file", driver = "com.mysql.jdbc.Driver")

      implicit def dateTimeTypeMapper = MappedTypeMapper.base[DateTime, Timestamp] (
        dateTime => new Timestamp(dateTime.getMillis()),
        timeStamp => new DateTime(timeStamp)
      )

      case class user(
        id: String,
        name: String,
        joinedAt: DateTime,
        description: Option[String]
      )

      implicit val getUserResult: GetResult[user] = 
        GetResult( result =>
         user(
           result.nextString,
           result.nextString,
           result.nextTimestamp,
           result.nextStringOption)
      )

      db withSession {
        val usr = Q.queryNA[user]("SELECT * FROM user").list()
        usr foreach println
      }
    }
  }
}

我不确定为什么这不起作用。非常感谢任何帮助或指示。

【问题讨论】:

    标签: scala jodatime playframework-2.1 slick


    【解决方案1】:

    这里的问题是result.nextTimestamp 返回一个java.sql.Timestampresult 是 JDBC ResultSet)。如果你想把它变成DateTime,我认为它有一个构造函数。所以你会写:

    implicit val getUserResult: GetResult[user] = 
      GetResult( result =>
        user(
          result.nextString,
          result.nextString,
          new DateTime(result.nextTimestamp),
          result.nextStringOption)
        )
    

    【讨论】:

    • 正确。 MappedTypeMapper 告诉 Slick 如何为类型安全的查询 api 进行转换。这不是这里需要的。
    • 这帮助我摆脱了编译错误,但现在我看到了运行时异常JdbcSQLException: Cannot parse "TIMESTAMP" constant "1" [22007-168] (DbException.java:158)。有什么建议吗?
    • 在不知道数据和表格是什么样子的情况下很难说什么。很可能您选择的 * 包含比映射更多的列,或者以不同的顺序 - 我建议使用明确的查询,例如 SELECT id, name, joinedAt, description FROM user
    猜你喜欢
    • 2013-03-13
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    相关资源
    最近更新 更多