我正在尝试按特定角色过滤jhipster中的用户。该过滤器是否会出现在UserService类中,本质上是一个getNonAdminUsers方法?默认情况下,UserService调用getAllManagedUsers,它基本上返回除我之外的每个用户。这很好,但我的目标是返回不是ROLE_ADMIN用户的所有人。这是现有的“核心”。
@Transactional(readOnly = true)
public Page<UserDTO> getAllManagedUsers(Pageable pageable) {
return userRepository.findAllByLoginNot(pageable,Constants.ANONYMOUS_USER).map(UserDTO::new); }
我不认为这是最好的方法
@Transactional(readOnly = true)
public Page<UserDTO> getAllManagedUsers(Pageable pageable) {
Optional<User> userOnline = getUserWithAuthoritiesByLogin(SecurityUtils.getCurrentUserLogin().get());
Page<UserDTO> userRepo = userRepository.findAllByLoginNot(pageable, Constants.ANONYMOUS_USER).map(UserDTO::new);
if(userOnline.get().getId() < 4)
{
return userRepo;
}else {
List<UserDTO> userList = new ArrayList<UserDTO>();
userList.addAll(userRepo.getContent());
Predicate<UserDTO> predicate = p-> p.getId() < 4;
userList.removeIf(predicate);
return new PageImpl<UserDTO>(userList, new PageRequest(pageable.getPageNumber(), pageable.getPageSize()),userList.size());
}
}
它可以使用Specification(org.springframework.data.jpa.domain.Specification)实现;
首先在UserRepository中添加新方法签名
Page<User> findAll(Specification<User> where, Pageable pageable);
然后在你UserService添加规范:
static Specification<User> isNotAdmin(Authority role) {
return (obj, cq, cb) -> cb.isNotMember(role, obj.get("authorities"));
}
然后修改您的方法以按要排除的角色进行过滤:
@Transactional(readOnly = true)
public Page<UserDTO> getAllManagedUsers(Pageable pageable) {
Authority admin = authorityRepository.findById(AuthoritiesConstants.ADMIN).get();
return userRepository.findAll(Specification.where(isNotAdmin(admin)), pageable).map(UserDTO::new);
}