簡體   English   中英

Spring Data JPA忽略null參數

[英]Spring Data JPA ignore null parameter

說我有以下JPA方法:

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

用戶使用輸入字段和選擇字段過濾這些對象的列表來調用此方法:

在此輸入圖像描述

在這種情況下,如果用戶沒有使用該字段進行搜索,則布爾值可以為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;
}

這很有效,但很明顯,在一個包含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);

你必須告訴它忽略任何ID字段或者你不打算搜索的任何其他字段,但這是無比強大的!

謝謝!

您可以使用這樣的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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM