我有用户和角色实体。它们之间存在多对多的关系。如何定义存储库方法以查找具有指定角色的所有用户?我试过了findByRolesContaining
,findByRolesContains
但似乎都不起作用。
我需要使用本机查询还是可以使用方法声明?
User
实体
@Entity
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(nullable = false, unique = true)
private String username;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "user_role",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id")
)
private Collection<Role> roles;
private String firstName;
private String lastName;
private String password;
private boolean enabled;
// getters and setters ...
}
Role
实体
@Entity
public class Role {
public static final String SUPER_ADMIN = "SUPER_ADMIN";
public static final String PROJECT_MANAGER = "PROJECT_MANAGER";
public static final String DEVELOPER = "DEVELOPER";
public static final String CLIENT = "CLIENT";
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@ManyToMany(mappedBy = "roles")
private Collection<User> users;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "role_privilege",
joinColumns = @JoinColumn(name = "role_id"),
inverseJoinColumns = @JoinColumn(name = "privilege_id")
)
private Collection<Privilege> privileges;
public Role() {
}
public Role(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Collection<User> getUsers() {
return users;
}
public void setUsers(Collection<User> users) {
this.users = users;
}
public Collection<Privilege> getPrivileges() {
return privileges;
}
public void setPrivileges(Collection<Privilege> privileges) {
this.privileges = privileges;
}
}
我的UserRepository
界面需要一个方法,例如
List<User> findByRole(Role role);
它将返回具有参数中指定角色的所有用户(包含在 User.roles 集合中。