mybatis 批量更新,首先要在数据库连接 url 上添加配置 &allowMultiQueries=true,因为 mysql 默认不支持批量更新,所以需要开发人员手动设置
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root
定义 mapper 接口
package com.music.mapper;
import com.music.bean.Music;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface MusicMapper {
//批量更新
int updataMusicForeach(@Param("list") List<Music> list);
}
mapper.xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.music.mapper.MusicMapper">
<resultMap id="BaseResultMap" type="com.music.bean.Music">
<id column="m_music_id" jdbcType="BIGINT" property="mMusicId" />
<result column="m_music_problem" jdbcType="VARCHAR" property="mMusicProblem" />
</resultMap>
<!--批量更新-->
<update id="updataMusicForeach" parameterType="java.util.List">
<foreach collection="list" item="item" index="index" open="" close=";" separator=";">
update m_music set m_music_problem = #{item.mMusicProblem} where m_music_id = #{item.mMusicId}
</foreach>
</update>
</mapper>