Slick 2.0在表中映射java.util.Date

时间:2014-05-08 14:27:50

标签: scala slick-2.0

我使用slick 2.0,我有一个简单的案例类:

case class Message(id: Option[Long], userId: Option[Long], body:String, creationDate:Date)

以下映射:

class Messages(tag: Tag) extends Table[Message](tag, "message") {
  import Mapping.Mapper._

  def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
  def userId = column[Long]("user_id")
  def body = column[String]("body")
  def creationDate = column[java.util.Date]("creationDate")
  def * = (id.?, userId.?, body, creationDate) <> (Message.tupled, Message.unapply _)
}

我导入了这个隐式映射器:

implicit def date2sqlDate(d: java.util.Date): java.sql.Date = new java.sql.Date(d.getTime())

我一直收到这个错误:

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: 
scala.slick.lifted.ShapeLevel.Flat Source type:
(scala.slick.lifted.Column[Option[Long]], 
scala.slick.lifted.Column[Option[Long]], 
scala.slick.lifted.Column[String], 
scala.slick.lifted.Column[java.sql.Date]) 
Unpacked type: (Option[Long], Option[Long], String, java.util.Date)
Packed type: Any

如何在表格中使用java.util.Date? 我不想使用JodaTime或其他所有东西,我只想要简单的旧java.util.Date。

看起来我们需要使用MappedColumnType http://slick.typesafe.com/doc/2.0.1/userdefined.html#scalar-types

但像这样的简单映射不起作用

implicit val date2sqlDateMapper = JdbcDriver.MappedJdbcType.base[java.util.Date, java.sql.Date](
      { d => date2sqlDate(d) }, 
      { sqlDate => sqlDate } 
      )

我会得到     找不到scala.slick.driver.JdbcDriver.BaseColumnType [java.sql.Date]

类型的证据参数的隐含值

1 个答案:

答案 0 :(得分:11)

  implicit val JavaUtilDateMapper =
    MappedColumnType .base[java.util.Date, java.sql.Timestamp] (
      d => new java.sql.Timestamp(d.getTime),
      d => new java.util.Date(d.getTime))

你需要在隐式范围内有这样的东西,正如你所注意到的,java.util.Date被映射到java.sql.Timestamp,如果映射到java.sql.Date,它将失去时间部分