2016-04-29 30 views
1

我正在使用光滑的scala項目,因爲它的數據庫訪問庫。我試圖用下面的定義更新一行,其中有一個組合鍵。更新行與從光滑codegen數據庫生成的複合主鍵

class TableName(tag: Tag) extends Table[TableName](tag, "table_name"){ 
    def keyPart1 = column[String]("key_part_1", O.Length(100, varying = true)) 
    def keyPart2 = column[String]("key_part_2", O.Length(100, varying = true)) 
    // More columns defined 
    def pk = primaryKey("t_composite_pk", (keyPart1, keyPart2)) 
    def * (keyPart1, keyPart2, ..more columns..) <> (TableNameRow.tupled, TableNameRow) 
} 

從JdbcActionComponent中使用insertOrUpdate或update方法將無法插入或更新值。有一個known issue浮油與複合主鍵,將阻止這些方法正常工作,因爲它無法確定它應該與哪個標識符相關。但是有一個解決方法。如果將O.PrimaryKey值添加爲組成複合主鍵的行的參數,則光面將能夠正確確定該鍵。

class TableName(tag: Tag) extends Table[TableName](tag, "table_name"){ 
    def keyPart1 = column[String]("key_part_1", O.Length(100, varying = true), O.PrimaryKey) 
    def keyPart2 = column[String]("key_part_2", O.Length(100, varying = true), O.PrimaryKey) 
    // More columns defined 
    def pk = primaryKey("t_composite_pk", (keyPart1, keyPart2)) 
    def * (keyPart1, keyPart2, ..more columns..) <> (TableNameRow.tupled, TableNameRow) 
} 

該項目現在已遷移到使用slick codegen,現在代碼模式是從數據庫的模式動態生成的。這個生成的模式沒有解決複合主鍵的問題。

有使複合主鍵華而不實的代碼生成功能允許使用insertOrUpdate的或更新的方法呢?代碼生成確實有複合主鍵一些支持,但它只是爲下面的值的產生:

/** Primary key of TableName(database name table_name_pk) */ 
val pk = primaryKey("table_name_pk", (keyPart1, keyPart2)) 

然而,這並不顯得不夠光滑,能夠正確識別的行。如果這不能起作用,還有其他方法可以用來更新這些行嗎?

+0

這是政策,使用codegen和不提交生成表scala定義,因此修改生成的文件不是一個選項 –

回答

0

通過檢查有關更新的其他帖子來確定是否使用了此post中的過濾器(...)。update(...)。它可以用下面的辦法來更新:

// Where the following was defined by the codegen 
/** Collection-like TableQuery object for table TableName*/ 
lazy val TableName = new TableQuery(tag => new TableName(tag)) 

// We can then filter on the primary key values 
def updateMethod(row: TableNameRow) = 
    TableName 
     .filter(x => x.keyPart1 === row.keyPart1 && x.keyPart2 === row.keyPart2) 
     .update(row) 

它可以適用於允許行的更新與複合鍵給我們模擬通過過濾器的關鍵。但是,這是一種解決方法,不允許使用JdbcActionComponent中的某些函數。