首页 > 代码库 > 多对多manytomany

多对多manytomany

----------------------多对多manytomany要点:多对多必须有mappedBy,让一个端维护关系多对多会创建一张关系表,维护关系就是维护第三张表。所以增加关系,则在集合中添加实体。删除关系,则从集合中删除实体。mappedBy使一方丧失关系维护@Entitypublic class User {    @Id    @GeneratedValue    private long id;        @Column(name="name")    private String name;        @ManyToMany(cascade=CascadeType.PERSIST,mappedBy="users")    private Set<Role> roles = new HashSet<Role>();}@Entitypublic class Role {    @Id    @GeneratedValue    private long id;    @Column    private String name;    @ManyToMany    private Set<User> users = new HashSet<User>();    public String getName() {        return name;} 删除用户139的ADMIN权限        User u = session.get(User.class,139L);        Set<Role> roles = u.getRoles();        Iterator<Role> ites = roles.iterator();        while(ites.hasNext()) {            Role r = ites.next();            if(r.getName().equals("ADMIN")){                r.getUsers().remove(u);//执行成功,删除关系,而不删除用户                //u.getRoles().remove(r);//执行失败,关系它不维护            }        }

 

多对多manytomany