26、Mybatis-Puls性能分析插件,Wapper条件构造器、代码生成器
1、性能分析插件,加入mybatis-puls 的组件,首先添加mybatis-plus依赖
<!-- mybatis-plus的依赖 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>
<!-- mybatis-plus的自动生成依赖 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.0.6</version>
</dependency>
//性能分析插件 @Bean @Profile({"dev","test"}) public PerformanceInterceptor performanceInterceptor(){ PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor(); performanceInterceptor.setMaxTime(2000); performanceInterceptor.setFormat(true); return performanceInterceptor; }


3、Wapper条件构造器
@RunWith(SpringRunner.class) @SpringBootTest public class WapperTest { @Autowired private UserMapper userMapper; @Test public void testSelect() { Page<User> page = new Page<>(1,8); QueryWrapper<User> wappper = new QueryWrapper<>(); wappper.eq("name","edwin"); IPage<User> userIPage = userMapper.selectPage(page, wappper); List<User> records = userIPage.getRecords(); records.forEach(System.out::println); } }
4、Mybatis-plus 的代码生成器(简单的)
public static void main(String[] args) { // 需要构建一个 代码自动生成器 对象 AutoGenerator mpg = new AutoGenerator(); // 1、全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir").concat("/mybatis-plus"); gc.setOutputDir(projectPath+"/src/main/java"); gc.setAuthor("危存盛"); gc.setOpen(false); gc.setFileOverride(false); // 是否覆盖 gc.setServiceName("%sService"); // 去Service的I前缀 gc.setIdType(IdType.ID_WORKER); gc.setDateType(DateType.ONLY_DATE); gc.setSwagger2(true); mpg.setGlobalConfig(gc); //2、设置数据源 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://8.129.215.115:3306/mybatis_plus? useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("root"); dsc.setDbType(DbType.MYSQL); mpg.setDataSource(dsc); //3、包的配置 PackageConfig pc = new PackageConfig(); //pc.setModuleName("system");//如果有模块名就配置这个 pc.setParent("com.wei.shun.mybatis.plus"); pc.setEntity("entity"); pc.setMapper("mapper"); pc.setService("service"); pc.setController("controller"); mpg.setPackageInfo(pc); //4、策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setInclude("my_user"); // 设置要映射的表名 strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setEntityLombokModel(true); // 自动lombok; strategy.setLogicDeleteFieldName("deleted"); // 自动填充配置 TableFill gmtCreate = new TableFill("create_time", FieldFill.INSERT); TableFill gmtModified = new TableFill("update_time", FieldFill.INSERT_UPDATE); ArrayList<TableFill> tableFills = new ArrayList<>(); tableFills.add(gmtCreate); tableFills.add(gmtModified); strategy.setTableFillList(tableFills); // 乐观锁 strategy.setVersionFieldName("version"); strategy.setRestControllerStyle(true); strategy.setControllerMappingHyphenStyle(true); // localhost:8080/hello_id_2 mpg.setStrategy(strategy); mpg.execute(); //执行 }
4、创建公共实体类公用的属性类
@Getter @Setter @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) public class OperationEntity extends IdEntity{ /** * 创建时间 */ @TableField(fill = FieldFill.INSERT) private Date createTime; /** * 创建账号 */ // @TableField(fill = FieldFill.INSERT) // private String createBy; /** * 更新时间 */ @TableField(fill = FieldFill.INSERT_UPDATE) private Date updateTime; /** * 更新账号 */ // @TableField(fill = FieldFill.UPDATE) // private String modifiedBy; @TableLogic() private Integer logicDelete; @Version private Integer version;
@Data public class IdEntity implements java.io.Serializable{ /** * 主键id,统一使用id名称 */ @JsonSerialize private Long id; }
5、创建自动生成的模板文件存放目录:test/resouurces/template/controller.java.vm 文件
package ${package.Controller}; import com.baomidou.mybatisplus.core.metadata.IPage; import com.sf.ibu.base.annotation.ActionLog; import com.sf.ibu.base.domain.dto.PageDTO; import com.sf.ibu.base.enums.OperateTypeEnum; import com.sf.ibu.base.utils.ArgumentCheckUtil; import com.sf.ibu.base.utils.Result; import com.sf.ibu.base.utils.ResultUtil; import ${package.Entity}.${entity}; import ${package.Entity}.dto.${entity}DTO; import ${package.Entity}.vo.${entity}VO; import ${package.Service}.${entity}Service; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.util.List; #set ($lowEntity = $entity.substring(0,1).toLowerCase() + $entity.substring(1,$entity.length())) /** * <p> * $!{table.comment} 前端控制器 * </p> * * @author ${author} * @since ${date} */ @Api(tags = "$!{table.comment}接口") @RestController @RequestMapping("/$lowEntity") public class ${table.controllerName} { @Autowired ${entity}Service ${lowEntity}ServiceImpl; @ApiOperation(value = "保存或修改$!{table.comment}" , notes = "保存或修改$!{table.comment}") @ActionLog(operateType = OperateTypeEnum.UPDATE, detail = "保存或修改$!{table.comment}") @PostMapping(value = "/saveOrUpdate") public Result<Void> saveOrUpdate(@Validated @RequestBody ${entity}DTO ${lowEntity}DTO) { ${entity} $lowEntity = new ${entity}(); BeanUtils.copyProperties(${lowEntity}DTO, $lowEntity); ${lowEntity}ServiceImpl.saveOrUpdate($lowEntity); return ResultUtil.successResult(); } @ApiOperation(value = "查询$!{table.comment}" , notes = "查询$!{table.comment}") @GetMapping(value = "/getById") public Result<${entity}VO> getById(@RequestParam("id") Long id) { ${entity} ${lowEntity} = ${lowEntity}ServiceImpl.getById(id); ArgumentCheckUtil.checkObjetNull(${lowEntity}, "exception.common.getById.notNull"); ${entity}VO ${lowEntity}VO = new ${entity}VO(); BeanUtils.copyProperties(${lowEntity}, ${lowEntity}VO); return ResultUtil.successResultReturnData(${lowEntity}VO); } @ApiOperation(value = "查询$!{table.comment}列表" , notes = "查询$!{table.comment}列表") @PostMapping(value = "/getList") public Result<IPage<${entity}VO>> getList(@RequestBody PageDTO paramDTO) { return ${lowEntity}ServiceImpl.getList(paramDTO); } @ApiOperation(value = "批量删除$!{table.comment}" , notes = "批量删除$!{table.comment}") @Transactional(rollbackFor = Exception.class) @ActionLog(operateType = OperateTypeEnum.DELETE, detail = "批量删除$!{table.comment}") @DeleteMapping(value = "/deleteByIds") public Result<Void> deleteByIds(@RequestBody List<Long> ids) { ${lowEntity}ServiceImpl.removeByIds(ids); return ResultUtil.successResult(); } }
6、创建自动生成的模板文件存放目录:test/resouurces/template/dto.java.vm 文件
package ${package.Entity}.dto; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.io.Serializable; /** * <p> * $!{table.comment} * </p> * * @author ${author} * @since ${date} */ #if(${entityLombokModel}) @Data #end #if(${swagger2}) @ApiModel(value="${entity}DTO对象", description="$!{table.comment}") #end public class ${entity}DTO { #if(${entitySerialVersionUID}) private static final long serialVersionUID = 1L; #end @ApiModelProperty(value = "主键") private Long id; ## ---------- BEGIN 字段循环遍历 ---------- #foreach($field in ${table.fields}) #if("$!field.comment" != "") @ApiModelProperty(value = "${field.comment}") #end private ${field.propertyType} ${field.propertyName}; #end ## ---------- END 字段循环遍历 ---------- }
7、创建自动生成的模板文件存放目录:test/resouurces/template/vo.java.vm
package ${package.Entity}.vo; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.io.Serializable; /** * <p> * $!{table.comment} * </p> * * @author ${author} * @since ${date} */ #if(${entityLombokModel}) @Data #end #if(${swagger2}) @ApiModel(value="${entity}VO对象", description="$!{table.comment}") #end public class ${entity}VO implements Serializable { #if(${entitySerialVersionUID}) private static final long serialVersionUID = 1L; #end @ApiModelProperty(value = "主键") private Long id; ## ---------- BEGIN 字段循环遍历 ---------- #foreach($field in ${table.fields}) #if("$!field.comment" != "") @ApiModelProperty(value = "${field.comment}") #end private ${field.propertyType} ${field.propertyName}; #end ## ---------- END 字段循环遍历 ---------- }
8、创建MyBatisPlusGenerator.java 代码生成器这个类放在 项目的test包下
public static void main(String[] args) { // 需要构建一个 代码自动生成器 对象 AutoGenerator mpg = new AutoGenerator(); // 1、全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir").concat("/mybatis-plus"); gc.setOutputDir(projectPath+"/src/main/java"); gc.setAuthor("edwin"); gc.setOpen(false); gc.setFileOverride(true); // 是否覆盖 gc.setServiceName("%sService"); // 去Service的I前缀 gc.setIdType(IdType.ID_WORKER); gc.setDateType(DateType.ONLY_DATE); gc.setSwagger2(false); mpg.setGlobalConfig(gc); //2、设置数据源 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://8.129.215.115:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("root"); dsc.setDbType(DbType.MYSQL); mpg.setDataSource(dsc); dsc.setTypeConvert(new MySqlTypeConvert() { @Override public DbColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) { System.out.println("转换类型:" + fieldType); //tinyint转换成Boolean if (fieldType.toLowerCase().contains("tinyint")) { return DbColumnType.INTEGER; } return (DbColumnType) super.processTypeConvert(globalConfig, fieldType); } }); //3、包的配置 PackageConfig pc = new PackageConfig(); //pc.setModuleName("system");//如果有模块名就配置这个 pc.setParent("com.wei.shun.mybatis.plus"); pc.setEntity("entity"); pc.setMapper("mapper"); pc.setService("service"); pc.setController("controller"); mpg.setPackageInfo(pc); //4、策略配置 StrategyConfig strategy = new StrategyConfig(); //"tb_asset_category","tb_asset_disposal","tb_asset_disposal_detail" // ,"tb_asset_modify","tb_dept_dict_binding","tb_dictionary_field","tb_sys_dictionary" strategy.setInclude("my_user"); // 设置要映射的表名 strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setTablePrefix("tb_"); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setEntityLombokModel(true); // 自动lombok; strategy.setLogicDeleteFieldName("deleted"); // 自动填充配置 TableFill gmtCreate = new TableFill("create_time", FieldFill.INSERT); //TableFill createBy = new TableFill("create_by", FieldFill.INSERT); TableFill gmtModified = new TableFill("update_time", FieldFill.UPDATE); //TableFill modifiedBy = new TableFill("modified_by", FieldFill.UPDATE); ArrayList<TableFill> tableFills = new ArrayList<>(); tableFills.add(gmtCreate); //tableFills.add(createBy); tableFills.add(gmtModified); //tableFills.add(modifiedBy); strategy.setTableFillList(tableFills); // 乐观锁 strategy.setVersionFieldName("version"); strategy.setRestControllerStyle(true); strategy.setControllerMappingHyphenStyle(true); // localhost:8080/hello_id_2 //继承父类 strategy.setSuperEntityClass("com.wei.shun.mybatis.plus.pojo.OperationEntity"); //去掉序列化 //strategy.setEntitySerialVersionUID(false); //不生成的字段 strategy.setSuperEntityColumns("id","create_time","update_time","deleted","version"); mpg.setStrategy(strategy); mpg.execute(); //执行 }
9、创建MyBatisPlusGeneratorCustom.java 代码生成器这个类放在 项目的test包下
public static void main(String[] args) { // 需要构建一个 代码自动生成器 对象 AutoGenerator mpg = new AutoGenerator(); // 1、全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir").concat("/mybatis-plus"); gc.setOutputDir(projectPath + "/src/main/java"); gc.setAuthor("edwin"); gc.setOpen(false); gc.setFileOverride(true); // 是否覆盖 gc.setServiceName("%sService"); // 去Service的I前缀 gc.setIdType(IdType.ID_WORKER); gc.setDateType(DateType.ONLY_DATE); gc.setSwagger2(false); mpg.setGlobalConfig(gc); //2、设置数据源 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://8.129.215.115:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("root"); dsc.setDbType(DbType.MYSQL); mpg.setDataSource(dsc); dsc.setTypeConvert(new MySqlTypeConvert() { @Override public DbColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) { System.out.println("转换类型:" + fieldType); //tinyint转换成Boolean if (fieldType.toLowerCase().contains("tinyint")) { return DbColumnType.INTEGER; } return (DbColumnType) super.processTypeConvert(globalConfig, fieldType); } }); //3、包的配置 PackageConfig pc = new PackageConfig(); //pc.setModuleName("system");//如果有模块名就配置这个 pc.setParent("com.wei.shun.mybatis.plus"); pc.setEntity("entity"); pc.setMapper("mapper"); // pc.setService("service"); // pc.setController("controller"); mpg.setPackageInfo(pc); //4、策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setInclude("my_user"); // 设置要映射的表名 strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setTablePrefix("tb_"); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setEntityLombokModel(true); // 自动lombok; strategy.setLogicDeleteFieldName("deleted"); // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { Map<String, Object> map = new HashMap<String, Object>(); this.setMap(map); } }; List<FileOutConfig> focList = new ArrayList<FileOutConfig>(); //生成导出视图对象 //vo focList.add(new FileOutConfig("/templates/vo.java.vm") { @Override public String outputFile(TableInfo tableInfo) { return projectPath + "/src/main/java/" + pc.getParent().replace("." , "/") + "/domain/vo/" + tableInfo.getEntityName() + "VO.java"; } }); //dto focList.add(new FileOutConfig("/templates/dto.java.vm") { @Override public String outputFile(TableInfo tableInfo) { return projectPath + "/src/main/java/" + pc.getParent().replace("." , "/") + "/domain/dto/" + tableInfo.getEntityName() + "DTO.java"; } }); //controller focList.add(new FileOutConfig("/templates/controller.java.vm") { @Override public String outputFile(TableInfo tableInfo) { return projectPath + "/src/main/java/" + pc.getParent().replace("." , "/") + "/controller/" + tableInfo.getEntityName() + "Controller.java"; } }); //service focList.add(new FileOutConfig("/templates/service.java.vm") { @Override public String outputFile(TableInfo tableInfo) { return projectPath + "/src/main/java/" + pc.getParent().replace("." , "/") + "/service/" + tableInfo.getEntityName() + "Service.java"; } }); //serviceImpl focList.add(new FileOutConfig("/templates/serviceImpl.java.vm") { @Override public String outputFile(TableInfo tableInfo) { return projectPath + "/src/main/java/" + pc.getParent().replace("." , "/") + "/service/impl/" + tableInfo.getEntityName() + "ServiceImpl.java"; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // 自动填充配置 TableFill gmtCreate = new TableFill("create_time", FieldFill.INSERT); //TableFill createBy = new TableFill("create_by", FieldFill.INSERT); TableFill gmtModified = new TableFill("update_time", FieldFill.UPDATE); //TableFill modifiedBy = new TableFill("modified_by", FieldFill.UPDATE); ArrayList<TableFill> tableFills = new ArrayList<>(); tableFills.add(gmtCreate); //tableFills.add(createBy); tableFills.add(gmtModified); //tableFills.add(modifiedBy); strategy.setTableFillList(tableFills); // 乐观锁 strategy.setVersionFieldName("version"); strategy.setRestControllerStyle(true); strategy.setControllerMappingHyphenStyle(true); // localhost:8080/hello_id_2 //继承父类 strategy.setSuperEntityClass("com.wei.shun.mybatis.plus.pojo.OperationEntity"); //去掉序列化 //strategy.setEntitySerialVersionUID(false); //不生成的字段 strategy.setSuperEntityColumns("id","create_time","update_time","deleted","version"); mpg.setStrategy(strategy); mpg.execute(); //执行 }

浙公网安备 33010602011771号