Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip @Param in @Query if is null or empty in Spring Data JPA

@Query(value = "Select f from Documents f " +
        "RIGHT JOIN f.documentStatus ds " +
        "where f.billingAccount.accountId  in :billingAccountIdList " +
        " and ds.statusCode in :paymentStatuses" +
        " and f.paymentDate < :paymentDate")
List<FinancialDocumentEntity> getFinancialDocumentsOverdue(@Param("billingAccountIdList")List<String> billingAccountIdList,
                                                           @Param("paymentStatuses") List<String> paymentStatuses,
                                                           @Param("paymentDate") Date paymentDate);

I have query like above. It is possible to skip searching param for example @Param("paymentStatuses") in query method if is null or is empty ?

like image 519
luafanti Avatar asked Oct 17 '17 12:10

luafanti


People also ask

How do I ignore null values in JPA?

You can ignore null fields at the class level by using @JsonInclude(Include. NON_NULL) to only include non-null fields, thus excluding any attribute whose value is null. You can also use the same annotation at the field level to instruct Jackson to ignore that field while converting Java object to json if it's null.

How does JPA handle null values?

The JPA specification defines that during ordering, NULL values shall be handled in the same way as determined by the SQL standard. The standard specifies that all null values shall be returned before or after all non-null values. It's up to the database to pick one of the two options.

Which annotation in JPA specifies whether the entity field can be null or not?

@Basic annotation's optional attribute defines whether the entity field can be null or not; on the other hand, @Column annotation's nullable attribute specifies whether the corresponding database column can be null.

Is it possible to define a sort type in @query annotation using Spring JPA?

Spring Data JPA allows you to add a Sort parameter to your query method. The Sort class is only a specification that provides sorting options for database queries. With dynamic sorting, you can choose the sorting column and direction at runtime to sort the query results.


1 Answers

Try changing

" and ds.statusCode in :paymentStatuses"

into

" and (:paymentStatuses is null or ds.statusCode in :paymentStatuses)"
like image 174
Predrag Maric Avatar answered Nov 14 '22 22:11

Predrag Maric