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>