MyBatis Generator Selective选择插入更新增强插件
在使用Mybatis保存或者更新数据时往往需要指定插入或者更新某些字段而非全字段,或者把数据库某字段置为null的操作。在MyBatis Generator 生成的方法中有xxxSelective方法来实现第一个需求(某些情况下并不方便),而第二个需求实现更是曲折。这里提供了一个Selective方法的增强插件来增强指定功能,具体实现可以参照我的mybatis-generator-plugin,下面是具体使用方法。
一、依然是在Mybatis Generator增加插件依赖(插件最新版本查看);
<!-- mybatis-generator 自动代码插件 --> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.5</version> <configuration> <!-- 配置文件 --> <configurationFile>src/main/resources/mybatis-generator.xml</configurationFile> <!-- 允许移动和修改 --> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> <dependencies> <!-- jdbc 依赖 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.40</version> </dependency> <dependency> <groupId>com.itfsw</groupId> <artifactId>mybatis-generator-plugin</artifactId> <version>1.0.7-SNAPSHOT</version> </dependency> </dependencies> </plugin>
二、mybatis-generator.xml配置文件中增加插件配置;
<!-- Selective选择插入更新增强插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.SelectiveEnhancedPlugin"/>
三、具体使用;
public class Test { public static void main(String[] args) { // 1. 指定插入或更新字段 Tb tb = new Tb.Builder() .field1(1) .field2("xx2") .field3(1) .field4(new Date()) .createTime(new Date()) .delFlag(Tb.DEL_FLAG) .build(); // 只插入或者更新field1,field2字段 this.tbMapper.insertSelective(tb.selective(Tb.Column.field1, Tb.Column.field2)); this.tbMapper.updateByExampleSelective(tb.selective(Tb.Column.field1, Tb.Column.field2), new TbExample() .createCriteria() .andIdEqualTo(1l) .example() ); this.tbMapper.updateByPrimaryKeySelective(tb.selective(Tb.Column.field1, Tb.Column.field2)); this.tbMapper.upsertSelective(tb.selective(Tb.Column.field1, Tb.Column.field2)); this.tbMapper.upsertByExampleSelective(tb.selective(Tb.Column.field1, Tb.Column.field2), new TbExample() .createCriteria() .andField3EqualTo(1) .example() ); // 2. 更新某些字段为null this.tbMapper.updateByPrimaryKeySelective( new Tb.Builder() .id(1l) .field1(null) // 方便展示,不用设也可以 .build() .selective(Tb.Column.field1) ); } }