Spring Data JPA 忽略空参数

Mar*_*tin 5 java methods null spring-data-jpa spring-boot

假设我有以下 JPA 方法:

public List<FrequencyCode> findAllByNameContainingAndAllowExplicitDosingTimesEqualsOrderByName(String name, Boolean allowExplicitDosingTimes);
Run Code Online (Sandbox Code Playgroud)

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

在此处输入图片说明

在这种情况下,如果用户没有使用该字段进行搜索,则布尔值可以是 true、false 或 null。当我希望 JPA 忽略任何空值时,它看起来像是在实际搜索空值。我已经能够使用以下代码使这个组合搜索工作:

@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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

这是我在接受的答案的帮助下如何完成这项工作的:

FrequencyCode fc = new FrequencyCode();
    fc.setName(name);
    fc.setAllowExplicitDosingTimes(allowExplicitDosingTimes);

    ExampleMatcher matcher = ExampleMatcher.matching()
        .withMatcher("name", match -> match.contains())
        .withMatcher("allowExplicitDosingTimes", match -> match.exact())
        .withIgnorePaths("id", "uuid")
        .withIgnoreNullValues();
    Example<FrequencyCode> example = Example.of(fc, matcher);

    List<FrequencyCode> frequencyCodes = ((FrequencyCodeRepository) baseRepository).findAll(example);
Run Code Online (Sandbox Code Playgroud)

您必须告诉它忽略任何 ID 字段或您不打算搜索的任何其他字段,但这非常强大!

谢谢!

Saš*_*jak 3

你可以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);
}
Run Code Online (Sandbox Code Playgroud)