CascadeType.SAVE_UPDATE: 具有相同标识符值的不同对象已与会话相关联

CascadeType.SAVE_UPDATE: A different object with the same identifier value was already associated with the session

我有一个 User 实体,它与 Address

有 ManyToOne 关系
@NotNull
@ManyToOne
@Cascade(CascadeType.SAVE_UPDATE)
@JoinColumn(name = "id_registered_address")
private Address registeredAddress;

当我将来自数据库 (dao.getById) 的地址设置为 'registeredAddress',然后在我的用户实体上调用 saveOrUpdate 时,我得到:

A different object with the same identifier value was already associated with the session

如果我设置一个新创建的地址实体,这个实体会正确保存在数据库中。

我做错了什么?

这意味着 hibernate 在会话中找到 2 个或更多地址,并且它不知道在更新地址时使用哪一个。可能是你两次获取相同的地址。