mybatis(18)——动态sql,where标签去掉多余的and和or

1.不使用where标签可能会出现的问题

<select id="getStudents" resultType="student" parameterType="map">
    select * from mybatis_test.student where
    <if test="id != null">
        id = #{id}
    </if>
    <if test="name!= null">
        and name = #{name}
    </if>
</select>
  1. 当id==null,name!=null的时候,SQL语句变成:select * from mybatis_test.student where and name = #{name}

2.使用where标签解决问题

<select id="getStudents" resultType="student" parameterType="map">
    select * from mybatis_test.student
    <where>
        <if test="id != null">
            id = #{id}
        </if>
        <if test="name!= null">
            and name = #{name}
        </if> 
    </where>
</select>
  1. where标签会在sql语句中添加where。
  2. where后面的语句以and或者or开头的时候,where标签会自动删除开头的and和or

版权声明:本文为qq_45895576原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。