在MyBatis的Mapper中是不支持if-else语句,如下:if( condition ) {
// ...
} else {
// ...
}
我们可以通过choose(即Java的switch语句)语句来进行替换。choose语句的语法如下:
你的SQL语句1
所有when都没有匹配的默认SQL语句
其中:when 表示一个if语句
otherwise 表示if语句的else语句
实例1:下面Mapper将批量插入用户信息,其中当name为空(null或'')时,插入‘-’符号。age为空时,插入0。代码如下:
insert into user(name, age)
values
#{item.name, jdbcType=VARCHAR},
'-',
#{item.age, jdbcType=INTEGER},
0,
实例2:查询用户信息,如果指定了name查询条件,则使用name进行模糊查询(%name%);如果没有指定,则使用“Admin%”进行模糊查询。代码如下:
...
select id, name, age from user where del_flag=0
and name like concat(concat('%', #{name}), '%')
and name like 'Admin%'
MyBatis的Mapper中的choose用法就这些,谢谢支持!!!
参考资料:
点击学习 MyBatis 教程,了解更多的 MyBatis 知识!