java - Spring+boot+data - 通过具有关联返回页面的示例进行查询

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

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

这是我的代码

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);
    }
}

感谢您的建议。

最佳答案

抱歉,没有评论的声誉,因此将其作为答案发布

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

例如定义一个方法(方法名称可以是任何内容)

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

关于java - Spring+boot+data - 通过具有关联返回页面的示例进行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44218588/

相关文章:

java - 在java中使用selenium web驱动程序从div获取文本值

java - 猜数字游戏

java - 配置 Spring + Hibernate 事务管理器

java - 是否可以在 Spring Batch 中结合分区和并行步骤?

java - Spring Boot 中未找到映射

java - 为 DateTime 列更新 MySQL 中的结果集

java - 如何从 "Event"对象获取发生此事件的对象?

java - Spring Java 配置中的 Hibernate 3 sessionFactory

Spring Data Rest 异常处理 - 返回通用错误响应

spring-boot - 用于安全托管 zip 文件的 Azure 服务