github: https://github.com/wuyujia/java-utils/tree/master/mybatis/batch
在工作中使用mybatis进行数据库操作时遇到过, mybatis批量插入, 更新操作繁琐问题, 所以写了2个工具类, 一个插入工具类, 一个更新工具类, 在使用中收到同事的鼓励, 所以分享出来大家用!
希望大家能多多给我建议和支持
工具本身有一些bug, 暂时没想到很好的解决方案, 也希望大家多提提建议. 能够有pull request也更好.
[TOC]
my poor English!!!
Introduction
This is a util of mybatis batch operation,
include batch insert
and batch update
Although it's very convenient to use, it also limit to use
limit:
- 1: create background
In my workspace, I use the SpringFramework with Mybatis, and my db is Mysql.
- 2: design
It's designed to solve the difficult problem of Mybatis batch operation, no matter
insert
orupdate
- 3: bug
Because it is batch operation, so I don't consider that once mysql don't allow null value, but insert or update a null value. Although I design a property about null value not insert or not update
For example:
- When I want to insert a JavaBean (mapping with mysql fields, JavaBean's fields use hump names and db fields use underline names), no problem. If there is null value in bean's fields, it will be ignored by util when I set a selective is true.
- When I want to insert a list of JavaBean,
there are some potential pitfalls. Why? Because I use java reflect to get many fields of db fields mapping, if dbnot allow null
and there isnull value
in beans, it will failure to execute sql if don't chooseselective
. If I chooseselective
, and values of beans fields are the same with each other.
e.g User.class has two fieldname
andage
, one of list has name value , and age value is null, the other of list has null value of name, age has normal value, and both values arenot allow null
in db, so what will happen when execute sql? Failure!!!
So when you plan to use it, you must consider how to promise each bean has the same value structure. And We hope you will help us to improvement the util
Quick Start
Framework: Spring + Mybatis
Where to use: The InsertProvider Or UpdateProvider
StrategyMapper
@Mapper
public interface StrategyMapper {
@InsertProvider(type = StrategyProvider.class, method = "batchInsert")
Integer batchInsert(@Param("dataList")List<Strategy> dataList);
}
StrategyProvider
public class StrategyProvider {
public String batchInsert(List<Strategy> dataList) {
BatchInsertSQLBuilder<Strategy> builder = new BatchInsertSQLBuilder<>();
builder.setInsertTable("ad_strategy");
builder.setSelective(true);
for (Strategy data: dataList) {
builder.setData(data);
}
return builder.toString();
}
}
End
Thanks for Use, Hope receive your Suggestion or Pull Requests!!!
Excuse my poor English!!!
网友评论