In my Spring Boot application, I have two entities user and authorities. There are three parameters ROLE_USER, ROLE_ADMIN, and ROLE_SYSTEM is assignable to the user as Authority and one user can have multiple authorities. in the user entity I have created join column which joins user and authority, so I can assign multiple authority to a user using Join table, the Entity field is shown below:
@JsonIgnore
@ManyToMany
@JoinTable(
name = "jhi_user_authority",
joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name")})
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@BatchSize(size = 20)
private Set<Authority> authorities = new HashSet<>();
so, using this field hibernate created the third table which has a user id and authority role. In Repository, I have used Hibernate JPARepository. and using findAll() I am getting all users. Controller:
In Controller:
@GetMapping("/users")
@Timed
@Secured({ AuthoritiesConstants.ADMIN, AuthoritiesConstants.SYSTEM })
public ResponseEntity<List<UserDTO>> getAllUsers(Pageable pageable) {
final Page<UserDTO> page = userService.getAllManagedUsers(pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/users");
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
In Service:
@Transactional(readOnly = true)
public Page<UserDTO> getAllManagedUsers(Pageable pageable) {
return userRepository.findAll(pageable).map(UserDTO::new);
}
In Repository:
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Page<User> findAll(Pageable pageable);
}
I have tried with this in the repository:
@Query("select users from User users where users.authorities = 'ROLE_USER'")
Page<User> getAllByAuthoriy(Pageable pageable);
Authority entity:
@Entity
@Table(name = "jhi_authority")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Authority implements Serializable {
private static final long serialVersionUID = 1L;
@NotNull
@Size(max = 50)
@Id
@Column(length = 50)
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
So, Now I have to change the query from findAll to findAllByAuthorities(Pageable pageable, set authorities). but this not works, showing type casting error. How to fetch all that user which role is ROLE_USER?
Here is the solution, I have to write a query for getting users from user table which authority is a user_role. for that, I have to pass a string to match in HashSet.
@Query("select users from User users where 'ROLE_USER' member of users.authorities")
Page<User> getAllByAuthoriy(Pageable pageable);