默认情况下,MybatisPlus的批量插入saveBatch方法实际上是for循环单条插入。
如果想要实现真实的批量插入,需要在spring.datasource.url配置中加
rewriteBatchedStatements=true
此时调用saveBatch方法,就会是真实的批量插入:
INSERT INTO T () VALUES (?), (?), (?);
此外,批量更新和批量删除也会是真实的批处理。
提交的list中,entity对象的所有字段都必须不为null,否则全部会转换为for循环单条插入。
即使数据库的表设置了默认值,即使表中字段允许为空,提交的entity对象也必须都set值。
1.如果表是自增主键AUTO_INCREMENT,在entity的id字段上加IdType.AUTO后,可以不setId。
- @TableId(value = "id", type = IdType.AUTO)
- private Long id;
2.如果在entity字段上面使用了忽略策略,可以不set相关字段。
- @TableField(insertStrategy = FieldStrategy.IGNORED)
- private Date expireTime;
3.如果在entity字段上面使用了自动填充字段功能,并维护了自动填充接口,可以不set相关字段。
-
- @TableField(fill = FieldFill.INSERT)
- @Version
- private Integer version;
-
- @TableField(fill = FieldFill.INSERT)
- private String createUser;
-
- @TableField(fill = FieldFill.INSERT)
- private Date createTime;
-
- @TableField(fill = FieldFill.INSERT_UPDATE)
- private String updateUser;
-
- @TableField(fill = FieldFill.INSERT_UPDATE)
- private Date updateTime;
-
- @TableField(fill = FieldFill.INSERT)
- @TableLogic
- private Long deleteFlag;