Hibernate annotations ——@ManyToMany

1.此处以用户和角色作为实体进行多对多映射,用@JoinTable指定中间表的名称

User.java

@Entity
public class User {

    private Integer id;
    private String name;
    private Set<Role> roles;

    @Id
    @GeneratedValue
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @ManyToMany
    @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
    public Set<Role> getRoles() {
        return roles;
    }

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

}

 

Role.java

@Entity
public class Role {

    private Integer id;
    private String name;

    @Id
    @GeneratedValue
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

 

3.删除中间表的数据

user表

id name
1 xxx

 

role表

id name
1 admin

 

user_role表

 

user_id role_id
1 1

 

只需查询user,然后修改user中关联的role,再重新保存user即可

public class HibernateTestCase {

    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        User user = (User) session.get(User.class, 1);
        user.getRoles().clear();
        session.merge(user);
        session.flush();
        session.close();
    }

}

 

你可能感兴趣的:(Hibernate,@manytomany)