Spring Data - 如果参数为空,则忽略该参数值

78

我希望创建一个Spring Data存储库接口,它需要两个参数。有没有办法使它具有以下行为?

MyObject findByParameterOneAndParameterTwo( String parameterOne, String parameterTwo);
如果两个参数都有值,我希望它能够正常工作并对这两个值执行“AND”操作。
如果例如第二个参数为null,则仅通过ParameterOne进行搜索。
有什么建议吗?

3
Spring Data提供的从存储库方法名称中获取查询的机制是为了在查询事先已知的情况下使用。但是,希望这种机制用于只在运行时准确知道查询的情况是不现实的。对于动态情况,有几个其他选项,例如@Query和QueryDSL。SQL和JPA支持COALESCE函数,该函数可用于解决某些参数可能具有NULL值的情况。应该可以使用@Query("SELECT e FROM MyObject e WHERE COALESCE(e.parameterOne, ?1) = ?1 AND COALESCE(e.parameterOne, ?2) = ?2")来解决问题。 - manish
2
@manish 我认为 COALESCE(?1, e.parameterOne) = e.parameterOne 是你的意图。 - Blank
@Forward,我只是给发帖人指明了方向,因为我不确定发帖人想要匹配的具体方式。例如,尚未指定数据库是否可以包含这些列的“null”值,如果可以,匹配应该如何进行等等。但是,是的,仅基于已发布的内容,您的评论是正确的。 - manish
@manish COALESCE函数将返回第一个非空值,那么如果我们有不同的情况呢? - Rishabh Agarwal
1
可以使用JpaRepository和Specification,如此处所述https://dev59.com/410a5IYBdhLWcg3wipFA#61948111,它允许您使用构建器处理此问题。 - ganaraj
显示剩余3条评论
14个回答

0

我在Spring/JPA领域还是新手,

使用'Query By Example'

我正在使用(在serviceImp中),以下所有参数都是可选的/取决于用户选择

`
  .
    if (!firstName.isEmpty() ) {
    staff.setFirstName(firstName);
    }



    if (!lastName.isEmpty() ) {
    staff.setLastName(lastName);
    }

    if (!ptAadhar.isEmpty() ) {
        patient.setPtAadhar(ptAadhar);
    }

    if (!Cell.isEmpty() ) {
        staff.setCell(Cell);
    }


      Example<StaffEntity> example = Example.of(staff);  

      List<StaffEntity> staffList =staffRepository.findAll(example);
       .

0
如果参数之间存在或条件,则以下是一个适用于我的示例。
@Query(value = "select distinct P from PostEntity P where (P.community.id = :communityId or P.communityParentCategory.id in :parentCats or P.communityCategory.id in :cats or (:countryId is not null and P.country.id=:countryId) or (:stateId is not null and P.state.id=:stateId) or (:districtId is not null and P.district.id=:districtId)) and (:postType is null or P.postType = :postType) and (:isNotice is null or P.isNotice = :isNotice) and (:isReported is null or P.isReported = :isReported) and (:isInternalPost is null or P.isInternalPost = :isInternalPost)  and P.parent.id is null and P.status = :postStatus order by P.createdDate desc")
Page<PostEntity> getCommunityPosts(int communityId, Pageable pageable, PostType postType, PostStatus postStatus, Boolean isNotice, Boolean isReported, Boolean isInternalPost, Set<Long> cats, Set<Long> parentCats, Long countryId, Long stateId, Long districtId);

这个条件 (:stateId 不为空且 P.state.id=:stateId) 或者 (:districtId 不为空且 P.district.id=:districtId)) 在这种情况下评估得非常好。

-2
你也可以这样做。
代码库:
`MyObject findByParameterOneAndParameterTwo( String parameterOne, String parameterTwo);`

如果您传递了一个空的parameterTwo参数,生成的JPQL将包括IS NULL条件:
`myobject0_.parameterTwo is null`

例如:repository.findByParameterOneAndParameterTwo("D", null);

参考:https://www.baeldung.com/spring-data-jpa-null-parameters#query-methods


-4

我不确定是否可以将Repo用作单独的类,但您可以使用带有选项参数的StringBuilder append查询。这肯定会起作用。

 StringBuilder queryBuilder = new StringBuilder();
    queryBuilder.append("select p.name from personDemographic p "); 
    Boolean flag = true;
    if(parameterOne != null){
      if(flag){
          queryBuilder.append("where condition...");
            flag=false;
        } 
      }
    if(parameterOne != null){
    if(flag){
     queryBuilder.append("where condition...");
     flag = false;
    }else{
      queryBuilder.append("and condition...");
    }
   Query query = entityManager.createQuery(queryBuilder.toString());

6
这会导致 SQL 注入攻击的可能性。 - Kamil

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接