首页 文章

@ManyToMany with cascade = CascadeType.REMOVE删除关联和实体

提问于
浏览
4

我有2个实体: GroupGrouped ,有1个ManyToMany关联 .

在数据库中, Association 表在 GroupGrouped 上都有一个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.ALLcascade = 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 回答

  • 4

    这是预期的行为 . 删除级联意味着:删除此实体时,还要删除关联的实体 . 在ManyToXxx上没有任何意义,因为很明显,其他实体仍在引用相关实体 .

    如果要删除Grouped,但保留关联的组,则需要先删除两个实体之间的关联:

    for (Group group : grouped.getGroups()) {
        group.getGrouped().remove(grouped);
    }
    grouped.getGroups().clear();
    

    然后删除不再与任何组关联的Grouped实体 .

相关问题