[英]Spring Data Jpa - The type Specifications<T> is deprecated
我正在實現鏈接中的邏輯: Spring Data - Multi-column search where I want to search by FirstName
。
根據鏈接: https : //docs.spring.io/spring-data/jpa/docs/current/api/org/springframework/data/jpa/domain/Specifications.html
員工規范.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)));
}
}
錯誤:
此行的多個標記 - 類型規范中的方法 where(Specification) 不適用於參數 (Specification) - 不推薦使用類型規范
您的 repo 代碼需要像這樣擴展JpaSpecificationExecutor
:
public interface EmployeeRepository extends JpaRepository<Employee, Long>,
JpaSpecificationExecutor<Employee> {
}
JpaSpecicationExecutor 具有可以調用的方法:
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)
);
}
我將您的規范更改為使用 lambdas:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.