繁体   English   中英

Spring 引导 JPA CrudRepository 如何使可选搜索参数

[英]Spring Boot JPA CrudRepository how to make optional search parameters

对于下面的 class,我正在向存储库添加其他搜索方法,如何在 findByFields 方法中使搜索参数可选? 这种方法只有两个参数,但考虑一个有更多参数的场景。

一个示例场景是一个搜索表单页面,其中可能有 10 到 20 个搜索过滤器。 用户可以使用 0 到所有搜索参数的任意组合。

有没有办法使这些字段成为可选的,如果提供了 null 值,那么该字段将不会作为查询过滤器添加?

我知道我可以在方法中添加逻辑来说明 paramA 和 paramB 是否具有值,然后为该组合调用一个方法并为不同的组合调用另一个方法,但在我看来,这将是一个糟糕的解决方案。

有什么建议么? 能够在不添加手动查询语句的情况下执行此操作会很好。


import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface ReportMappingRepository extends CrudRepository<ReportMapping, Integer> {

    public ReportMapping findReportMappingByReportId(@Param("reportID") int reportId);

    public List<ReportMapping> findByFields(@Param("id")int id, @Param("reportID") int reportId);

}

我使用 JPA 规范解决了这个问题,感谢 Eklavya 为我指明了正确的方向。

更改了存储库以扩展 JpaSpecificationExecutor。

import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;

public interface ReportMappingRepository extends CrudRepository<ReportMapping, Integer>, JpaSpecificationExecutor<ReportMapping> {

}

创建搜索条件和搜索操作类,然后像这样执行查询。

    // Build up Search Criteria Specification
    // Id
    ReportMappingSpecification searchSpec = new ReportMappingSpecification();
    if (queryForm.getId() != null && queryForm.getId().length() > 0) {
        searchSpec.add(new SearchCriteria("id", queryForm.getId(), SearchOperation.EQUAL));
    }
    // reportId
    if (queryForm.getReportId() != null && queryForm.getReportId().length() > 0 && !queryForm.getReportId().equalsIgnoreCase("0")) {
        searchSpec.add(new SearchCriteria("reportId", queryForm.getReportId(), SearchOperation.EQUAL));
    }

    // Run search
    reportMappingRepo.findAll(searchSpec).forEach(reportMappings::add);

希望这对其他人有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM