Search code examples
javaspringspring-boothibernatejpql

Spring Boot JPA Native Query - is not null check based on parameter


In Spring boot JPA native query how can we add a dynamic check if a column value can be null or not based on the parameter. For example, in the below scenario if isEmailNullAllowed is true than the 'email' column can be null else it has to be not null.

@Query(value = "select * from users where user_id=:userId and email is not null")
List<User> findByName(@Param("userId") String userId,
                      @Param("isEmailNull") Boolean isEmailNullAllowed);

Solution

  • Just or:

    @Query(value = "select * from users where user_id=:userId and (:isEmailNull = true or email is not null)")
    List<User> findByName(@Param("userId") String userId,
                          @Param("isEmailNull") Boolean isEmailNullAllowed);