1. 通过实现MybatisPlus IService接口,获取saveBatch
底层其实是单条插入
@Transactional(
rollbackFor = {Exception.class}
)
public boolean saveBatch(Collection<T> entityList, int batchSize) {
String sqlStatement = this.getSqlStatement(SqlMethod.INSERT_ONE);
return this.executeBatch(entityList, batchSize, (sqlSession, entity) {
sqlSession.insert(sqlStatement, entity);
});
}
2. 通过XML手动拼接SQL实现批量插入
缺点是每个表都要手动编写xml,优点是效率较高
// mapper.xml
<mapper namespace="com.example.mapper.UserMapper">
<insert id="insertUsers" parameterType="java.util.List">
insert into user (id, name, age) values
<foreach collection="list" item="user" separator=",">
(#{user.id}, #{user.name}, #{user.age})
</foreach>
</insert>
</mapper>
3. 使用InsertBatchSomeColumn方法批量插入
底层和第二种方法是一样也是拼接sql,但无需手动编写sql语句
1. 自定义SQL注入器实现DefaultSqlInjector,添加InsertBatchSomeColumn方法
2. 编写配置类,把自定义注入器放入spring容器
3.编写自定义BaseMapper,加入InsertBatchSomeColumn方法
ps:如果在你的项目中,仅仅有一两个类需要用到批量插入,那完全没必要抽取一个MyBaseMapper。直接用你的业务Mapper继承BaseMapper,并在对应业务Mapper中配置insertBatchSomeColumn()方法即可
4.需要批量插入的Mapper继承自定义BaseMapper
测试
参考文献: