首页 > 解决方案 > 无法在 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 是非空列。

请提供任何可以在这里工作的适当解决方案。

标签: javahibernatemappingorphan-removal

解决方案


嗯......我有完全相同的逻辑,它对我来说很好。这是我的课

@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}


推荐阅读