mybatis_05动态SQL_if和where

时间:2023-03-08 22:24:08
  • If标签:作为判断入参来使用的,如果符合条件,则把if标签体内的SQL拼接上。

   注意:用if进行判断是否为空时,不仅要判断null,也要判断空字符串‘’;

  • Where标签:会去掉条件中的第一个and符号。

通过if和where通过判断可以选择那些语句来执行,那些语句不执行,生成最终SQL语句

 

在第一个底层if判断中,SQL语句前面加上and也可以,系统会自动去掉

<resultMap id="userByresultmap" type="user">
<id property="id" column="id_"></id>
<result property="username" column="username_"></result>
<result property="birthday" column="birthday_"></result>
<result property="sex" column="sex_"></result>
<result property="address" column="address_"></result>
</resultMap> <select id="findUserByifwhere" parameterType="userQueryVO" resultMap="userByresultmap"> select * from USER <where>
<if test="user!=null and user!=''"> <if test="user.sex!=null and user.sex!=''">
<!—也可以写成and sex=#{user.sex},系统会自动去掉-->
sex=#{user.sex}
</if>
<if test="user.username!=null and user.username!=''">
and username LIKE "%${user.username}%"
</if>
</if> </where> </select>