我正在研究JPA规范,该规范必须根据我输入的内容进行选择。 我有实体部门,其中的字段 code 类似于 DB001 。.
@OneToMany(mappedBy = "department", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JsonIgnore
private Set<Employee> departments;
也员工
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "departmentId")
@JsonIgnore
private Department department;
还有我的员工测试主管
@GetMapping("/employee")
public List<Employee> getAllEmployee() {
final List<SearchData> searchDataList = new ArrayList<>();
searchDataList.add(new SearchData("name", "Ivan"));
searchDataList.add(new SearchData("code", "01"));
return employeeService.getDynamicEmployeeSearch(searchDataList);
}
当我在浏览器中打开它时,它对我说
Unable to locate Attribute with the the given name [name] on this ManagedType [com.mentor.jpa.dynamicquery.domain.Department]; nested exception is java.lang.IllegalArgumentException: Unable to locate Attribute with the the given name [name] on this ManagedType [com.mentor.jpa.dynamicquery.domain.Department]
我了解,该属性名称仅存在于 Employee 实体上,而并不存在于部门上,但是我需要使用两个标准进行选择,因此他们需要同时工作。 (当我尝试一个或多个不需要联接的条件时,它们会起作用!)
我应该在我的规格代码上进行哪些更改,以使连接正确工作。我在规格
处的代码@Override
public Predicate toPredicate(final Root<Employee> root, final CriteriaQuery<?> query,
final CriteriaBuilder criteriaBuilder) {
if (searchData != null) {
return criteriaBuilder.like(criteriaBuilder.lower(root
.join("department")
.get(searchData.getFieldName())
.as(String.class)),
"%" + searchData.getValue().toLowerCase() + "%");
}
return null;
}
P.S。类 SearchData 是带有
的简单pojoprivate String fieldName;
private String value;
还有我的员工服务方法
public List<Employee> getDynamicEmployeeSearch(List<SearchData> searchDataList) {
List<Employee> employeesList = new ArrayList<>();
Specification<Employee> specification = new EmployeeSpecification();
if (searchDataList != null) {
for (SearchData data : searchDataList) {
specification = Specification.where(specification).and(new EmployeeSpecification(data));
}
employeesList = employeeRepository.findAll(specification);
return employeesList;
}
return employeesList;
}
我需要返回名称为雇员的雇员(或我在SearchData中输入的部分,以及我在第二个SearchData中输入的部门代码,但是该代码在另一个具有OneToMany关系的表上
答案 0 :(得分:0)
已解决。 写到谓词并添加另一个谓词,当我现在有部门的标准时,它将选择部门,当员工的标准时,它将选择员工。 在列表中,我有正确的数据。只是以为这可能是默认值。