好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

关于mybatis遇到Integer类型的参数时动态sql需要注意条件

mybatis Integer类型参数动态sql注意条件

例如以下拼接的动态sql

?

1

2

3

< if test = "work_status !=null  and work_status !='' " >

  and T.status=#{work_status,jdbcType=INTEGER}

</ if >

当work_status为0时,Mybatis会将0解析为了空字符串‘’,这样if判断就为false,如果想正确添加and后的查询条件,应该改成

?

1

2

3

< if test = "work_status !=null  " >

  and T.status=#{work_status,jdbcType=INTEGER}

</ if >

mybatis的坑——Integer类型参数解析问题

有时候我们使用实体类传递参数时

有些属性会被设置为Integer类型,比如status、sort等,在这里,使用Integer类型参数作为条件时,要注意一点:例如

?

1

2

3

< if test = "bean.activitySort != null and bean.activitySort !=" "">

        AND activity_sort = #{bean.activitySort,jdbcType=VARCHAR}

</ if >

这里对于bean.activitySort的判断正常情况下如果activitySort是String类型,先判空,再判断是否是空字符串,这样是正常的,但是如果activitySort是Integer类型参数,那么使用时就需要注意,此处不能对activitySort进行空字符串的判断,因为什么呢?

因为mybatis在解析Integer类型数据时

如果数据值为0,会将0解析为空字符串,这样你传入的参数就成为无效的了,所以正常使用Integer类型参数应该是下面这样:

?

1

2

3

< if test = "bean.activitySort != null" >

        AND activity_sort = #{bean.activitySort,jdbcType=VARCHAR}

</ if >

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/yangyansong789/article/details/80618116

查看更多关于关于mybatis遇到Integer类型的参数时动态sql需要注意条件的详细内容...

  阅读:18次