Home > OS >  Ignoring condition if the parameter is null in Spring Data JPA
Ignoring condition if the parameter is null in Spring Data JPA

Time:10-17

I am currently developing the search and filtering feature of my project. I am trying to retrieve data with this Request body:

{
    "researchers": [
        "Jhon Doe"
    ],
    "unit": null,
    "agency":null,
    "date": null,
    "status": null,
    "budget": null
}

and below is the method from the ReasearchRepository that retrieves this data:


    @Query("select r from Research r "  
            "left join r.fundingAgencies fundingAgencies "  
            "left join r.researchers researchers "  
            "where (:budgetStart is null or :budgetEnd is null or  r.budget between :budgetStart and :budgetEnd )"  
            "and (:startDate is null or r.startDate >= :startDate) "  
            "and (:endDate is null or r.endDate <= :endDate) "  
            "and (:agencyNames is null or fundingAgencies.agencyName in :agencyNames) "  
            "and (:unitNames is null or r.deliveryUnit.unitName in :unitNames )"  
            "and (:names is null or researchers.name in :names ) "  
            "and (:researchStatuses is null or r.researchStatus in :researchStatuses)")
    List<Research> findAdvanced( @Param("budgetStart") Double budgetStart,
                                 @Param("budgetEnd")  Double budgetEnd,
                                 @Param("startDate")  LocalDate startDate,
                                 @Param("endDate") LocalDate endDate,
                                 @Param("agencyNames") Collection<String> agencyNames,
                                 @Param("unitNames") Collection<String> unitNames,
                                 @Param("names") Collection<String> names,
                                 @Param("researchStatuses") Collection<ResearchStatus> researchStatuses);

My problem is when I'm trying to find data from given values in the request, it returns an empty list [] even though it exists in the database. What I want to achieve is that if the parameter is null, it will ignore a specific condition in the query and will still return data.

I just followed the article from Baeldung.

I also find another article about using Criteria API, but it will take a lot of time for me to understand that. My project is a bit rush.

TIA

CodePudding user response:

I seems like a good case to use Specifications.

https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/

  • Related