我对规范、生成器、查询不是很有经验,我必须做一个相当复杂的查询,比如:
select * from table where
code in ('code1', 'code2' //codes) and
(
(
date between "2020-03-23 //from" and "2020-03-30 //to"
and
status in ('Status1' , 'Status2' //status)
)
or
(
date between "2021-03-23" and "2021-03-30"
and
status in ('Status3' , 'Status4')
)
)
我有一个这样的DTO:
public class SearchCriteria {
@Embedded
private Filters filters;
@Embeddable
@Getter
@Setter
public static class Filters {
private List<String> codes;
private List<TimePeriod> timePeriods;
}
@Embeddable
@Getter
@Setter
public static class TimePeriod {
private List<String> status;
private StartDate startDate;
}
@Embeddable
@Getter
@Setter
public static class StartDate {
private LocalDate from;
private LocalDate to;
}
这对我来说很难。我什么都试。我宁愿给你看一个具体的案例,以免引起误解。有人能帮我吗?我将不胜感激!
我不需要使用规范,我只需要能够重现那个查询示例,规范似乎是最好的选择。
谢谢大家。
我认为您走在了正确的轨道上,criteria类看起来不错。以下是如何在构建JPA标准的方法中使用它,并使用与您的实体对应的存储库执行查询:
public void query(List<String> codes, List<TimePeriod> timePeriods) {
// build the code filter
Specification<Table> codeSpec = (root, query, criteriaBuilder) -> {
Path<String> codeField = root.get("code");
var codePredicate = criteriaBuilder.in(codeField);
codes.forEach(code -> codePredicate.value(code));
return codePredicate;
};
// iterate over the time periods
var timePeriodSpec = timePeriods.stream().map(timePeriod -> {
Specification<Table> dateSpec = (root, query, criteriaBuilder) -> {
Path<LocalDate> dateField = root.get("date");
return criteriaBuilder.between(dateField, timePeriod.startDate.from, timePeriod.startDate.to);
};
Specification<Table> statusSpec = (root, query, criteriaBuilder) -> {
Path<String> statusField = root.get("status");
var statusPredicate = criteriaBuilder.in(statusField);
timePeriod.status.forEach(status -> statusPredicate.value(status));
return statusPredicate;
};
// combine the date and status filter
return dateSpec.and(statusSpec);
})
.reduce(Specification::or).get(); // chain the time period filters together
var fullSpec = codeSpec.and(timePeriodSpec);
var result = tableRepository.findAll(fullSpec, Pageable.unpaged());
}
您还需要确保您的存储库实现JpaSpecificationExecutor接口,但您可能已经明白了这一点。