JpaRepository find User with Role in list of roles

user3626048 picture user3626048 · Feb 8, 2017 · Viewed 9.5k times · Source

I'm using Spring with Hibernate and JpaRepository as database repository.

I have two classes for user storage:

@Entity
public class User {
    @Id
    private Long id;

    private String username;

    private String password;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    private List<UserRole> roles;
}

@Entity
public class UserRole {
    @Id
    private Long id;

    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    @Enumerated(EnumType.STRING)
    private Role role;
}

public enum Role {
    ADMIN,
    MEMBER;
    /* some others in the future */
}

As you can see User can have multiple roles assigned. So user1 can have ADMIN and MEMBER roles and user2 only MEMBER role.

I would like to user with ADMIN role (among others) could list all users in database (JpaRepository findAll() method is enough) but user with only MEMBER role could list only users with MEMBER role.

How to write method in JpaRepository to achieve that? I tried some below but it's not working:

List<User> findByRoles_RoleIn(Collection<Role> roles);

or

List<User> findByRoles_Role(Role role);

Maybe some custom @Query?

Answer

Maciej Kowalski picture Maciej Kowalski · Feb 8, 2017

If you can go for a custom query then try following:

@Query( "select u from User u inner join u.roles r where r.role in :roles" )
List<User> findBySpecificRoles(@Param("roles") List<Role> roles);