Mybatis動態SQL優化:如何避免拼接錯誤導致查詢報錯?

Mybatis動態SQL優化:如何避免拼接錯誤導致查詢報錯?

mybatis動態sql優化報錯

在mybatis中進行動態sql查詢時,經常會遇到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}

針對該問題,有幾種常見的優化方法:

方法1:使用標簽

<pre class="brush:php;toolbar:false"><code><if test="type == 'idcard'">a.id_card = #{code}</if> <if test="type == 'unitcode'">a.unit_code = #{code}</if></code>

方法2:使用標簽

<pre class="brush:php;toolbar:false"><code><choose>     <when test="type == idcard">          and a.id_card = #{code}     </when> <when test="type == unitcode">and a.unit_code = #{code}</when>     <otherwise>       </otherwise>   </choose></code>

優化后的sql如下:

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查詢中出現的sql拼接錯誤。

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