spring data jpa 多对多查询
程序员文章站
2022-04-23 22:17:23
...
spring data jpa 多对多查询
以用户-角色 多读多为例:
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<Role> roles = new HashSet<>();
//...省略gets sets
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
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<Resource> resources = new HashSet<>();
//... 省略gets sets
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
SetJoin<User, Role> roles = root.join(root.getModel().getSet("roles", Role.class), JoinType.LEFT);
Predicate in = roles.in(ids);
//省略Predicate的使用,拿到Predicate后就解决了set集合的in查询