Mybatis
前言
在XML 判断中 test 的 表达式 最好写在 '
'
里面。
test 的 表达式 采用"
"
写,当字符串是单个字符会报NumberFormatException
异常
在XML中判断时候
不能使用 <
需要用 <
替代。
if 判断
if判断表达式里面最好是单引号
作为表达式
的区间
字符串判断
如果字符串是单个字符采用下列写法会报”NumberFormatException"
<if test = "sex != null and sex != '' and sex == 'M'">
需要修改一下如下方法才不会报错
<if test = 'sex != null and sex != "" and sex == "M"'>
if 整数判断
<if test = 'age == 10'>
使用示例代码
select *
from
<if test = 'condition <= 1' >
table_1
</if>
<if test = 'condition > 1'>
table_2
</if>
结果
传入参数 condition = 1
select *
from
table_1
传入参数 condition = 2
select *
from
table_2
case when 使用替代if else
<choose>
<when test = 'condition == 1'>
条件一执行如下SQL
</when>
<when test = 'condition == 2'>
条件二执行如下SQL
</when>
<otherwise>
上面条件不满足执行当前SQL
</otherwise>
</choose>
示例代码
select *
from order
where 1 = 1
<choose>
<when test = 'condition == 1'>
and price > 10 /**价格超过10元*/
</when>
<when test = 'condition == 2'>
and type = 1 /**订单类型为 数码*/
</when>
<otherwise>
and name like '%科技%'
</otherwise>
</choose>
结果
传入参数 condition = 1
select *
from order
where 1 = 1 and price > 10
传入参数 condition = 2
select *
from order
where 1 = 1 and type = 1
传入参数 condition = 10
select *
from order
where 1 = 1 and name like '%科技%'