数据准备
CREATE TABLE `user_t` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_name` varchar(10) CHARACTER SET latin1 DEFAULT NULL,
`password` varchar(10) CHARACTER SET latin1 DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=128 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
@RestController
public class TransactionController {
@Resource
private UserTMapper userTMapper;
private List<UserT> userTList;
private List<UserT> updateList;
{
userTList = new ArrayList<>();
userTList.add(new UserT("LiBai", "123", 14));
userTList.add(new UserT("Tom", "124", 13));
userTList.add(new UserT("Tonny", "12", 11));
userTList.add(new UserT("Unix", "13", 10));
}
{
updateList = new ArrayList<>();
updateList.add(new UserT(128, "Tom_2"));
//更新这个参数时会发生异常。但是之前操作并不会回滚。
updateList.add(new UserT(129, "1111111111111111111111111111111adsdsadsadsadas"));
updateList.add(new UserT(130, "uninx_2"));
}
/**
* 批量插入数据
*
* @return
*/
@RequestMapping("/listUser")
public List<UserT> insertUser2() {
userTMapper.batchSave(userTList);
return userTList;
}
/**
* 批量更新数据
*
* @return
*/
@RequestMapping("/listUpdate")
public List<UserT> updateUser2() {
userTMapper.batchUpdate(updateList);
return userTList;
}
}
public interface UserTMapper {
void batchSave(@Param(value = "list") List<UserT> userTList);
void batchUpdate(@Param(value = "list") List<UserT> userTList);
}
<?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.tellme.mapper.UserTMapper">
<insert id="batchSave" parameterType="java.util.List">
insert into user_t (user_name, password,
age)
VALUES
<foreach collection="list" item="item" index="index" separator=",">
(
#{item.userName,jdbcType=VARCHAR},
#{item.password,jdbcType=VARCHAR},
#{item.age,jdbcType=INTEGER}
)
</foreach>
</insert>
<insert id="batchUpdate">
<foreach collection="list" item="item" index="index" open="" close="" separator=";">
UPDATE user_t
SET user_name = #{item.userName}
WHERE id= #{item.id}
</foreach>
</insert>
</mapper>
批量插入时,可以构建多个value()
。最终与数据库执行时只是一条sql语句。
但是在xml中进行批量更新时,会执行多条sql语句。但mybatis会抛出异常,即不允许多条语句同时执行。
实现批量操作:
在url后面增加allowMultiQueries=true
配置。
spring:
datasource:
name: mysql_test
type: com.alibaba.druid.pool.DruidDataSource
#druid相关配置
druid:
url: jdbc:mysql://localhost:3306/test_db?allowMultiQueries=true
# url: jdbc:mysql://localhost:3306/test_db
username: root
password: 123qwe
但是需要注意:该批量操作的sql语句并未在一个commit中,效果等同于代码中使用for循环去更新sql。