04-MyBatis-更新操作

MyBatis修改操作

单笔更新

根据用户id修改用户名

使用的sql:

UPDATE `user`SET username = ‘赵云’ WHERE id = 26

映射文件

在User.xml配置文件中添加如下内容:


<update id="updateUserById" parameterType="cn.itcast.mybatis.pojo.User">
	UPDATE `user` SET
	username = #{username} WHERE id = #{id}
update>

批量更新

1. 拼接sql

实现方式 : 用for循环通过循环传过来的参数集合,循环出N条sql
注意第一种方法要想成功,需要在db链接url后面带一个参数 &allowMultiQueries=true
即: jdbc:mysql://localhost:3306/mysqlTest?characterEncoding=utf-8&allowMultiQueries=true

 
    <update id="batchUpdate" parameterType="java.util.Map">
        
        <foreach collection="list" separator=";" item="cus">
            update t_customer set
            c_name = #{cus.name},
            c_age = #{cus.age},
            c_sex = #{cus.sex},
            c_ceroNo = #{cus.ceroNo},
            c_ceroType = #{cus.ceroType}
            where id = #{cus.id}
        foreach>
    update>

接口

 int batchUpdate(Map<String,Object> param);

2. 用mysql的case when 条件判断变相的进行批量更新

 
    <update id="batchUpdateCaseWhen" parameterType="java.util.Map">
        update t_customer
        <trim prefix="set" suffixOverrides=",">
            
            
            
            
 
            
            <trim prefix="c_name =case" suffix="end,">
                <foreach collection="list" item="cus">
                    <if test="cus.name!=null">
                        when id=#{cus.id} then #{cus.name}
                    if>
                foreach>
            trim>
            <trim prefix="c_age =case" suffix="end,">
                <foreach collection="list" item="cus">
                    <if test="cus.age!=null">
                        when id=#{cus.id} then #{cus.age}
                    if>
                foreach>
            trim>
            <trim prefix="c_sex =case" suffix="end,">
                <foreach collection="list" item="cus">
                    <if test="cus.sex!=null">
                        when id=#{cus.id} then #{cus.sex}
                    if>
                foreach>
            trim>
            <trim prefix="c_ceroNo =case" suffix="end,">
                <foreach collection="list" item="cus">
                    <if test="cus.ceroNo!=null">
                        when id=#{cus.id} then #{cus.ceroNo}
                    if>
                foreach>
            trim>
            <trim prefix="c_ceroType =case" suffix="end,">
                <foreach collection="list" item="cus">
                    <if test="cus.ceroType!=null">
                        when id=#{cus.id} then #{cus.ceroType}
                    if>
                foreach>
            trim>
        trim>
        <where>
            <foreach collection="list" separator="or" item="cus">
                id = #{cus.id}
            foreach>
        where>
    update>

接口

int batchUpdateCaseWhen(Map<String,Object> param);

总结: 拼接sql方式更新比第二种方式速度上会快一些

你可能感兴趣的:(MyBatis)