MyBatis动态SQL解决字段值包含空值问题

学习目标:

MyBatis动态SQL解决字段值包含空值问题,使用数据库为Oracle

需求:

前端给字段传多个值时,其中包含空值,后端查询时应查询出字段为NULL的数据

字段空值数组写法的问题

前端给字段传多选值,要求包含空值,如果前端传 ’ ',存储到数据库里字段值为空字符串,如果用List 的数组入参查询时,查询条件为
status in (‘SUCCESS’, ’ '),不能查询 status is null的数据

private List<String> statusList;

<if test="statusList!= null and statusList.size() > 0">
and statusList in
	<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
    	#{item}
    </foreach>
</if>

字段空值字符串写法

前端对字段空值做特殊处理,传入 ‘NULL’ 的字符串值,后端用String字符串 + ‘,’ 拼接的方式传参,再用String的split()、contauns()函数做特殊处理,添加一个or status is NULL的查询条件即可。

private String status;
<if test="status != null and status != ' ' ">
and (status in
	<foreach item="status.split(',') " index="index" collection="list" open="(" separator="," close=")">
    	#{item}
    </foreach>
    <if test="status.contauns('NULL')">
    or status is NULL
    </if>
    )
</if>

注意点:(status in () or status is NULL) 必须用() 作为一个条件

如果没有 (),那么SQL加上其他条件会查出多余数据。
例如:beginDt = ‘20240410’ and status in (‘SUCCESS’) or status is NULL 查的数据是beginDt = ‘20240410’ and status in (‘SUCCESS’) 和 status is NULL两种情况数据的合集

注意点二:为何不用前端传 特点字符值 ‘NULL’ + 字符数组(List)传参的方式,SQL如下:

<if test="statusList!= null and statusList.size() > 0">
and (statusList in
	<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
    	#{item}
    </foreach>
     <if test="statusList.contauns('NULL')">
    or status is NULL
    </if>
    )
</if>

原因:foreach 动态SQL后,查询条件为是(status in (‘SUCCESS’, ‘NULL’) or status is NULL),多一个status = NULL的查询条件与预期不符合。

题目:Mybatis字符串拼接

1、数据库类型:Oracle
2、字符串拼接方式:concat(“a”, “b”)函数、“a” || “b”
3、两种拼接方式的区别:concat(“a”, “b”)函数只能拼接两个字符串,|| 拼接的方式没有这个限制,
优先使用 || 的拼接方式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值