我有2个实体: Group
和 Grouped
,有1个ManyToMany关联 .
在数据库中, Association
表在 Group
和 Grouped
上都有一个NOT NULL FK .
I want Hibernate to delete the association but not the group when all grouped are deleted.
删除 Grouped
实体的代码:
@Autowired
private final GroupedRepository groupedRepository;
public void delete(Grouped groupedToRemove) {
groupedRepository.delete(groupedToRemove);
}
如果我设置 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<>();
如果我删除级联,hibernate尝试设置group_id = null并抛出 ModelConstraintException
. 我不想将FK设置为可空 .
集团实体:
@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<>();
}
分组实体:
@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<>();
}
1 回答
这是预期的行为 . 删除级联意味着:删除此实体时,还要删除关联的实体 . 在ManyToXxx上没有任何意义,因为很明显,其他实体仍在引用相关实体 .
如果要删除Grouped,但保留关联的组,则需要先删除两个实体之间的关联:
然后删除不再与任何组关联的Grouped实体 .