MyBatis where标签的用法

来源:互联网 发布:淘宝团队规模 编辑:程序博客网 时间:2024/05/11 04:22

场景:在MyBatis拼装动态SQL语句中,在where的条件中常常先判断 if 条件是否成立,再加入 where 的条件部。

例如,查询满足条件的学生时,考虑到 if 标签的条件都不成立的情况,因此在 where 的 条件补加入 1=1 这个永真条件,如果没有加入1=1,这个语句在执行时是一个错误不能执行的语句。

XML语句代码:

    <select id="queryStudent" parameterType="StudentDTO" resultType="Student" >        select * from Student        where 1 = 1        <if test="name != null and name != ''">            and name = #{name,jdbcType=VARCHAR}        </if>        <if test="address != null and address != '' ">            and address = #{address,jdbcType=VARCHAR}        </if>        <if test="nation != null and address != '' ">            and nation = #{nation,jdbcType=VARCHAR}        </if>    </select>

解决方法:MyBatis的 where 标签可以解决如上所示的例子,经过改写后的XML语句代码:

    <select id="queryStudent" parameterType="StudentDTO" resultType="Student">        select * from Student        <where>            <if test="name != null and name != ''">                and name = #{name,jdbcType=VARCHAR}            </if>            <if test="address != null and address != '' ">                and address = #{address,jdbcType=VARCHAR}            </if>            <if test="nation != null and address != '' ">                and nation = #{nation,jdbcType=VARCHAR}            </if>        </where>    </select>
当where标签里面的条件成立之时,SQL会自动加入 where 关键字,而且如果where标签内返回的内容是以 and 或者 or 关键字开头的,则开头的 and 或者 or 会被剔除掉。

原创粉丝点击