Hibernate @ManyToMany delete relation

社会主义新天地 提交于 2019-11-29 00:28:51

What you need is the @JoinTable attribute:

Hibernate does not know that the many-to-many relations refer to each other and will probably create two join tables. If you specify the same @JoinTable on both sides of the relation it will work as expected.

Make sure that the joinColumn and the inverseJoinColumn are opposites on the opposing sides of the relation.

  • joinColumn on one side == inverseJoinColumn on other side
  • inverseJoinColumn on one side == joinColumn on other side

I hope this helps.

@Entity
public class Role extends Identifiable {

    @ManyToMany(cascade ={CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinTable(name="Role_Permission",
            joinColumns=@JoinColumn(name="Role_id"),
            inverseJoinColumns=@JoinColumn(name="Permission_id")
        )
    public List<Permission> getPermissions() {
        return permissions;
    }

    public void setPermissions(List<Permission> permissions) {
        this.permissions = permissions;
    }
}

@Entity
public class Permission extends Identifiable {

    @ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinTable(name="Role_Permission",
            joinColumns=@JoinColumn(name="Permission_id"),
            inverseJoinColumns=@JoinColumn(name="Role_id")
        )
    public List<Role> getRoles() {
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }

}

I think you must as this annotaion

    @OnDelete(action = OnDeleteAction.CASCADE)
    @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)

and change cascade.remove to CascadeType.ALL your code must be something like this

   @ManyToMany(cascade = CascadeType.ALL, mappedBy = "users")
   @OnDelete(action = OnDeleteAction.CASCADE)
   @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
   private List<UsersList> usersLists = new ArrayList<UsersList>();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!