简体   繁体   中英

Springboot dynamic query with optional parameters

In the below I can have the modifedDate as null some times. at that time it is throwing error as "could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet"

How can I get data even the modifiedDate is null. Some time the date will be coming. How do this ?

I want the below Query method return data always

  1. return based on adminStatus if modifiedDate is null.
  2. return based on adminStatus and modifiedDate. if modifiedDate is not null.

we can do by building a dynamic query and executing with entity Manager. but I want with repository.

@Repository
public interface AdminRepository extends JpaRepository<AdminEntity, Long> {

@Query(
     value="SELECT * from admin_entity where status=:adminStatus and modified_tsz>=:modifedDate:", 
    nativeQuery=true)
  List<AdminEntity> getAdmins(String adminStatus, Date modifedDate)
}


Try this

@Repository
public interface AdminRepository extends JpaRepository<AdminEntity, Long> {

@Query(
     value="SELECT * from admin_entity where status=:adminStatus
           AND  (modified_tsz>=:modifedDate OR :modifedDate is null)", 
    nativeQuery=true)
  List<AdminEntity> getAdmins(String adminStatus, Date modifedDate)
}

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