加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 18:22:37 所属栏目:安全 来源:网络整理
导读:我使用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 = col
我使用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]类型的证据参数的隐含值

解决方法

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,它将失去时间部分

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读