MyBatis中的<where>標籤和where子句的區別

顏同學發表於2020-12-23

MyBatis中的標籤和where子句的區別

 <select id="selectAll" resultMap="BaseResultMap" parameterType="***">
    select <include refid="Base_Column_List"></include>
    from sys_log
    <where>
    <if test="username!=null and username!=''">
      and username like concat ('%',#{username},'%')
    </if>
    <if test="userId!=null and userId!=''">
      AND  user_Id=#{userId}
    </if>
    <if test="operation!=null and operation!=''">
      AND  operation LIKE  concat('%',#{operation},'%')
    </if>
    <if test="startTime!=null and startTime!=''">
      AND  create_time &gt;= #{startTime}
    </if>
    <if test="endTime!=null and endTime!=''">
      AND  create_time &lt;= #{endTime}
    </if>
    </where>
  </select>

< where >標籤為baiMyBatis的動態語句
上述程式碼中若baiwhere標籤裡的if全不成立,則不執行where語句。
在使用< where >標籤的情形下編譯時會自動刪除 多餘的 AND和OR

<select id="selectByParams" parameterType="map" resultType="user">
select * from user
<where>
<if test="id != null ">id=#{id}</if>
<if test="name != null and name.length()>0">
and name=#{name}
</if>
<if test="gender != null and gender.length()>0">
and gender = #{gender}
</if>
</where>
</select> 

若第一個if標籤裡ID的值為bainull的話,那麼列印出來的SQL為:select * from user where name=”xx” and gender=”xx”

相關文章