我正在实现链接Spring Data - Multi-column searches的逻辑,在这里我希望通过FirstName
进行搜索。
EmployeeSpecification.java
public class EmployeeSpecification {
public static Specification<Employee> textInAllColumns(String text) {
if (!text.contains("%")) {
text = "%" + text + "%";
}
final String finalText = text;
return new Specification<Employee>() {
@Override
public Predicate toPredicate(Root<Employee> root, CriteriaQuery<Employee> cq, CriteriaBuilder builder) {
return builder.or(root.getModel().getDeclaredSingularAttributes().stream().filter(a -> {
if (a.getJavaType().getSimpleName().equalsIgnoreCase("string")) {
return true;
} else {
return false;
}
}).map(a -> builder.like(root.get(a.getName()), finalText)).toArray(Predicate[]::new));
}
};
}
}
EmployeeRepository.java
public interface EmployeeRepository extends JpaRepository<Employee, Long>{
List<Employee> findAll(Specification<Employee> spec);
}
EmployeeServiceImpl.java
@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeRepository employeeRepository;
@Override
public void findAllCustomersByFirstName(String firstName) {
employeeRepository.findAll(Specifications.where(EmployeeSpecification.textInAllColumns(firstName)));
}
}
错误:
此行有多个标记 -规范类型中的方法(规范)不适用于自变量 (规格) -规格类型已弃用
答案 0 :(得分:1)
您的存储库代码需要像这样扩展JpaSpecificationExecutor
:
public interface EmployeeRepository extends JpaRepository<Employee, Long>,
JpaSpecificationExecutor<Employee> {
}
JpaSpeficationExecutor具有可以调用的那些方法:
public interface JpaSpecificationExecutor<T> {
Optional<T> findOne(@Nullable Specification<T> var1);
List<T> findAll(@Nullable Specification<T> var1);
Page<T> findAll(@Nullable Specification<T> var1, Pageable var2);
List<T> findAll(@Nullable Specification<T> var1, Sort var2);
long count(@Nullable Specification<T> var1);
}
那么您可以做:
public void findAllCustomersByFirstName(String firstName) {
employeeRepository.findAll(
EmployeeSpecification.textInAllColumns(firstName)
);
}
我将您的规范更改为使用lambda:
public class EmployeeSpecification {
public static Specification<Employee> textInAllColumns(String text) {
if (!text.contains("%")) {
text = "%" + text + "%";
}
final String finalText = text;
return (Specification<Employee>) (root, query, builder) ->
builder.or(root.getModel().getDeclaredSingularAttributes().stream().filter(a -> {
if (a.getJavaType().getSimpleName().equalsIgnoreCase("string")) {
return true;
} else {
return false;
}
}).map(a -> builder.like(root.get(a.getName()), finalText)).toArray(Predicate[]::new));
}
}
您可以在此处查看答案中包含的代码的更新版本:https://github.com/zifnab87/spring-boot-rest-api-helpers/blob/26501c1d6afcd6afa8ea43c121898db85b4e5dbe/src/main/java/springboot/rest/specifications/CustomSpecifications.java#L172