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
}

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查询

(全文完)

(转载本站文章请注明作者和出处 spring data jpa 多对多查询