我在Scala中有以下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
当我尝试更新时,出现以下错误:
执行异常[[例外:applyReq中的失败:不同 具有相同标识符值的对象已与该关联 会话: [admin.group.manage.Item#admin.group.manage.Item@50ec]]]
如何解决这个问题?
答案 0 :(得分:2)
如果要修改hibernate会话中已存在的对象,则无法创建新对象,设置相同的ID并期望它将更新原始对象。您需要从会话中实际检索原始对象,然后进行修改。
替换
val it = new Item
与
val it = session.get(classOf[Item], i.index)