java - 无法在 OneToMany 映射中删除孩子并添加新孩子 [休眠]
问题描述
我知道这个问题已经被问过很多次了,但没有一个解决方案对我有用。
所以我有一个父类:
class User{
@Id
@NotNull
@Column(name = "`UserId`", nullable = false)
private Long userId;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
@JoinColumn(name = "`UserId`")
private Set<Phone> phoneList;
}
还有一个子类:
class Phone {
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "`UserId`")
private User user;
}
现在,当我收到带有新电话列表的用户类更新时,我想删除所有旧电话并添加新电话。请注意,这所有操作都发生在同一个@Transactional 中。
我试过的解决方案:
user.getPhoneList().clear()
user.getPhoneList().addAll(新电话列表)
当我尝试上述逻辑时,Hibernate 正在尝试将旧手机的 userId 设置为 null。在这个位置,我得到 DataIntegrityViolation,因为 Phone 表中的 userId 是非空列。
请提供任何可以在这里工作的适当解决方案。
解决方案
嗯......我有完全相同的逻辑,它对我来说很好。这是我的课
@Data
@Entity
public class ProductReference {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@OneToMany(mappedBy = "productReference", fetch = FetchType.EAGER, cascade = CascadeType.REMOVE, orphanRemoval = true)
private Set<Attribute> attributes = new HashSet<>();
}
我看到的唯一区别是CascadeType.REMOVE
@Data
@Entity
public class Attribute {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@ManyToOne
private ProductReference productReference;
}
我的删除:
productReference.getAttributes().clear();
你有哪个休眠版本?对我来说是org.hibernate.Version - HHH000412: Hibernate Core {5.4.10.Final}
推荐阅读
- css - Material UI 中的样式如何改变焦点标签的颜色?
- c# - 如何在我的网格中实现用户控件的拖动选择
- eclipse - 由于 http 受到限制,无法在组织网络内访问 Eclipse 市场
- php - 在 symfony 中将值设置为 EntityType 的占位符选项
- java - 由于多重继承,Java 8 无法实现两个接口
- javascript - 从选择框获取值后计算
- json - Oracle ORA-40474 不一致
- arrays - 将 CSV 转换为 JSON,其中一些 JSON 键具有多个值
- javascript - 无法在用户界面中查看 Hyperledger 作曲家发出的事件
- sql - 如何获取仅存在 3 个连续大小的数量?