mybatisPlus之自动填充功能及防全表更新与删除插件
发布人:shili8
发布时间:2025-03-10 12:03
阅读次数:0
**MyBatisPlus 之自动填充功能及防全表更新与删除插件**
在实际的开发过程中,我们经常会遇到一些需要自动填充数据的场景,例如:创建时间、更新时间等。同时,也有可能出现误操作导致的全表更新或删除问题。为了解决这些问题,我们可以使用 MyBatisPlus 提供的自动填充功能及防全表更新与删除插件。
### 自动填充功能MyBatisPlus 提供了一个叫做 `AutoFill` 的接口,用于实现自动填充数据的功能。我们可以通过实现这个接口来自定义需要填充的字段和值。
#### 实现 AutoFill 接口
javapublic class MyAutoFill implements AutoFill { @Override public void autoFill(ListupdateInfoList, UpdateInfo updateInfo) { // 自动填充创建时间 updateInfo.setCreateTime(new Date()); // 自动填充更新时间 updateInfo.setUpdateTime(new Date()); } }
#### 配置 MyBatisPlus在 `mybatis-plus-config.xml` 中配置自动填充功能:
xml<configuration> <settings> <!-- ... --> <setting name="autoFillEnabled" value="true"/> </settings> <typeAliases package="com.example.mybatisplus.entity"/> <mapperRegistry> <!-- ... --> </mapperRegistry> </configuration>
#### 使用自动填充功能在使用 MyBatisPlus 的时候,我们可以通过 `@TableField` 注解来指定需要自动填充的字段:
java@TableIdprivate Long id; @TableField(fill = FieldFill.INSERT) private Date createTime; @TableField(fill = FieldFill.UPDATE) private Date updateTime;
### 防全表更新与删除插件MyBatisPlus 提供了一个叫做 `UpdateById` 的方法,用于实现安全的更新操作。同时,也提供了一个叫做 `deleteBatchBySqlId` 的方法,用于实现安全的批量删除操作。
#### 使用 UpdateById 方法
javapublic void updateById(Long id) { // ... }
#### 使用 deleteBatchBySqlId 方法
javapublic void deleteBatchBySqlId(String sqlId, Long[] ids) { // ... }
#### 配置 MyBatisPlus在 `mybatis-plus-config.xml` 中配置防全表更新与删除插件:
xml<configuration> <settings> <!-- ... --> <setting name="updateByIdEnabled" value="true"/> <setting name="deleteBatchBySqlIdEnabled" value="true"/> </settings> <typeAliases package="com.example.mybatisplus.entity"/> <mapperRegistry> <!-- ... --> </mapperRegistry> </configuration>
#### 使用防全表更新与删除插件在使用 MyBatisPlus 的时候,我们可以通过 `@TableField` 注解来指定需要防全表更新与删除的字段:
java@TableIdprivate Long id; @TableField(fill = FieldFill.INSERT) private Date createTime; @TableField(fill = FieldFill.UPDATE) private Date updateTime;
### 总结MyBatisPlus 提供了自动填充功能及防全表更新与删除插件,用于解决实际开发过程中遇到的问题。通过实现 `AutoFill` 接口和配置 MyBatisPlus,我们可以自定义需要填充的字段和值,并且可以安全地进行更新和删除操作。
### 参考* [MyBatisPlus 文档]( />* [MyBatisPlus GitHub仓库](