Don't know how to findByRole to return a customised list of users

Viewed 99

I am trying to list users in my application based on role. I have an endpoint in my controller which tries to call my userService class .findByRoles method but I dont know how to put the role I want to without having the role as a string(wont work).

adminController.java method:

@GetMapping(path="/users")
public String showUsers( Model model){
    var userList = (List<User>) userService.findByRoles("ROLE_TEACHER"); // dont know how to pass a role here
    model.addAttribute("userList", userList);
    return "users";
}

User.java:

@Entity
@Table(name = "user_table", schema = "public")
public class User {

    @Id
    @Column(name = "user_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long user_id;

    @Column(name = "name")
    private String name;

    @Column(name = "username")
    private String username;

    @Column(name = "password")
    private String password;

    @Column(name = "email")
    private String email;

    @Column(name = "confirmed")
    private boolean confirmed;

    @ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.DETACH}, fetch = FetchType.EAGER)
    @JoinTable(
            name = "user_role_table",
            joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "role_id"))
    private Collection<Role> roles = new HashSet<>();



    /*******************************************
     * Setters and getters
     *******************************************/

    public Long getId() {
        return user_id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getUsername() {
        return username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPassword() {
        return password;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getEmail() {
        return email;
    }

    public void setConfirmed(Boolean confirmed) {
        this.confirmed = confirmed;
    }

    public Boolean getConfirmed() {
        return confirmed;
    }

    public void setRoles(Collection roles) {
        this.roles = roles;
    }

    public Collection<Role> getRoles() { return this.roles;
    }
}

userRepository:

public interface UserRepository extends JpaRepository<User, Long> {
    User findByUsername(String username);
    User findByEmail(String email);
    User findByRoles(Role role);
}

roleRepository:

public interface RoleRepository extends JpaRepository<Role, Long> {

    Role findByName(String name);
}

IUserService.java:

public interface IUserService {

    User registerNewUserAccount(UserDto userDto);

    List<User> findAll();

    Optional<User> findById(Long id);

    User findByRoles(Role role);

    public void delete(Long id);

    public User updateConfirmed(Long id);

}

UserService.java method:

@Override
public User findByRoles(Role role) {
    return userRepository.findByRoles(role);
}

Any tips how I can go about to fix this issue?

1 Answers

After tweaking around with the classes I think the most logical method to fix the issue is to use roleRepository method findByName. Furthermore, created findAllByRoles in userRepository, IUserService & UserService for returning a list(check my comment on this answer).

Changed IUserService.java to:

public interface IUserService {

     User registerNewUserAccount(UserDto userDto);

     List<User> findAll();

     Optional<User> findById(Long id);

     List<User> findAllByRoles(String roles); //Added this new method (VERY IMPORTANT for returning multiple users)

     User findByRoles(String roles);

     public void delete(Long id);

     public User updateConfirmed(Long id);
}

Changed UserService.java method to:

@Override
public User findByRoles(String roles) {
    return userRepository.findByRoles(roleRepository.findByName(roles)); // Using roleRepository here
}

// Added below findAllbyRoles to return a list

@Override
public List<User> findAllByRoles(String roles){
    return userRepository.findAllByRoles(roleRepository.findByName(roles));
}

Changed adminController.java method to:

@GetMapping(path="/users")
public String showUsers( Model model){
    List<User> userList = userService.findAllByRoles("ROLE_STUDENT");
    userList.addAll(userService.findAllByRoles("ROLE_TEACHER"));
    model.addAttribute("userList", userList);
    return "users";
}
Related