2016-09-07 44 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

你確定有作品???????????你可以顯示完整的代碼嗎? –

相關問題