zoukankan      html  css  js  c++  java
  • MyBatis(五)动态SQL 之 批量操作(更新)

    一、批量修改

      批量修改,分为两种情况:

      (1)把每条数据修改为相同内容

    方式一:update emp set ....  where eid in (1,2,3);
    方式二:update emp set .... where eid = 1 or eid = 2 or eid = 3;
    

      

      (2)把每条数据修改为对应的字段内容

    update emp set ... where eid = 1;
    update emp set ... where eid = 2;
    update emp set ... where eid = 3;
    

      

    二、实现批量修改

      1、在接口中声明方法

    //批量修改
    public void updateMoreByArray(@Param("emps")Employee[]  emps);

      2、在对应的 xml 中进行配置

        <!--
            public void updateMoreByArray(@Param("emps")Employee[]  emps);
        -->
        <update id="updateMoreByArray">
            <foreach collection="emps" item="emp">
                update tbl_employee
                set
                    last_name = #{lastName},
                    gender  = #{gender},
                    email = #{email}
                where id = #{id};
            </foreach>
        </update>

      3、测试

        @Test
         public void testBatchUpdate() throws IOException {
              //1、获取 sqlSessionFactory
              SqlSessionFactory sqlSessionFactory = getsqlSessionFactory();
              //2、获取 sqlSession 实例,能直接执行已经映射的 SQL 语句
              SqlSession sqlSession = sqlSessionFactory.openSession();
              try {
                   EmployeeMapperBatch mapper = sqlSession.getMapper(EmployeeMapperBatch.class);
    
                   Employee emp1 = new Employee(1, "Tom1", "1", "Tom@126.com");
                   Employee emp2 = new Employee(3, "John", "1", "John@126.com");
                   Employee emp3 = new Employee(4, "Smith", "0", "Smith@126.com");
                   
                   Employee[] emps = {emp1, emp2, emp3};
    
                   mapper.updateMoreByArray(emps);
    
              } finally {
                   sqlSession.close();
              }
         }

        运行结果:

        原因:创建的 预编译对象(PrepareStatement),默认只能执行一条 SQL 语句,并不支持执行多条 SQL 语句。不能通过分号写多个 SQL 来让它执行。

        解决方法

        在 jdbc.properties 的 url 后面添加一个 allowMultiQueries 参数

    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/mybatis?allowMultiQueries=true
    jdbc.username=root
    jdbc.password=root
    

        默认情况下,该属性为 false,  预编译对象只能执行一条 SQL语句。添加了该属性后,预编译对象就允许执行多条 SQL 语句。  

        再次来执行就成功了,执行的 SQL 语句:

    update tbl_employee set last_name = ?, gender = ?, email = ? where id = ?; 
    update tbl_employee set last_name = ?, gender = ?, email = ? where id = ?;
    update tbl_employee set last_name = ?, gender = ?, email = ? where id = ?;

        这时数据库也修改成功了。

  • 相关阅读:
    从排序开始(二) 希尔排序
    Linux之入侵痕迹清理总结
    MySQL使用痕迹清理~/.mysql_history
    WINDOWS之入侵痕迹清理总结
    SQL注入攻击技巧总结
    PHP iconv函数字符串转码导致截断问题
    PHP中is_numeric函数十六进制绕过0day
    反射型xss绕过IE xss filter
    Dedecms最新版本存储型XSS
    网站程序+服务器提权思路总结
  • 原文地址:https://www.cnblogs.com/niujifei/p/15242443.html
Copyright © 2011-2022 走看看