Spring Data JPA忽略null参数

时间:2019-02-08 14:27:26

标签: java spring-boot methods null spring-data-jpa

说我有以下JPA方法:

aggregate(Value ~ Gene, subset(df, Value > 0), min)
#    Gene Value
#1    A    10
#2    B     3
#3    C     1
#4    D     4

用户通过输入字段和选择字段过滤这些对象的列表来调用此方法:

enter image description here

在这种情况下,如果用户不使用该字段进行搜索,则布尔值可以为true,false或null。当我希望它忽略任何空值时,JPA似乎正在实际搜索空值。我已经可以使用以下代码进行组合搜索:

public List<FrequencyCode> findAllByNameContainingAndAllowExplicitDosingTimesEqualsOrderByName(String name, Boolean allowExplicitDosingTimes);

这有效,但是显然,在具有8个搜索选项的页面上,这将成为一场噩梦。 String参数没有此问题,因为当用户不选择过滤器时,它们实际上是一个空String。这与Containing关键字配对,任何值都包含“”,因此它的行为就像忽略了该参数一样,这正是我对其他类型想要的。 JPA findAll ...()方法是否可以简单地忽略空参数?

******解决方案******

这是我在公认的答案的帮助下完成这项工作的方式:

@Override
public List<FrequencyCode> findAllWithFilters(String name, Boolean allowExplicitDosingTimes) 
{
    if (allowExplicitDosingTimes == null)
    {
        return ((FrequencyCodeRepository) baseRepository).findAllByNameContainingOrderByName(name);
    }
    else if (allowExplicitDosingTimes == true)
    {
        return ((FrequencyCodeRepository) baseRepository).findAllByNameContainingAndAllowExplicitDosingTimesTrueOrderByName(name);
    }
    else if (allowExplicitDosingTimes == false)
    {
        return ((FrequencyCodeRepository) baseRepository).findAllByNameContainingAndAllowExplicitDosingTimesFalseOrderByName(name);
    }

    return null;
}

您必须告诉它忽略任何ID字段或实际上不打算使用其搜索的任何其他字段,但这确实功能强大!

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以像这样使用Example

@Override
public List<FrequencyCode> findAllWithFilters(String name, Boolean allowExplicitDosingTimes) {

  FrequencyCode fc = new FrequencyCode();         
  //I assume that you have setters like bellow                 
  fc.setName(name);
  fc.setAllowExplicitDosingTimes(allowExplicitDosingTimes);                           

  ExampleMatcher matcher = ExampleMatcher.matching().withIgnoreNullValues();                        

  Example<FrequencyCode> example = Example.of(fc, matcher);

  return ((FrequencyCodeRepository) baseRepository).findAll(example);
}