Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA Query to handle NULL parameter value

Tags:

jpa

I am new to JPA here is one of my query and i have couple of parameters as part of query and any parameter can be null value

@Query(value = "SELECT ord.purchaseOrderNumber,ord.salesOrderNumber,ord.quoteNumber"

            + " FROM Order ord WHERE ord.purchaseOrderNumber LIKE :poNumber%  "
            + " AND ord.salesOrderNumber LIKE :soNumber "
            + " AND ord.quoteNumber = :quoteNumber "

example in the above if my input parameter :quoteNumber is NULL then i shouldn't filter by ord.quoteNumber = NULL, so how do avoid this

like image 715
gnanesh Avatar asked Feb 17 '15 04:02

gnanesh


People also ask

Does JPA return null or empty list?

The normal behavior is indeed returning an empty list if no results are found. If a List<Object> is the return value of the method in the defined interface, the method should never return Null . The problem is that a parameter is given to the method and is not used anywhere in the Query.

Is empty in JPA query?

The IS EMPTY operator is the logical equivalent of IS NULL, but for collections. Queries can use IS EMPTY operator or IS NOT EMPTY to check whether a collection association path resolves to an empty collection or has at least one value.

What is JPA coalesce?

Coalesce is supported by JPA 2.0 API. The new construct is proprietary to Hibernate, not necessarily supported in all JPA implementations. First try the query without also trying to construct an object: select COALESCE(k.projectId,'N') as projectId, k.projectName from Emp o inner join o.projects k.


Video Answer


1 Answers

You could add a set of conditions to "ignore" properties with null values or empty strings.

e.g.

+ " AND (ord.quoteNumber = :quoteNumber or :quoteNumber is null or :quoteNumber = '' ")
like image 190
ccamcmxc Avatar answered Sep 23 '22 06:09

ccamcmxc