2017-09-03 81 views
2

我有以下的Hibernate類Group和斯卡拉Items其中一個Group包含許多Items錯誤:休眠+斯卡拉:當刪除和重新插入孩子

@Entity 
@Table(name = "items") 
class Item extends Serializable { 

    @Id 
    @ManyToOne 
    @JoinColumn(name="group_sk", nullable=false) 
    var group: Group = _ 

    @Id 
    var index: Int = _ 

    var name: String = _ 

    def canEqual(a: Any) = a.isInstanceOf[Item] 

    override def equals(that: Any): Boolean = 
     that match { 
      case that: Item => that.canEqual(this) && this.hashCode == that.hashCode 
      case _ => false 
    } 

    override def hashCode: Int = { 
     val prime = 31 
     var result = 1 
     result = prime * result + group.sk; 
     result = prime * result + index 
     return result 
    } 

} 


@Entity 
@Table(name = "groups") 
class Group { 

    @Id 
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "group_generator") 
    @SequenceGenerator(name="group_generator", 
    sequenceName = "GroupSeq", allocationSize = 1)  
    var sk: Int = _ 

    @Column(name = "group_name") 
    var name: String = _ 

    @OneToMany(cascade=Array(CascadeType.ALL)) 
    @JoinColumn(name="group_sk") 
    var items: java.util.List[Item] = _ 
} 

假設我有1組與項目A和B 。爲了更新組,我讓用戶編輯項目,所以當我保存組時,我首先清除Items數組,然後添加新的項目(注意用戶可能會留下一些項目,所以這些項目將被刪除並重新插入):

val group = session.get(classOf[Group],groupCode) 
session.beginTransaction 
group.name = "Group 1x" 
group.items.clear 
for (i <- updatedItems) { 
     val it = new Item 
     it.group = group 
     it.index = i.index 
     it.name = i.name 
     group.itemss.add(it) 
} 
session.update(group) 
session.getTransaction.commit 

當我嘗試更新,我得到以下錯誤:

Execution exception[[Exception: Failure in applyReq: A different object with the same identifier value was already associated with the session : [admin.group.manage.Item#[email protected]]]]

如何解決這個問題?

回答

2

如果你想修改一個已經存在於hibernate session中的對象,你不能只是創建一個新的對象,設置相同的id並期待它會更新原始對象。您需要實際從會話中檢索原始對象,然後對其進行修改。

更換

val it = new Item 

val it = session.get(classOf[Item], i.index) 
+0

的'@'的Item'包含兩列,'group'和'index',做Id'我要創建這些新的類兩個字段獲取/閱讀該項目? – ps0604

+0

哦,我沒有注意到,你在這裏有一個複合鍵。我認爲創建新類代表複合鍵是更爲優雅的解決方案,但實際上如果沒有它,你可以應付。請參閱https://stackoverflow.com/questions/13375019/hibernate-compsite-key-without-new-class – mateuszlo