![](/img/trans.png)
[英]save an object with childs in Hibernate/JPA - @OneToMany
[英]Unable to remove childs in OneToMany Mapping and add new childs [Hibernate]
我知道這個問題已經被問過很多次了,但沒有一個解決方案對我有用。
所以我有一個父 class:
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:
class Phone {
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "`UserId`")
private User user;
}
現在,當我收到帶有新手機列表的用戶 class 的更新時,我想刪除所有舊手機並添加新手機。 請注意,這所有操作都發生在同一個@Transactional 中。
我試過的解決方案:
user.getPhoneList().clear()
user.getPhoneList().addAll(新電話列表)
當我嘗試上述邏輯時,Hibernate 正在嘗試將舊手機的 userId 設置為 null。 在這個 position 我得到 DataIntegrityViolation 因為電話表中的 userId 不是 null 列。
請提供任何可以在這里工作的適當解決方案。
嗯......我有完全相同的邏輯,它對我來說很好。 這是我的課
@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();
你有哪個 Hibernate 版本? 我是org.hibernate.Version - HHH000412: Hibernate Core {5.4.10.Final}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.