在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