在我的Spring Boot应用程序中,我有两个实体用户和权限。有三个参数ROLE_USER、ROLE_ADMIN和ROLE_SYSTEM可分配给用户作为权限,一个用户可以有多个权限。在用户实体中,我创建了连接用户和权限的连接列,因此我可以使用连接表将多个权限分配给一个用户,实体字段如下所示:
@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<>();
因此,hibernate使用这个字段创建了第三个表,该表具有用户id和权限角色。在存储库中,我使用了Hibernate JPARepository。使用findAll()我获得了所有用户。控制器:
在控制器中:
@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);
}
在职:
@Transactional(readOnly = true)
public Page<UserDTO> getAllManagedUsers(Pageable pageable) {
return userRepository.findAll(pageable).map(UserDTO::new);
}
在存储库中:
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Page<User> findAll(Pageable pageable);
}
我在存储库中尝试过这个:
@Query("select users from User users where users.authorities = 'ROLE_USER'")
Page<User> getAllByAuthoriy(Pageable pageable);
当局实体:
@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;
}
}
所以,现在我必须将查询从findAll更改为findAllByAuthorities(可分页、可分页、设置权限)。但这不起作用,显示类型转换错误。如何获取所有该用户,哪个角色是role_user?
这是解决方案,我必须编写一个查询来从用户表中获取用户,哪个权限是user_role。为此,我必须在HashSet中传递一个字符串来匹配。
@Query("select users from User users where 'ROLE_USER' member of users.authorities")
Page<User> getAllByAuthoriy(Pageable pageable);