2016-12-28 107 views
4

創建通用的更新功能,我有這樣的溫控功能:的油滑3.1.1

def updateInvoiceAdminStatusField(id: Int, newAdminStatus: AdminStatus): Future[Int] = { 


    db.run { 

     val adminStatus: Query[Rep[AdminStatus], AdminStatus, Seq] = InvoicesTable.filter(invoice => invoice.id === id).map(invoice => invoice.status) 

     adminStatus.update(newAdminStatus) 
    } 
    } 

我想使其成爲通用的:

def updateInvoiceField[T](id: Int, fieldExtractor: (Invoices) => Rep[T], newValue: T): Future[Int] = { 

    db.run { 

     val adminStatus = InvoicesTable.filter(invoice => invoice.id === id).map(invoice => { 

     fieldExtractor(invoice) 
     }) 

     adminStatus.update(newValue) 
    } 
    } 

但是,這並不編譯。有人可以協助嗎?

回答

2

它幾乎不錯。有了這樣低於它應該工作的小變化:

// I added below T: ColumnType 
def updateInvoiceField[T: ColumnType](id: Int, fieldExtractor: (Invoices) => Rep[T], newValue: T): Future[Int] = { 

    db.run { 
     val adminStatus = InvoicesTable.filter(invoice => invoice.id === id).map(invoice => { 
      fieldExtractor(invoice) 
     }) 

     adminStatus.update(newValue) 
    } 
} 

通知我加入這個: ColumnType這基本上意味着你需要有適當的範圍內隱 - 特別是將轉換T =>ColumnType[T]之一。這只是因爲否則T可能是任何東西,Slick將無法​​弄清楚如何轉換它。

因此,對於像String,Int等事情,您顯然已經有適當的對話(在配置文件/驅動程序中從api導入)。對於您自定義類型,您需要使用MappedColumnType來提供適當的轉換。下面的示例(類型安全ID):

implicit def columnType[T]: BaseColumnType[Id[T]] = 
    MappedColumnType.base[Id[T], Long](toLong, fromLong) 

private def fromLong[T](dbId: Long): Id[T] = Id(dbId) 

private def toLong[T](id: Id[T]): Long = id.value 
+0

解決了這個問題。謝謝! –