【问题标题】:How can I convert Rep[Option[Instant]] to Rep[Option[String]] in scala如何在 Scala 中将 Rep[Option[Instant]] 转换为 Rep[Option[String]]
【发布时间】:2016-09-07 13:42:51
【问题描述】:

我正在使用 scala play 2、slick 和 postgresql 作为数据库。我的功能之一是

def getAllCustomersWithAccount: Future[Seq[CustomerDetail]] = {
val joinException = for {
  (customer, account) <- table join accountTable on (_.id === _.id)
} yield (customer.id, account.name, account.phone, account.email, customer.status, customer.balance, customer.payable, customer.created, customer.updated)

val result = db.run(joinException.result)
result.map(row => row.map(x => CustomerDetail(x._1, x._2, x._3, x._4, x._5, x._6, x._7, x._8, x._9)))
}

此代码不起作用。问题是创建和更新客户的属性。也就是说 customer.created 和 customer.updated 是 Rep[Option[Instant]] ,它是日期时间。如果我转义这两列(customer.created 和 customer.updated),那就没问题了。那就是

def getAllCustomersWithAccount: Future[Seq[CustomerDetail]] = {
    val joinException = for {
      (customer, account) <- table join accountTable on (_.id === _.id)
    } yield (customer.id, account.name, account.phone, account.email, customer.status, customer.balance, customer.payable)
    val result = db.run(joinException.result)
    result.map(row => row.map(x => CustomerDetail(x._1, x._2, x._3, x._4, x._5, x._6, x._7)))
}

此代码运行良好。我想将 Rep[Option[Instant]] 转换为 Rep[Option[String]]。我该怎么做?

【问题讨论】:

    标签: scala slick


    【解决方案1】:

    Slick 需要从 custom types 到已知 jdbc typesMapping。在您的情况下,为光滑提供从 DateTimeTimestampInstantTimestamp 的隐式映射。这有助于slicknative database supported types 的角度理解custom types

    implicit def jodaTimeMapping: BaseColumnType[DateTime] = MappedColumnType.base[DateTime, Timestamp](
    dateTime => new Timestamp(dateTime.getMillis),
    timeStamp => new DateTime(timeStamp.getTime))
    

    以上implicit 帮助SlickDateTime 转换为Timestamp,反之亦然。

    Instant类型的情况

    假设InstantDateTime 的包装器

    case class Instant(time: DateTime)
    
    implicit def instantMapping: BaseColumnType[Instant] = MappedColumnType.base[Instant, Timestamp](
    instant => new Timestamp(instant.time.getMillis),
    timeStamp => Instant(new DateTime(timeStamp.getTime)))
    

    java.time.Instant 的 Slick 隐式映射

    import java.sql.Timestamp
    
    implicit def instantMapping: BaseColumnType[Instant] = MappedColumnType.base[Instant, Timestamp](
    instant => new Timestamp(instant.toEpochMilli),
    timeStamp => Instant.ofEpochMilli(timeStamp.getTime))
    

    【讨论】:

    • 感谢您的回答。你能清楚你的答案吗?我该如何解决这个问题?我只想将Rep[Option[Instant]] 转换为Rep[Option[String]]
    • 提供从InstantString的转换。隐式 def instantMapping: BaseColumnType[Instant] = MappedColumnType.base[Instant, String](....)
    • 需要更多关于即时的信息...编写完整的代码
    • @Md.ShougatHossain Instant 是什么?它是自定义对象吗?如果它是一个自定义对象。它的内容是什么
    • java.time.Instant
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 2022-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多