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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值