四、动态SQL(if_where)

一、动态SQL

根据条件的不同, SQL 语句也会随之动态的改变. MyBatis中, 提供了一组标签用于实现动态SQL.

二、 <if>

用于进行条件判断, test 属性用于指定判断条件. 为了拼接条件, 在 SQL 语句后强行添加 1=1 的恒成立条件.

<select id="sel" resultType="user"> 
  select * from t_user where 1=1   
<if test="username != null and username != ''">
    and username=#{username}   
</if>   <if test="password != null and password != ''">
    and password=#{password}   </if> </select>

三、<where>

用于管理 where 子句. 有如下功能:

  a) 如果没有条件, 不会生成 where 关键字

  b) 如果有条件, 会自动添加 where 关键字

  c) 如果第一个条件中有and, 去除之

 1 <select id="sel" resultType="user"> 
 2     select * from t_user
 3     <where>
 4         <if test="username != null and username != ''">
 5              and username=#{username}
 6         </if>
 7 
 8         <if test="password != null and password != ''">
 9              and password=#{password}
10         </if>
11      </where>
12 </select>            
原文地址:https://www.cnblogs.com/qiaoxin11/p/12855458.html