Mybatis框架之动态SQL

if标签

       实际业务中,有时候会需要一个参数,有时候需要两个参数,按照原来的方法,需要写两个方法。为了解决这个mybatis提出了if标签。

SELECT * FROM

t_user
<where>
<if test="(user.name != null) and (user.name != '')">
    AND name=#{user.name}
</if>
<if test="(user.sex) != null and (user.sex) != ''">
    AND sex={user.sex}
</if>

where标签

       按照上面的方法写的话,有一个问题,if标签中的and关键字没法放,前后都可能报错。所以提出了where标签。

       能够自动删除if标签中的前and

       如果后面的条件不成立,where关键字也可以省略。

SELECT * FROM

t_user
<where>
<if test="(user.name != null) and (user.name != '')">
    AND name=#{user.name}
</if>
<if test="(user.sex) != null and (user.sex) != ''">
    AND sex={user.sex}
</if>
</where>

foreach标签

       foreach应用于通过多个id查询人

       SELECT* FROM t_user where id in (1,2,3)

<select id="findUserByIds" parameterType="cn.hd.param.QueryVo">

       <include refid="selectUser"></include>
    <where>
        id in
    <foreach collection="ids"item="id" separator="," open="(" close=")">
        #{id}
    </foreach>
    </where>
</select>

       如果参数类型是包装类,collection的值,包装类中属性名保持一致即可。

       Item必须写    给遍历的元素起名字跟下面的占位符中的值保持一致。

       separator分隔符

       open    将遍历的结果后方加上一个值

       如果参数是数组

       collection的值必须是array

       如果是list集合

       Collection中的值必须是list

sql片段

<sql id="selectUser">

    SELECT * FROM t_user
</sql>

<include refid="selectUser"></include>


<where>
<if test="(user.name != null) and (user.name != '')">
    AND name=#{user.name}
</if>
<if test="(user.sex) != null and (user.sex) != ''">
    AND sex={user.sex}
</if>
</where>


发布了88 篇原创文章 · 获赞 383 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/weixin_42047611/article/details/80998948