.MyBatisPlus简介
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
MybatisPlus特点
- 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
- 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
- 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
- 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
- 支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer2005、SQLServer 等多种数据库
- 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
- 支持 XML 热加载Mapper 对应的 XML支持热加载对于简单的 CRUD 操作甚至可以无 XML 启动
- 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
- 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
- 支持关键词自动转义:支持数据库关键词(order、key......)自动转义,还可自定义关键词
- 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
- 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
- 内置性能分析插件:可输出 Sql 语句以及其执行时间建议开发测试时启用该功能,能快速揪出慢查询
- 内置全局拦截插件:提供全表 delete,update 操作智能分析阻断也可自定义拦截规则,预防误操作
- 内置 Sql 注入剥离器:支持 Sql 注入剥离,有效预防 Sql 注入攻击
代码生成器
我们的微服务要生成代码,也要连接数据库,需要集成MyBatis-Plus,同时我们需要搭建一个代码生成器模块,它需要集成Mybatis-plus和Velocity
-
代码生成器模块:整合mybatis-plus,连接数据库,生成代码
-
微服务项目:整合mybatis-plus,链接数据库,做表的CRUD
导包
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<!--模板引擎-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
再resources创建配置文件
文件名 mybatiesplus-config-system.properties
#代码输出基本路径
OutputDir=F:/IDEA/workspace/yrstudy-edu/yrstudy-edu-service/yrstudy-edu-service-system/src/main/java
#mapper.xml SQL映射文件目录
OutputDirXml=F:/IDEA/workspace/yrstudy-edu/yrstudy-edu-service/yrstudy-edu-service-system/src/main/resources
#domain输出路径
OutputDirBase=F:/IDEA/workspace/yrstudy-edu/yrstudy-edu-pojo/yrstudy-edu-pojo-system/src/main/java
#作者名
author=
#基础包的路径
parent=xx.xx.xx
#四大金刚
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///yrstudy-system?serverTimezone=UTC
jdbc.user=xxx
jdbc.pwd=xxx
代码生成主类
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.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.*;
/**
* 生成代码的主类
*/
public class GenteratorCode {
public static void main(String[] args) throws InterruptedException {
//用来获取Mybatis-Plus.properties文件的配置信息
ResourceBundle rb = ResourceBundle.getBundle("mybatiesplus-config-system"); //不要加后缀
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(rb.getString("OutputDir"));
gc.setFileOverride(false);
gc.setActiveRecord(true);// 开启 activeRecord 模式
gc.setEnableCache(false);// XML 二级缓存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(false);// XML columList
gc.setAuthor(rb.getString("author"));
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setTypeConvert(new MySqlTypeConvert());
dsc.setDriverName(rb.getString("jdbc.driver"));
dsc.setUsername(rb.getString("jdbc.user"));
dsc.setPassword(rb.getString("jdbc.pwd"));
dsc.setUrl(rb.getString("jdbc.url"));
mpg.setDataSource(dsc);
// 表策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setTablePrefix(new String[] { "t_" });// 此处可以修改为您的表前缀
strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
strategy.setInclude(new String[]{
"表名字"
}); // 需要生成的表
mpg.setStrategy(strategy);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent(rb.getString("parent")); //cn.itsource.ymcc
pc.setController("web.controller"); //cn.itsource.ymcc.web.controller
pc.setService("service");
pc.setServiceImpl("service.impl");
pc.setEntity("domain");
pc.setMapper("mapper");
mpg.setPackageInfo(pc);
// 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-rb");
this.setMap(map);
}
};
List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
//controller的输出配置
focList.add(new FileOutConfig("/templates/controller.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
//合并好的内容输出到哪儿?
return rb.getString("OutputDir")+ "/xx/xx/xx/web/controller/" + tableInfo.getEntityName() + "Controller.java";
}
});
//query的输出配置
focList.add(new FileOutConfig("/templates/query.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return rb.getString("OutputDirBase")+ "/xx/xx/xx/query/" + tableInfo.getEntityName() + "Query.java";
}
});
// 调整 domain 生成目录演示
focList.add(new FileOutConfig("/templates/entity.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return rb.getString("OutputDirBase")+ "/xx/xx/xx/domain/" + tableInfo.getEntityName() + ".java";
}
});
// 调整 xml 生成目录演示
focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return rb.getString("OutputDirXml")+ "/xx/xx/xx/mapper/" + tableInfo.getEntityName() + "Mapper.xml";
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,
// 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称
TemplateConfig tc = new TemplateConfig();
tc.setService("/templates/service.java.vm");
tc.setServiceImpl("/templates/serviceImpl.java.vm");
tc.setMapper("/templates/mapper.java.vm");
tc.setEntity(null);
tc.setController(null);
tc.setXml(null);
// 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
mpg.setTemplate(tc);
// 执行生成
mpg.execute();
}
}
xx/xx/xx是自己的基础包路径
在resources下创建一个templates文件夹
里面有query模板和controller模板
controller模板
xx/xx/xx是自己的基础路径
package ${package.Controller};
import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
import xx.xx.xx.query.${entity}Query;
import xx.xx.xx.result.JSONResult;
import xx.xx.xx.result.PageList;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/${table.entityPath}")
public class ${entity}Controller {
@Autowired
public ${table.serviceName} ${table.entityPath}Service;
/**
* 保存和修改公用的
*/
@RequestMapping(value="/save",method= RequestMethod.POST)
public JSONResult saveOrUpdate(@RequestBody ${entity} ${table.entityPath}){
if(${table.entityPath}.getId()!=null){
${table.entityPath}Service.updateById(${table.entityPath});
}else{
${table.entityPath}Service.insert(${table.entityPath});
}
return JSONResult.success();
}
/**
* 删除对象
*/
@RequestMapping(value="/{id}",method=RequestMethod.DELETE)
public JSONResult delete(@PathVariable("id") Long id){
${table.entityPath}Service.deleteById(id);
return JSONResult.success();
}
/**
* 获取对象
*/
@RequestMapping(value = "/{id}",method = RequestMethod.GET)
public JSONResult get(@PathVariable("id")Long id){
return JSONResult.success(${table.entityPath}Service.selectById(id));
}
/**
* 查询所有对象
*/
@RequestMapping(value = "/list",method = RequestMethod.GET)
public JSONResult list(){
return JSONResult.success(${table.entityPath}Service.selectList(null));
}
/**
* 带条件分页查询数据
*/
@RequestMapping(value = "/pagelist",method = RequestMethod.POST)
public JSONResult page(@RequestBody ${entity}Query query){
Page<${entity}> page = new Page<${entity}>(query.getPage(),query.getRows());
page = ${table.entityPath}Service.selectPage(page);
return JSONResult.success(new PageList<${entity}>(page.getTotal(),page.getRecords()));
}
}
query模板
package xx.xx.xx.query;
import xx.xx.xx.query.BaseQuery;
/**
*
* @author ${author}
* @since ${date}
*/
public class ${table.entityName}Query extends BaseQuery{
}
最后运行,在运行前一点要把库和表创好,代码生成器是根据你的表反向生成的