MyBatis(五)动态SQL 之 批量操作(更新) | 您所在的位置:网站首页 › mybatis多条件批量更新 › 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 中进行配置 update tbl_employee set last_name = #{lastName}, gender = #{gender}, email = #{email} where id = #{id}; 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", "[email protected]"); Employee emp2 = new Employee(3, "John", "1", "[email protected]"); Employee emp3 = new Employee(4, "Smith", "0", "[email protected]"); 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 = ?;这时数据库也修改成功了。
|
CopyRight 2018-2019 实验室设备网 版权所有 |