Mybatis中SQL片段以及if,foreach的使用

<!--
    SQL片段
    sql标签,id属性:唯一标识,将来各个statement语句中通过include标签的refid属性将其引入
-->

<!--
    1.1 if标签    test属性:布尔类型表达式
-->
<sql id="sql1">
    <if test="user!=null">
        <if test="user.gender!=null and user.gender!=''">
            and gender=#{user.gender}
        </if>
        <if test="user.name!=null and user.name!=''">
            and name like concat('%',#{user.name},'%')
        </if>
    </if>
</sql>
<!--
    1.2 foreach标签  迭代标签
    collection属性:列表名,例如:ids数组、List<User>集合等
    index属性:索引值
    item属性:迭代出的元素
    open属性:拼接开始的符号
    close属性:拼接结束的符号
    separator属性:分隔符
-->
<!-- 方式一:and id in(13,17,22) -->
<sql id="sql2">
    <if test="ids!=null">
        <foreach collection="ids" item="id" open="and id in(" close=")" separator=",">
            #{id}
        </foreach>
    </if>
</sql>
<!-- 方式二:and (id=13 or id=17 or id=23) -->
<sql id="sql2">
    <if test="ids!=null">
        <foreach collection="ids" item="id" open="and (" close=")" separator="or">
            id=#{id}
        </foreach>
    </if>
</sql>
<!--
    1.需求:通过用户性别和姓名查询用户列表 PS:不允许性别或者姓名为null或者空串
    动态sql:标签 if where foreach set choose&when&otherwise  ...

    where标签 充当where条件进行使用,默认去除第一个拼接上的条件的and
-->
<select id="findUserByGenderAndName" parameterType="UserQueryVO" resultType="User">
    select * from user
    <where>
        <include refid="sql1" />
    </where>
</select>

<!--
    2.需求:通过用户性别和姓名查询用户列表,且id值是15或20或25  PS:不允许性别或者姓名为null或者空串
-->
<select id="findUsers" parameterType="UserQueryVO" resultType="User">
    select * from user
    <where>
        <include refid="sql1" />
        <include refid="sql2" />
    </where>
</select>
<!-- 3.批量插入用户数据 -->
<insert id="insertUserBatch" parameterType="list">
    insert into user(name,age,gender,birthday,pwd,state)
    <foreach collection="list" item="user" open="values" close="" separator=",">
        (#{user.name},#{user.age},#{user.gender},#{user.birthday},#{user.pwd},#{user.state})
    </foreach>
</insert>
<!-- 4.更新用户的非空信息 -->
<update id="updateUser" parameterType="User">
    update user
    <set>
        <if test="name!=null">
            name=#{name}
        </if>
        <if test="gender!=null">
            gender=#{gender}
        </if>
    </set>
    where state=#{state}
</update>
  • 32
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值