mybatis时间查询使用字符串判空和in查询使用字符串传递参数踩坑

本文分享了在使用MyBatisXML时遇到的两个常见问题:1.时间类型参数的正确判断方式,避免因为空字符串引发的异常;2.如何正确处理IN查询中的数组参数,包括使用@Param注解和避免null值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

mybatis xml踩坑记录

问题1

当传递参数为时间类型时不要使用字符串判空否则就会报以下错误

错误示范
//注意以下时错误写法
<if test="begTime != null  and endTime != null and begTime != '' and endTime != ''">
AND insert_time BETWEEN #{begTime,jdbcType=TIMESTAMP} AND #{endTime,jdbcType=TIMESTAMP}
</if>
Caused by: java.lang.IllegalArgumentException: invalid comparison: cn.hutool.core.date.DateTime and java.lang.String
正确写法
//注意以下时错误写法,不要判断空字符串
<if test="begTime != null  and endTime != null">
AND insert_time BETWEEN #{begTime,jdbcType=TIMESTAMP} AND #{endTime,jdbcType=TIMESTAMP}
</if>
问题2

当使用in查询数据时,不能直接传字符串比如1,2,否则虽不会报错,但查出数据是有问题的

错误示范
//Dao层
public class CuuService(){
public Integer getOne(String ids);
}
//调用方法
public class cuuApplication(){
CuuService srvice = new CuuService();
String ids = "1,2"
Integer one = service.getOne(ids);
}
//注意以下时错误写法,xml无法直接支持数组
<if test="param1!=null">
id in(#{param1,jdbcType=VARCHAR}) 
</if>
正确写法
//Dao层
public class CuuService(){
//注意使用@Param注解可给数组起别名
public Integer getOne(@Param("idArr")String[] idArr);
}
//调用方法
public class cuuApplication(){
CuuService srvice = new CuuService();
String ids = "1,2"
//把字符串转成数组在传递就正常了
String[] idArr = ids.split(",");
Integer one = service.getOne(idArr);
}
//以下为正确写法
<if test="param1 != null and param1 != ''">
AND store_id in
<foreach collection="idArr" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</if>
问题3

mysql使用in查询时踩坑,in之后的数据不能存在null,否则无法查出结果

错误示范
//此处包含null,是无法查出数据的
<select>
select * from user where id in(1,2,null)
</select>
正确示范
//不包含null可以查出数据,提示在使用子查询in时记得排除null
<select>
select * from user where id in(1,2)
</select>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值