[英]@ManyToMany with cascade = CascadeType.REMOVE removes associations AND entities
I have 2 entities: Group
and Grouped
, with 1 ManyToMany association. 我有2个实体:
Group
和Grouped
,有1个ManyToMany关联。
In database, the Association
table has a NOT NULL FK on both Group
and Grouped
. 在数据库中,
Association
表在Group
和Grouped
上都有一个NOT NULL FK。
I want Hibernate to delete the association but not the group when all grouped are deleted. 我希望Hibernate在删除所有分组时删除关联,但不删除组。
Code to delete a Grouped
entity: 删除
Grouped
实体的代码:
@Autowired
private final GroupedRepository groupedRepository;
public void delete(Grouped groupedToRemove) {
groupedRepository.delete(groupedToRemove);
}
If I set cascade = CascadeType.ALL
or cascade = CascadeType.REMOVE
, my Group
entities are deleted when I delete a Grouped
entity, not only the associations: 如果我设置
cascade = CascadeType.ALL
或cascade = CascadeType.REMOVE
,当我删除Grouped
实体时,我的Group
实体将被删除,而不仅仅是关联:
@ManyToMany(cascade = CascadeType.ALL, // same behavior with CascadeType.REMOVE
mappedBy = "grouped",
targetEntity = Group.class)
private Set<Group> groups = new HashSet<>();
If I remove the cascade, hibernate tries to set group_id=null and it throws a ModelConstraintException
. 如果我删除级联,休眠尝试设置GROUP_ID = null,并且它抛出一个
ModelConstraintException
。 I don't want to set the FK as nullable. 我不想将FK设置为可空。
Group entity: 集团实体:
@Entity
@Table(name = "groups")
@Getter
@Setter
public class Group {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@ManyToMany(targetEntity = Grouped.class)
@JoinTable(
name = "association",
joinColumns = @JoinColumn(name = "group_id", nullable = false, updatable = false),
inverseJoinColumns = @JoinColumn(name = "grouped_id", nullable = false, updatable = false)
)
private Set<Grouped> grouped= new HashSet<>();
}
Grouped entity: 分组实体:
@Entity
@Table(name = "grouped")
@Getter
@Setter
public class Grouped {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@ManyToMany(mappedBy = "grouped", targetEntity = Group.class)
private Set<Group> groups= new HashSet<>();
}
That's the expected behavior. 这是预期的行为。 REMOVE cascading means: when removing this entity, also remove the associated entities.
删除级联意味着:删除此实体时,还要删除关联的实体。 It makes no sense on a ManyToXxx, since obviously, other entities are still referencing the associated entity.
在ManyToXxx上没有任何意义,因为很明显,其他实体仍在引用相关实体。
If you want to delete a Grouped, but leave the associated Groups there, you need to remove the association between the two entities first: 如果要删除Grouped,但将关联的组保留在那里,则需要首先删除两个实体之间的关联:
for (Group group : grouped.getGroups()) {
group.getGrouped().remove(grouped);
}
grouped.getGroups().clear();
and then remove the Grouped entity, which is not associated to any Group anymore. 然后删除不再与任何组关联的Grouped实体。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.