SpringBoot整合MyBatis-Plus,实现代码生成器,逻辑删除,自动填充等功能
mybatis-plus简介:
Mybatis-Plus(简称MP)是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生。这是官方给的定义,关于mybatis-plus的更多介绍及特性,可以参考mybatis-plus官网。那么它是怎么增强的呢?其实就是它已经封装好了一些crud方法,我们不需要再写xml了,直接调用这些方法就行,就类似于JPA。
1.添加pom引用
<!--mybatis-plus 依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<!-- mybatis plus 代码生成器依赖 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.2.0</version>
</dependency>
<!-- 代码生成器模板 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.29</version>
</dependency>
2.yml配置
mybatis-plus:
mapper-locations: classpath:/mybatis-mappers/*Mapper.xml
typeAliasesPackage: com.tckj.wx.application.entity
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
logic-delete-value: 1 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
3.启动类
/**
* @author WCH
* @date 2020/6/11 11:49
*/
@SpringBootApplication
@MapperScan("com.tckj.wx.application.dao")
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
@Bean
public RestTemplate restTemplate(){
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new WxMappingJackson2HttpMessageConverter());
return restTemplate;
}
}
4.代码生成器
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
/**
* @author WCH
* @date 2020/6/23 17:07
*/
public class MysqlGenerator {
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("WCH");
gc.setOpen(false);
// service 命名方式
// gc.setServiceName("%sService");
// // service impl 命名方式
// gc.setServiceImplName("%sServiceImpl");
// gc.setMapperName("%sMapper");
// gc.setXmlName("%sMapper");
gc.setFileOverride(true);
gc.setActiveRecord(true);
// XML 二级缓存
gc.setEnableCache(false);
// XML ResultMap
gc.setBaseResultMap(true);
// XML columList
gc.setBaseColumnList(true);
gc.setSwagger2(true); //实体属性 Swagger2 注解
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
dsc.setUrl("jdbc:mysql://127.0.0.1:3306/user?characterEncoding=utf8");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.tckj.wx.application");
pc.setEntity("entity");
pc.setService("service");
pc.setMapper("dao");
pc.setServiceImpl("service.impl");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/mybatis-mappers/"
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
/*
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判断自定义文件夹是否需要创建
checkDir("调用默认方法创建的目录");
return false;
}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();
// 生成带有Swagger注解的实体类
templateConfig.setController("templates/controller.java");
//templateConfig.setEntity("templates/controller.java.ftl");
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity");
strategy.setEntityLombokModel(true);
strategy.setEntityTableFieldAnnotationEnable(true);
strategy.setRestControllerStyle(true);
// 公共父类
// strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");
// 写于父类中的公共字段
// strategy.setSuperEntityColumns("id");
strategy.setTablePrefix(new String[] { "tb_"});
strategy.setControllerMappingHyphenStyle(true);
mpg.setStrategy(strategy);
strategy.setInclude(new String[] { "tb_menu","tb_role","tb_user_role","tb_role_menu" });//表名
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
注意:代码生成器可以直接复制过去使用,根据自己实际情况修改数据库配置,包文件路径等, templateConfig.setController(“templates/controller.java”);这段代码是我自定义的controller模板,可以删除使用默认的
5.controller调用service层的增删改查
@ApiOperation(value = "添加组织机构")
@PostMapping("saveOrUpdate")
public ResultHelper saveOrUpdate(@RequestBody Organization organization){
boolean b = organizationService.saveOrUpdate(organization);
return ResultHelper.succeed(organization);
}
@ApiOperation(value = "查询所有机构")
@GetMapping("findList")
public ResultHelper findList(){
List<Organization> list = organizationService.list();
return ResultHelper.succeed(list);
}
@ApiOperation(value = "删除机构")
@ApiImplicitParam(name = "id",value = "机构id",required = false,dataType = "int",paramType = "query")
@GetMapping("deleteOrganizationById")
public ResultHelper deleteOrganizationById(@RequestParam Integer id){
boolean b = organizationService.removeById(id);
if (!b){
return ResultHelper.failed2Msg("删除失败");
}
return ResultHelper.succeed("删除成功");
}
注意:service都实现com.baomidou.mybatisplus.extension.service.IService接口,里面所有放法都可以使用,其他方法可以点进去学习一下
6.service调用dao层的增删改查
public int addOrganization(Organization organization){
int insert = organizationMapper.insert(organization);
return insert;
}
public int updateByIdOrganization(Organization organization){
int insert = organizationMapper.updateById(organization);
return insert;
}
public List<Organization> findList(){
return organizationMapper.selectList(null);
}
public int deleteOrganizationById(Integer id){
return organizationMapper.deleteById(id);
}
注意:dao都实现com.baomidou.mybatisplus.core.mapper.BaseMapper接口,里面所有放法都可以使用,其他方法可以点进去学习一下
7.分页需要使用mybatisplus自带插件,我使用的是配置类配置
/**
-
@author WCH
-
@date 2020/6/24 10:09
*/
@Configuration
public class MybatisPlusConfig {@Bean
public PaginationInterceptor getPaginationInterceptor(){
PaginationInterceptor paginationInterceptor=new PaginationInterceptor();
paginationInterceptor.setDialectType(“mysql”);
return paginationInterceptor;
}
}
配置成功之后就可以使用Page进行分页
列:
@ApiOperation(value = "机构分页查询")
@ApiImplicitParams({
@ApiImplicitParam(name = "current",value = "当前页数",required = false,dataType = "int",paramType = "query",defaultValue = "1"),
@ApiImplicitParam(name = "size",value = "每页显示数量",required = false,dataType = "int",paramType = "query",defaultValue = "10")
})
@GetMapping("findPage")
public ResultHelper findPage(@RequestParam(required = false,defaultValue = "1") Integer current,
@RequestParam(required = false,defaultValue = "10") Integer size){
IPage<Organization> page = organizationService.page(new Page<>(current, size));
return ResultHelper.succeed(page);
}
8.逻辑删除
@ApiModelProperty(value = "状态(0有效,1无效)")
@TableLogic
private Integer enabled;
在字段上面添加@TableLogic注解在yml中配置逻辑删除值
mybatis-plus:
db-config:
logic-delete-value: 1 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
配置成功之后调用查询方法会默认在sql后面加上where enable=0
9.自动填充
@ApiModelProperty(value = "创建时间")
@TableField(value = "create_time",fill = FieldFill.INSERT)
private Date createTime;
@ApiModelProperty(value = "修改时间")
@TableField(value = "update_time",fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
使用fill = FieldFill.INSERT_UPDATE设置填充类型
/**
* @author WCH
* @date 2020/6/24 11:16
*/
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
/*this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推荐使用)
this.fillStrategy(metaObject, "createTime", LocalDateTime.now()); // 也可以使用(3.3.0 该方法有bug请升级到之后的版本如`3.3.1.8-SNAPSHOT`)*/
/* 上面选其一使用,下面的已过时(注意 strictInsertFill 有多个方法,详细查看源码) */
this.setFieldValByName("createTime", new Date(), metaObject);
this.setFieldValByName("updateTime", new Date(), metaObject);
//this.setInsertFieldValByName("operator", "Jerry", metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
// this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推荐使用)
// this.fillStrategy(metaObject, "updateTime", LocalDateTime.now()); // 也可以使用(3.3.0 该方法有bug请升级到之后的版本如`3.3.1.8-SNAPSHOT`)
/* 上面选其一使用,下面的已过时(注意 strictUpdateFill 有多个方法,详细查看源码) */
//this.setFieldValByName("operator", "Tom", metaObject);
//this.setUpdateFieldValByName("operator", "Tom", metaObject);
this.setFieldValByName("updateTime", new Date(), metaObject);
}
}
自定义处理器实现MetaObjectHandler接口,完成填充逻辑