jpa|springboot|informix自定义SQL,条件判断

jpa连mysql没什么说的,但是jpa连informix真的坑到家了。各种函数不支持。
需求:在自定义sql的时候,需要判断参数是否为空,如果参数为空则不参与sql条件判断。
就这么简单的一个需求,如果是jpa连mysql,那就用几个if判断就完事了,但是,informix不行。要用case when then else end。目前我只找到这个方法,后续有其他方法再更新,也欢迎大家提供其他方式。下面给出一个示例

jpa连mysql时:

@Query(value = "SELECT\n" +
            "name, \n" +
            "home \n" +
            "FROM\n" +
            "USER \n" +
            "WHERE\n" +
            " 1 = 1 \n" +
            "and IF(:#{#req.name} is not null and :#{#req.name} != '',name = :#{#req.name},1=1)\n"+
            "and IF(:#{#req.home} is not null and :#{#req.home} != '',home = :#{#req.home},1=1)\n", countProjection = "id", nativeQuery = true)
    Page<Map<String, Object>> listByPage(@Param("req") UserQueryRequest request, Pageable pageable);

jpa连informix时:

@Query(value = "SELECT\n" +
            "name, \n" +
            "home \n" +
            "FROM\n" +
            "USER \n" +
            "WHERE\n" +
            " 1 = 1 \n" +
            " and (case when :#{#req.name} is not null and :#{#req.name} != '' then name else '1' end) = \n"+
            " (case when :#{#req.name} is not null and :#{#req.name} != '' then :#{#req.name} else '1' end) \n"+
            " and (case when :#{#req.home} is not null and :#{#req.home} != '' then home else '1' end) = \n"+
            " (case when :#{#req.home} is not null and :#{#req.home} != '' then :#{#req.home} else '1' end) \n"+
            " and (case when :#{#req.createTime} is not null then to_char(create_time,'%Y-%m-%d') else '1' end) = \n"+
            " (case when :#{#req.createTime} is not null then to_char(:#{#req.createTime},'%Y-%m-%d') else '1' end) \n",
            countProjection = "id", nativeQuery = true)
    Page<Map<String, Object>> listByPage(@Param("req") UserQueryRequest request, Pageable pageable);

注意很多细节:
1.informix里面case when (断言) then (列|值) else (列|值) end
我是用两组case when来组合判断的(这是我想到的办法,欢迎大家提供其他办法)
2.很多时候需要把case when 里面的(列|值)转成字符串比较才行,不然要报错,比如我这里是’1’ = ‘1’。如果直接是1=1会报错。
3.在时间比较的时候需要将(列|值)都转成字符串比较,不然会报错。比如我这里用到的是:to_char(create_time,‘%Y-%m-%d’) = to_char(:#{#req.createTime},‘%Y-%m-%d’)
4.在自定义sql的时候注意空格

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值