Mybatis动态SQL优化:如何正确使用<if>和<choose>标签?
本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《Mybatis动态SQL优化:如何正确使用<if>和<choose>标签?》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~
mybatis动态sql编写,遇到问题求解
在使用mybatis动态sql时,遇到如下问题:
select * from table a where a.project_id=#{projectid} and a.id != #{id} and a.status=3 and a.id_card = #{code} or a.unit_code = #{code}
想要将其优化为:
select * from table a where a.project_id=#{projectid} and a.id != #{id} and a.status=3 and <if test="type == 'idcard'">a.id_card = #{code}</if> <if test="type == 'unitcode'">a.unit_code = #{code}</if>
但优化后运行会报错(3种写法都会报badsql)。
解决方法
正确的写法如下:
select * from table a <where> a.project_id=#{projectId} and a.id != #{id} and a.status=3 <choose> <when test="type == idCard"> and a.id_card = #{code} </when> <when test="type == unitCode">and a.unit_code = #{code}</when> <otherwise> </otherwise> </choose> </where>
理论要掌握,实操不能落!以上关于《Mybatis动态SQL优化:如何正确使用<if>和<choose>标签?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注主机宝贝公众号吧!