通过嵌套集合方法签名进行Spring Data查询

时间:2018-01-07 17:54:26

标签: java spring spring-data spring-repositories

我有用户和角色实体。他们之间有很多关系。如何定义存储库方法以查找具有指定角色的所有用户?我尝试了findByRolesContainingfindByRolesContains,但两者似乎都没有用。

我是否需要使用本机查询,或者是否可以使用方法声明?

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集合中。

1 个答案:

答案 0 :(得分:0)

我认为只需findByRoles即可。

我还建议在方法名称出现问题时随时使用JPQL @Query注释。

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.at-query