【问题标题】:Spring+boot+data - query by Example having association return PageSpring+boot+data - 通过具有关联返回页面的示例查询
【发布时间】:2017-05-27 15:25:07
【问题描述】:

我有一个映射了 Job 实体的 Employee 实体类。在控制器中,我想返回所有具有给定职位描述的职位的员工。我怎么做?目前我的代码返回空列表。

这是我的代码

public class Employee {
  public int id;
  public String name;

  @ManyToOne()
  @JoinColumn(name="JOB_ID", referencedColumnName="JOB_ID")
  public Job job;
  ...
}
public class Job {
  public int jobId;
  public String desc; // job description
  ...
}

@Controller
public MyController {
  // I want to filter employees when given Job desc property

  @RequestMapping("/filter")
    public ModelAndView filterBy(
        @ModelAttribute("emp") Employee emp, 
    Pageable pageable, ModelMap model) {

        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", match -> match.startsWith().ignoreCase());

        Example<Employee> example = Example.of(emp, matcher);
        Page<Employee> employeePage = employeeRepository.findAll(emp, 
                new PageRequest(pageable.getPageNumber(), 
                pageable.getPageSize(), null));

        PageWrapper<Employee> page = new PageWrapper<Employee>(employeePage, "/employee");

        model.addAttribute("employee", empPage.getContent());
        model.addAttribute("page", page);

        return new ModelAndView("employeePage", model);
    }
}

感谢您的建议。

【问题讨论】:

  • 你有什么问题?
  • 我想查询给定 Job desc 属性的 Empoyee 表。我怎么做?目前我的代码返回空列表。
  • 您的代码根本不这样做。它按姓名查找员工。那么,你为什么要发布这个不相关的代码呢?使用 JPQL 查询怎么样:select e from Employee e where e.job.desc = :description
  • 干杯,但我想将结果作为页面类类型列表返回。不仅将所有数据加载到列表中,而且加载到块中。之所以这样做是因为我有分页器,所有这些都是spring数据支持的
  • 所以? Spring data JPA 支持分页查询。只需使用 @Query 注释您的方法,并为方法添加一个 Pageable 参数。

标签: java spring spring-boot spring-data query-by-example


【解决方案1】:

抱歉没有发表评论的声誉,所以将其发布为答案

正如@JB Nizet 建议的那样,在 JPA 存储库中的方法中添加一个 @Query,即employeeRepository

例如定义一个类似的方法(方法名可以是任何东西)

@Query(value = "select e from Employee e where e.job.desc = :desc")
Page<Employee> findByDesc(Pageable pageable, @Param("desc") String desc);

【讨论】:

  • 好的,谢谢@Dark。如果我查询返回 10 个项目的第二页,它实际上会起作用吗?
  • 另外,我认为这不灵活。如果我想同时查询 Employee 和 Job 实体的多个属性,这会导致查询很长。
【解决方案2】:

我已经解决了这个问题。示例查询运行良好,它只是实体属性之一不能为空,因此我必须添加以忽略它。

.withIgnorePaths("job.property") <-- ignore property which is not null

【讨论】:

    猜你喜欢
    • 2020-09-22
    • 2015-02-21
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 2023-03-15
    • 1970-01-01
    • 2017-01-25
    • 2020-04-02
    相关资源
    最近更新 更多