如何使用JDBI查询日期范围和日期是否可选?

时间:2016-04-14 21:58:21

标签: sql postgresql jdbi

我需要查询from和to日期之间的订单列表。两者都是可选的,如果没有提供,则应从WHERE子句中排除。我需要使用JDBI为Postgres实现此目的。

前:

如果仅提供日期,则查询应为:

SELECT id, total, date, country FROM orders WHERE order date >=:fromDate AND country =:country

如果仅提供日期,则查询应为:

SELECT id, total, date, country FROM orders WHERE order date <:toDate AND country =:country

如果未提供两个日期:

SELECT id, total, date, country FROM orders WHERE country =:country

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

JDBI没有什么特别的东西可以让你这么做。

您的选择是:

  1. 检查代码中是否有任何参数为null,并调用适当的DAO方法(对于所有可能的null / not null排列,你需要4个)

  2. 一些使用PostgreSQL CASE表达式的SQL,如下所示:

    SELECT id, total, date, country FROM orders 
    WHERE order_date >= (case when :fromDate is null then 0 else :fromDate end) 
    AND order_date <= (case when :toDate is null then current_date else :toDate end) 
    AND country =:country