0

我有用户和角色实体。它们之间存在多对多的关系。如何定义存储库方法以查找具有指定角色的所有用户?我试过了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 集合中。

4

1 回答 1

0

我相信这findByRoles应该足够了。

每当您遇到方法名称问题时,我还建议您使用带有 JPQL 的 @Query 注释。

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

于 2018-01-07T22:09:30.593 回答