我正在使用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]]。我怎么能这样做?
答案 0 :(得分:2)
光滑需要Mapping
custom types
到已知jdbc types
。在您的案例中,为DateTime
到Timestamp
或Instant
到Timestamp
的光滑提供隐式映射。这有助于slick
根据custom types
了解native database supported types
。
implicit def jodaTimeMapping: BaseColumnType[DateTime] = MappedColumnType.base[DateTime, Timestamp](
dateTime => new Timestamp(dateTime.getMillis),
timeStamp => new DateTime(timeStamp.getTime))
上方implicit
可帮助Slick
将DateTime
转换为Timestamp
,反之亦然。
如果是即时类型
假设Instant
是DateTime
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)))
Slick Implicit for java.time.Instant
import java.sql.Timestamp
implicit def instantMapping: BaseColumnType[Instant] = MappedColumnType.base[Instant, Timestamp](
instant => new Timestamp(instant.toEpochMilli),
timeStamp => Instant.ofEpochMilli(timeStamp.getTime))