【发布时间】:2015-09-02 13:25:01
【问题描述】:
我有 2 个实体:Group 和 Grouped,有 1 个多对多关联。
在数据库中,Association 表在 Group 和 Grouped 上都有一个 NOT NULL FK。
我希望 Hibernate 在删除所有分组后删除关联而不是组。
删除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<>();
}
【问题讨论】:
标签: java hibernate jpa many-to-many cascade