我遇到一个问题,我希望使用一个查询而不是多个查询来显示多个结果。
假设一个表有50条记录和3列,可能不需要1列。当用户将其保留为空时,当用户给它一些值时,Query1将返回30条记录。Query2将返回15条记录。是否可以仅使用一个查询来实现?
控制器:
public Iterable<Number> getNumberRecords(@PathVariable String one, @PathVariable String two,
@RequestParam(value = "three", required = false) String three) {
if(three == null)
return numberRepository.findAllbyOneAndTwo(one,two);
else
return numberRepository.findAllbyOneAndTwoAndThree(one,two,three);
}
仓库:
@Repository
public interface NumberRepository extends CrudRepository<Number, Long>{
List<Number> findAllbyOneAndTwoAndThree(String one, String two, String three);
List<Number> findAllbyOneAndTwo(String one, String two);
}
我只希望在两种情况下都能满足并给出预期输出的查询。使用@Query(“”)的条件查询也可以。
最佳答案
要将我的评论转换为答案,应使用类似以下内容的内容:
public List<? extends Number> findAllByOneTwoAndThree(final String one,
final String two,
final @Nullable String three) {
final StringBuilder queryBuilder = new StringBuilder();
queryBuilder.append("SELECT x FROM some_table x")
.append(" WHERE x.one = :one")
.append(" AND x.two = :two");
if (three != null) {
// Only add to the query if three was NOT null.
queryBuilder.append(" AND x.three = :three");
}
// etc...
}