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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43780226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:24:37  来源:igfitidea点击:

Spring Data - ignore parameter if it has a null value

springspring-bootspring-data

提问by Panos

I want to have a spring data repository interface that takes two parameters. Is there a way to make it have the following behaviour?

我想要一个带有两个参数的 spring 数据存储库接口。有没有办法让它具有以下行为?

MyObject findByParameterOneAndParameterTwo( String parameterOne, String parameterTwo);

If both parameters have a value, I would like it to behave normally and do an "AND" for both values.

如果两个参数都有一个值,我希望它正常运行并对两个值执行“AND”。

If for example the second parameter is null, then it would search only by ParameterOne

例如,如果第二个参数为空,则它将仅通过 ParameterOne 进行搜索

Any suggestions?

有什么建议?

回答by Kadzhaev Marat

I'm not sure it is possible with repository methods naming but you can use @Querylike

我不确定存储库方法命名是否可行,但您可以使用@Query类似

(:parameterOne is null or parameter1 = :parameterOne) and (:parameterTwo is null or parameter2 = :parameterTwo)

回答by Abdullah Khan

Currently this is not possible in Spring-data-jpa.

目前这在Spring-data-jpa.

There is a JIRAticketregarding this which is still under investigationby the Springteam.

有一JIRA关于这个目前仍在调查Spring团队。

enter image description here

在此处输入图片说明

However if you want a workaround you can checkout a simple criteria queryexample.

但是,如果您想要一个解决方法,您可以查看一个简单的标准查询示例。

回答by Dovmo

One solution that's missing here is Spring Data JPA's Query By Examplefeature and leverage the ExampleMatcher#ignoreNullValues, which is built exactly to solve this problem. A custom query and query builder are notnecessary.

这里缺少的一个解决方案是 Spring Data JPA 的Query By Example功能并利用ExampleMatcher#ignoreNullValues,它正是为解决这个问题而构建的。自定义查询和查询构建器都没有必要。

This Spring Data query:

这个 Spring Data 查询:

ExampleMatcher matcher = ExampleMatcher.matching().withIgnoreNullValues();
Example<MyObject> exampleQuery = Example.of(new MyObject("foo", null), matcher);
List<MyObject> results = repository.findAll(exampleQuery);

Yields a query that looks like:

产生如下所示的查询:

select * 
from myObject 
where parameter1 = "foo"

While the following:

而以下:

ExampleMatcher matcher = ExampleMatcher.matching().withIgnoreNullValues();
Example<MyObject> exampleQuery = Example.of(new MyObject("foo", "bar"), matcher);
List<MyObject> results = repository.findAll(exampleQuery);

Yields:

产量:

select * 
from myObject 
where parameter1 = "foo"
and parameter2 = "bar"

Very cool!

很酷!

Note: One thing you'll have to do to your Repositoryinterface is add the QueryByExampleinterface. You can do this either by extending the QueryByExampleinterface directly, or implicity via the JpaRepository:

注意:您必须对Repository界面做的一件事是添加QueryByExample界面。您可以通过QueryByExample直接扩展接口或通过以下方式隐式扩展JpaRepository

public interface MyObjectRepository extends JpaRepository<MyObject, Long> {}

回答by Sergey Grigorchuk

Try this Kolobok

试试这个Kolobok

@FindWithOptionalParams
Iterable<MyObject> findByParameterOneAndParameterTwo( String parameterOne, String parameterTwo);

回答by M Singh

I am new in Spring/JPA space,

我是 Spring/JPA 领域的新手,

use 'Query By Example'

使用“按示例查询”

i am using (in seviceImp) , all below arguments are optional/ depends on user choice

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

`
  .
    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);
       .

回答by Sana

Try this one,

试试这个,

      @Query(value = "SELECT pr FROM ABCTable pr " +
        "WHERE((pr.parameterOne = :parameterOne) or (pr.parameterOne = null and :parameterOne = null)) and 
        ((pr.parameterTwo = :parameterTwo) or (pr.parameterTwo = null and :parameterTwo = null)) ")
      List<PaymentRequest> getSomething (@Param("parameterOne") String parameterOne,
                                             @Param("parameterTwo") String parameterTwo);

回答by Matheus Almeida

You could do that too.

你也可以这样做。

Repository:

存储库:

`MyObject findByParameterOneAndParameterTwo( String parameterOne, String parameterTwo);`

if you pass a null parameterTwo, the generated JPQL will include the IS NULL condition:

如果传递空参数二,生成的 JPQL 将包含 IS NULL 条件:

`myobject0_.parameterTwo is null`

Ex: repository.findByParameterOneAndParameterTwo("D", null);

前任: repository.findByParameterOneAndParameterTwo("D", null);

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

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

回答by Rishabh Agarwal

I am not sure if its possible using Repo as a separate class but you can use StringBuilder append query with option parameter. This will definitely work

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

 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());