MyBatis 批量插入与批量更新

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/totally123/article/details/79651841

1、批量插入:原理是循环insert values后的参数

  • Mapper
<insert id="addEmpBatch" parameterType="list">
    INSERT INTO employee (last_name, email, gender) VALUES
    <foreach collection="empList" item="emp" separator=",">
        (#{emp.lastName}, #{emp.email}, #{emp.gender})
    </foreach>
</insert>
  • Dao
Integer addEmpBatch(@Param("empList") List<Employee> empList);

2、批量更新:原理是循环update语句

  • Mapper
<update id="updateEmpBatch" parameterType="list">
    <foreach collection="empList" separator=";" item="emp">
        UPDATE employee
        SET last_name = #{emp.lastName}, email = #{emp.email}, gender = #{emp.gender}
        WHERE id = #{emp.id}
    </foreach>
</update>
  • Dao
Integer updateEmpBatch(@Param("empList") List<Employee> empList);

批量更新需要注意的地方:

  • 数据库连接必须加参数allowMultiQueries=true,如:
url=jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
  • 无论更新的数量是多少,如果匹配到返回1,未匹配到返回0。

猜你喜欢

转载自blog.csdn.net/totally123/article/details/79651841