2016-09-07 29 views
0

我正在使用scala play 2,slick和postgresql作为数据库。我的一个功能就像我如何将Rep [Option [Instant]]转换为scala中的Rep [Option [String]]

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]]。我怎样才能做到这一点?

回答

2

油滑需要Mappingcustom types到已知的jdbc types。在你的情况下,提供从DateTimeTimestampInstantTimestamp的隐式映射。这有助于slick根据native 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帮助Slick转换DateTimeTimestamp,反之亦然。

在即时型的情况下

假设Instant是一个包装的java.time.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))) 

油滑的隐式映射

import java.sql.Timestamp 

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

感谢您回答。你能否清楚你的答案?我该如何解决这个问题?我只想将Rep [Option [Instant]]转换为'Rep [Option [String]]' –

+0

提供从'Instant'到'String'的转换。隐式def instantMapping:BaseColumnType [Instant] = MappedColumnType.base [Instant,String](....) – pamu

+0

你确定有作品???????????你可以显示完整的代码吗? –

相关问题