【发布时间】:2019-09-01 11:19:45
【问题描述】:
我有 2 张桌子(人员和技能);它们之间存在多对多的关系。
这是来自个人实体:
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.LAZY)
@JoinTable(name = "person_skill",
joinColumns = @JoinColumn(name = "person_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "skill_id", referencedColumnName = "id"))
private Set<Skill> skills;
这来自技能:
@JsonBackReference
@ManyToMany(mappedBy = "skills")
private Set<Person> persons;
我尝试进行查询,您可以通过许多参数找到一个人,但所有参数都应该是可选的。所以我创建了一些规范:
public static Specification<Person> firstNameContains(String firstName) {
return (person, cq, cb) -> cb.like(person.get("firstName"), "%" + firstName + "%");
}
public static Specification<Person> isStudent(Boolean isStudent) {
return (person, cq, cb) -> cb.equal(person.get("isStudent"), isStudent);
}
我已经在服务中创建了这个函数:
@Override
public Page<Person> findByParams(Long id,
String firstName,
String lastName,
Boolean isStudent,
Boolean isActive,
String email,
String phone,
Set<Long> skills,
Pageable pageable) {
List<Specification> specifications = new ArrayList<>();
if(firstName != null){
specifications.add(PersonSpecifications.firstNameContains(firstName));
}
if (isStudent != null){
specifications.add(PersonSpecifications.isStudent(isStudent));
}
if (skills != null){
specifications.add(PersonSpecifications.hasSkills(skills));
}
Optional<Specification> spec = specifications.stream().reduce((s, acc) -> acc.and(s));
if(spec.isPresent()) {
return personRepository.findAll(spec.get(), pageable);
}
return personRepository.findAll(pageable);
}
在控制器中被这个函数调用:
@GetMapping(FIND)
Page<Person> findByParams(@RequestParam(value = "id", required = false) Long id,
@RequestParam(value = "firstName", required = false) String firstName,
@RequestParam(value = "lastName", required = false) String lastName,
@RequestParam(value = "isStudent", required = false) Boolean isStudent,
@RequestParam(value = "isActive", required = false) Boolean isActive,
@RequestParam(value = "email", required = false) String email,
@RequestParam(value = "phone", required = false) String phone,
@RequestParam(value = "skills", required = false) Set<Long> skills,
Pageable pageable) {
return personService.findByParams(id, firstName, lastName, isStudent, isActive, email, phone, skills, pageable);
}
我的问题是 hasSkills 规范应该如何工作。
【问题讨论】:
标签: java spring-boot criteria-api