spring data jpa 多对多查询

原文:https://www.toocruel.net/spring-data-jpa-duo-dui-duo-cha-xun/
以用户-角色 多读多为例:

User类,用户

@Entity
public class User {
    private String username;
    private String nickname;
    private String password;
    private String avatar;
    private String email;
    private String mobile;

    /**
     * 用户的所有角色
     */
    @ManyToMany(cascade = CascadeType.DETACH)
    @JoinTable(name = "user_role_relation",joinColumns = @JoinColumn(name = "userId"),inverseJoinColumns = @JoinColumn(name = "roleId"))
    private Set roles = new HashSet<>();

   //...省略gets sets
}

Role类,角色

@Entity
public class Role {
    /**
     * 角色名称
     */
    private String name;
    /**
     * 角色拥有权限的资源集合
     */
    @ManyToMany(cascade = CascadeType.DETACH,fetch = FetchType.EAGER)
    @JoinTable(name = "role_resource_relation",joinColumns = @JoinColumn(name = "roleId"),inverseJoinColumns = @JoinColumn(name = "resourceId"))
    private Set resources  = new HashSet<>();

    //... 省略gets sets
}
SetJoin roles = root.join(root.getModel().getSet("roles", Role.class), JoinType.LEFT);
Predicate in = roles.in(ids);

//省略Predicate的使用,拿到Predicate后就解决了set集合的in查询

你可能感兴趣的:(spring data jpa 多对多查询)