我希望通过Spring Boot中的分页用户找到Job。
当我为所有用户检索所有作业时,它可以正常工作
public List<Job> findAll(Pageable pageable) {
List<Job> jobs = new ArrayList<>();
for (Job job : paginatedJobRepository.findAll(pageable)) {
jobs.add(job);
}
return jobs;
}
当我尝试通过已分页的用户检索所有作业时,它不能正常工作。我这样做是
public List<Job> findJobByCompany(Pageable pageable) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User user = userService.findByUsername(authentication.getName());
Company userCompany = companyService.findCompany(user);
List<Job> jobs = new ArrayList<>();
for (Job job : paginatedJobRepository.findAll(pageable)) {
if (job.getCompany().getId() == userCompany.getId()) {
jobs.add(job);
}
}
return jobs;
}
答案 0 :(得分:1)
首先检索所有公司,然后过滤不必要的结果,并为您提供错误的分页值。而是在JobRepository中定义一个方法,如下所示
Page<Job> findByCompany_id(long companyId, Pageable pageable);
此方法将创建此类
的查询select j.* from Job j, Company c where j.companyId = c.id
它还会检索此查询的count
,以便您获得正确的分页结果。
答案 1 :(得分:0)
您可以使用查询定义自定义方法。像这样的东西
public interface JobRepository extends JpaRepository<Job, Long> {
@Query(value = "SELECT * FROM Job j join Company c WHERE c.id= ?1",
countQuery = "SELECT count(*) FROM jobs j join Company c WHERE c.id= ?1",
nativeQuery = false)
Page<User> findByCompanyId(Long companyId, Pageable pageable);
}
答案 2 :(得分:0)
现在效果非常好。
存储库
Page<Job> findJobsByCompanyId(Long id, Pageable pageable);
服务
public List<Job> findJobByCompany(Pageable pageable) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User user = userService.findByUsername(authentication.getName());
Company userCompany = companyService.findCompany(user);
List<Job> jobs = new ArrayList<>();
for (Job job : paginatedJobRepository.findJobsByCompanyId(userCompany.getId(),pageable)) {
jobs.add(job);
}
return jobs;
}