【发布时间】: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