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]]]]
如何解決這個問題?
的'@'的Item'包含兩列,'group'和'index',做Id'我要創建這些新的類兩個字段獲取/閱讀該項目? – ps0604
哦,我沒有注意到,你在這裏有一個複合鍵。我認爲創建新類代表複合鍵是更爲優雅的解決方案,但實際上如果沒有它,你可以應付。請參閱https://stackoverflow.com/questions/13375019/hibernate-compsite-key-without-new-class – mateuszlo