spring data jpa 多对多查询
程序员文章站
2022-04-23 22:17:17
...
原文: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<Role> 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<Resource> resources = new HashSet<>();
//... 省略gets sets
}
SetJoin<User, Role> roles = root.join(root.getModel().getSet("roles", Role.class), JoinType.LEFT);
Predicate in = roles.in(ids);
//省略Predicate的使用,拿到Predicate后就解决了set集合的in查询
下一篇: Java中的23种设计模式详解