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

本文介绍了MyBatis框架中<where>标签的使用,强调了当条件不成立时,where子句不会被添加到SQL中,避免生成无效的SQL语句。同时提到了在处理null值时,<where>标签的智能优化,能有效防止AND或OR前多余的条件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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”

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值