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>

? 版權聲明
THE END
喜歡就支持一下吧
點贊9 分享