好得很程序员自学网

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

Mybatis中<if>和<choose>的区别及“=”判断方式

<if>和<choose>的区别及[=]判断

在项目中xml文件经常会遇到在判断等于某个值时加什么条件不等于某个值的时候加什么条件

比如下面这个例子:

?

1

2

3

4

5

6

< if   test = " name != null" >

     AND T.NAME = #{NAME,jdbcType=VARCHAR}

</ if >

< if   test = " name  == null" >

     ORDER BY NAME,ID

</ if >

正确很好的写法需要引入<choose>标签

?

1

2

3

4

5

6

7

8

  < choose >

        < when test = " name != null" >

          AND T.NAME = #{NAME,jdbcType=VARCHAR}

      </ when >

      < otherwise >

        ORDER BY T.PRODUCT_TYPE_CODE, T.SORT DESC, T.CREATE_TIME

      </ otherwise >

</ choose >

第一种错误写法导致的结果就是不会去做任何判断即使name不为空。

为什么只能用<choose>标签,源码还没有研究,或者我这个例子本身就有问题现在记录下来,在后续的更新中我会再次总结一下这个问题。

<!--错误的写法-->

?

1

2

3

4

5

6

7

< if test = "newsImage != null and newsImage == 'y'" >  

    <![CDATA[ and len(newsImage) > 0 ]]>

</ if >  

<!-- 正确的,稳定,推荐使用 -->

< if test = "newsImage != null and newsImage == 'y'.toString()" >  

    <![CDATA[ and len(newsImage) > 0 ]]>

</ if >  

判断 newsImage == 'y' 时,有人认为成功,但实际上是不成功的,需要改为  newsImage == 'y'.toString()方可成功,

原因具体没有细入研究,根据实际使用推测应该是 [等于] 在java中是个比较复杂问题,涉及的[等于]有可能是变量地址相等,或者是变量值内容相等,在XML文件中简单的 == 在经过MyBatis处理后无法判断是哪种类型的[相等],所以加.toString()做强制转换操作,MyBatis就知道是值内容的比较,当然就成功了;

注意这个常量不限于数字,对于字母,如 'y' 同样需要加上 .toString()方可成功。

Mybatis选择choose和条件if用法

choose用法

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

        < choose >

             < when test = "showType == 1" >

                 IFNULL(k.fname,'未知') as pro_name,

             </ when >

             < when test = "showType == 2" >

                 IFNULL(e.fname,'未知') as business_name,

             </ when >

             < when test = "showType == 3" >

                 IFNULL(f.fname,'未知') as area_name,

             </ when >

             < when test = "showType == 4" >

                 IFNULL(h.fname,'未知') as sale_name,

             </ when >

             < otherwise >

                 IFNULL(j.F_PJQD_XMDJ,'未知') as project_type,

             </ otherwise >

         </ choose >

if用法

?

1

2

3

4

5

6

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

             and e.fname = #{businessName}

         </ if >

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

             and f.fname = #{areaName}

         </ if >

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

原文链接:https://blog.csdn.net/whatsyournamejack/article/details/52345989

查看更多关于Mybatis中<if>和<choose>的区别及“=”判断方式的详细内容...

  阅读:19次