MyBatis以集合方式批量新增(推荐)
1、编写UserService服务类
@Service
public class UserService {
@Resource
private UserMapper userMapper;
public void InsertUsers(){
long start = System.currentTimeMillis();
List<User> userList = new ArrayList<>();
User user;
for(int i = 0 ;i < 10000; i++) {
user = new User();
user.setUsername("name" + i);
user.setPassword("password" + i);
userList.add(user);
}
userMapper.insertUsers(userList);
long end = System.currentTimeMillis();
System.out.println("一万条数据总耗时:" + (end-start) + "ms" );
}
}
2、编写UserMapper接口
@Mapper
public interface UserMapper {
Integer insertUsers(List<User> userList);
}
3、编写UserMapper.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.ithuang.demo.mapper.UserMapper">
<insert id="insertUsers">
INSERT INTO user (username, password)
VALUES
<foreach collection ="userList" item="user" separator =",">
(#{user.username}, #{user.password})
</foreach>
</insert>
</mapper>
4、输出结果
一万条数据总耗时:521ms
MyBatis-Plus提供的InsertBatchSomeColumn方法(推荐)
1、编写EasySqlInjector 自定义类
public class EasySqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
// 注意:此SQL注入器继承了DefaultSqlInjector(默认注入器),调用了DefaultSqlInjector的getMethodList方法,保留了mybatis-plus的自带方法
List<AbstractMethod> methodList = super.getMethodList(mapperClass, tableInfo);
methodList.add(new InsertBatchSomeColumn(i -> i.getFieldFill() != FieldFill.UPDATE));
return methodList;
}
}
2、定义核心配置类注入此Bean
@Configuration
public class MybatisPlusConfig {
@Bean
public EasySqlInjector sqlInjector() {
return new EasySqlInjector();
}
}
3、编写UserService服务类
public class UserService{
@Resource
private UserMapper userMapper;
public void InsertUsers(){
long start = System.currentTimeMillis();
List<User> userList = new ArrayList<>();
User user;
for(int i = 0 ;i < 10000; i++) {
user = new User();
user.setUsername("name" + i);
user.setPassword("password" + i);
userList.add(user);
}
userMapper.insertBatchSomeColumn(userList);
long end = System.currentTimeMillis();
System.out.println("一万条数据总耗时:" + (end-start) + "ms" );
}
}
4、编写EasyBaseMapper接口
public interface EasyBaseMapper<T> extends BaseMapper<T> {
/**
* 批量插入 仅适用于mysql
*
* @param entityList 实体列表
* @return 影响行数
*/
Integer insertBatchSomeColumn(Collection<T> entityList);
}
5、编写UserMapper接口
@Mapper
public interface UserMapper<T> extends EasyBaseMapper<User> {
}
6、单元测试结果
一万条数据总耗时:575ms