简体   繁体   中英

Spring Data (Hibernate) dynamic WHERE clause

I have a repository like this

@Repository
public interface LeadRequestRepository extends PagingAndSortingRepository<LeadRequest, UUID> {

    @Query(value = "SELECT * FROM lead_request WHERE product IN :products AND current_status in :status", nativeQuery = true)
    List<LeadRequest> findLeadRequests(@Param("products") List<String> products, @Param("status") List<String> status);

}

In this query, the status can be null or empty list.
In such case, the query must returns all status (NEW, APPROVED, REJECTED, etc). In other words, the query must become SELECT * FROM lead_request WHERE product IN :products and no status clause.
I'm also confused because I use IN clause, so I can't use JPA Example API

How can I achieve this using hibernate and jpa?

There are two options:

  1. You would have two JPQL/native queries and based on null condition you would call one or the other query.
  2. Better option is to use JPA criterial queries. Spring Data JPA provides abstraction for JPA criteria queries called Specifications . Take a look into Spring Data JPA docs here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM