mybatis plus的IService(com.baomidou.mybatisplus.extension.service.IService)接口中提供了saveBatch()方法,但是这个插入方法使用的是多条insert语句的方式来插入数据,效率不够高。
所以mybatis plus又提供了另外一个方法来实现批量插入insertBatchSomeColumn(),但是这个批量存储的方法在某些场景下可能报错。
如果我们在设计数据库表的时候设置了not null default,如下所示gender列为not null
create table user(
id bigint(20) not null comment '主键',
name varchar(50) default '' comment '姓名',
gender char(1) not null default 'O' comment '性别';
)
再使用insertBatchSomeColumn()方法进行插入,就会报错。
报错示例如下:
### SQL: INSERT INTO user (id,name,gender) VALUES (?,?,?) , (?,?,?)
### Cause: java.sql.SQLIntegrityConstraintViolationException: (conn=20976313) Column 'QUIT_TIME' cannot be null
; (conn=20976313) Column 'gender' cannot be null; nested exception is java.sql.SQLIntegrityConstraintViolationException: (conn=20976313) Column 'gender' cannot be null
at org.springframework.jdbc.support.SQLExceptionSubclassTranslator.doTranslate(SQLExceptionSubclassTranslator.java:87)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:70)
这个时候有两种选择
1、将这个列设置成可以为空,去掉not null
create table user(
id bigint(20) not null comment '主键',
name varchar(50) default '' comment '姓名',
gender char(1) default 'F' comment '性别';
)
2、在xml中写SQL语句来进行批量插入了,为空的gender列直接不写入进去就可以了
<insert id="saveList">
insert into
user (
id,
name
)values
<foreach collection="list" item="item" index="index" separator="," >
(
#{item.id},
#{item.name}
)
</foreach>
</insert>