如何从多对多关系实体中删除对象

时间:2019-05-13 06:24:46

标签: hibernate groovy micronaut

我想删除一个仪表板并检查它是否也存在于dashboardGroup列表中,然后也将其从仪表板组中删除。

实体仪表板和dashboardGroup具有多对多关系,请检查以下代码:

if(params.id){
     def dashboard = Dashboard.get(params.id)
     if (dashboard) {
        def dashboardGroups = dashboard.dashboardGroups
        for(DashboardGroup dashGroup : dashboardGroups){
           dashboard.removeFromDashboardGroups(dashGroup)
        }
        dashboard.delete() 
}

2 个答案:

答案 0 :(得分:0)

if(params.id) {
   def dashboard = Dashboard.get(params.id)
   if (dashboard) {
       dashboard.dashboardGroups*.remove(dashboard)
       dashboard.delete()
 }

答案 1 :(得分:0)

您应该为此使用OrphanRemoval。例如:

public class Dashboard {

    @ManyToMany
    @Cascade(value = org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
    private Set<DashboardGroup> dashboardGroups = new HashSet<DashboardGroup>();

}

尝试时:

Dashboard dashboard = entityManager.find(Dashboard.class, 1L);
entityManager.remove(dashboard);

它将删除关联的dashboardGroups