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
a.id_card = #{code}
a.unit_code = #{code}

但优化后运行会报错(3种写法都会报badsql)。

解决方法

正确的写法如下:

select * from table a 

 a.project_id=#{projectId}
 and a.id != #{id}
 and a.status=3 

     
        and a.id_card = #{code}
    
and a.unit_code = #{code}