MyBatis中的<where>标签和where子句的区别

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”

经验分享 程序员 微信小程序 职场和发展