MyBatis学习【三】


动态SQL指的是:在程序运行时,根据不同的情况,拼接最终执行的sql语句

<if>

<if test="条件">
  SQL片段(当条件为true就拼接SQL片段)
</if>

<where>

  1. 相当于where关键字,自动补全where这个关键字
  2. 去掉多余的and和or关键字.因为当if条件不满足时可能会产生多余的and或者or关键字,使语法错误.
<select id="selectByConditionIfAndWhere" resultType="User">
    select * from user
    <where>
        <if test="username!=null and username!=''">
            username =#{username}
        </if>
        <if test="sex!=null and sex!=''">
            and sex=#{sex};
        </if>
    </where>
    </select>
</mapper>

<set>

  1. 用在update语句中,相当于set关键字
  2. 去掉SQL代码片段中后面多余的逗号
<update id="updatewithSet">
    update user
        <set>
            <if test="username!= null and username!=''">
                username=#{username},
            </if>
            <if test="birthday !=null and birthday!=''">
                birthday=#{birthday},
            </if>
            <if test="sex!=null and sex!=''">
                sex=#{sex},
            </if>
            <if test="address!=null and address!=''">
                address=#{address}
            </if>
        </set>
       where id=#{id};
    </update>
</mapper>

< foreach>

遍历list或其他集合,让每一条参数执行sql语句.
在这里插入图片描述

<delete id="deleteForeachID">
    delete from user where id in
    <foreach collection="ids" item="id" open="(" separator="," close=");">
    #{id}
</foreach>
    </delete>
</mapper>
    /**
     *  动态sql <foreach></foreach>
     * @param ids 要删除的id集合
     */
    void deleteForeachID(@Param("ids") int[] ids);

<sql>和<include>

  1. sql标签:定义一段SQL语句,起个名字可以重用。
  2. include标签:引入上面定义的SQL代码段。
<sql id="commonInsert">
        insert into user(username, birthday, sex, address) VALUES
    </sql>
<insert id="addAllUser" useGeneratedKeys="true" keyProperty="id">
    <include refid="commonInsert">
    </include>
    <foreach collection="list" item="user" close=";" separator="," >
        (#{user.username},#{user.birthday},#{user.sex},#{user.address})
    </foreach>
</insert>

遇到问题

1. 数据库id字段设置为自增,但是删除数据再添加时id字段不连续

原因: 自增使用过的值不会再被使用
解决:数据库执行:

SET @i=0;
UPDATE user SET id=(@i:=@i+1);
ALTER TABLE user AUTO_INCREMENT=0

2. xml<sql>报错

原因:使用了sql语言检测功能,可以无视报错

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值