前言
Mybatis-Plus(简称MP)是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生。这是官方给的定义,关于mybatis-plus的更多介绍及特性,可以参考mybatis-plus官网。那么它是怎么增强的呢?其实就是它已经封装好了一些crud方法,我们不需要再写xml了,直接调用这些方法就行,就类似于JPA。但是实话 楼主还是觉得JPA更好用一点.
废话 不多说 直接上代码:
1.pom依赖
<!--mybatisPlus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<!--使用generator生成代码需要的依赖 generator freemarker -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- 使用druid进行监控 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<!-- 日志-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
这里我们使用mybatis-plus-generator代码生成器可以生成 entity controller service serviceImpl mapper.xml等 稍后我们会介绍
2.application.yml配置
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
username: xxxx
password: xxxxx
url: jdbc:mysql://xxx:xxxx/xxxxxxx
#使用德鲁伊
type: com.alibaba.druid.pool.DruidDataSource
#配置druid
druid:
# 初始化大小,最小,最大
initial-size: 5
min-idle: 5
max-active: 20
# 配置获取连接等待超时的时间
max-wait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位毫秒
time-between-eviction-runs-millis: 60000
# 配置一个连接在池中最小生存时间
min-evictable-idle-time-millis: 300000
validation-query: SELECT 1 FROM sys_user
test-while-idle: true
test-on-borrow: false
test-on-return: false
# 打开 PSCache,并且指定每个连接上 PSCache 的大小
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
# 配置监控统计拦截的 Filter, SQL 去掉后监控界面无法统计,wall 用于防火墙
filters: stat,wall,log4j
# 通过 connection-properties 属性打开 mergeSql 功能;慢 SQL 记录
connection-properties: druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000
# 配置 DruidStatFilter
web-stat-filter:
enabled: true
url-pattern: /*
exclusions: .js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*
# 配置 DruidStatViewServlet
stat-view-servlet:
url-pattern: /druid/*
# IP 白名单,没有配置或者为空,则允许所有访问
allow: 127.0.0.1
# IP 黑名单,若白名单也存在,则优先使用
deny: 192.168.31.33
# 禁用 HTML 中 Reset All 按钮
reset-enable: false
# 登录用户名/密码
login-username: root
login-password: 123456
#配置mybatis
mybatis-plus:
global-config:
db-config:
id-type: auto
field-strategy: not_empty
table-underline: true
db-type: mysql
logic-delete-value: 1 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
#xxmapper.xml的位置
mapper-locations: classpath:/mapper/*.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
3.启动项目 测试 druid 是否配置成功
项目启动后 我们访问:http://127.0.0.1:8080/druid/login.html 弹出登录框 输入配置好的用户名密码 登录之后 如下图,说明我们已配置成功.
4.mybatis-plus-generator代码生成器
使用mybatis-plus-generator代码生成器 需要使用freemarker 所以我们加上了freemarker的依赖.
楼主这里只是个demo 实际应用 可以将其改造为批量生成的.使用过程中 修改 // TODO下的内容 即可
注意 生成之后的实体 可能需要修改 一些数据类型 java.util.Date 日期类型 生成的可能并不是Date类型
public class MysqlGenerator {
/**
* RUN THIS
*/
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");
// TODO 设置用户名
gc.setAuthor("an");
gc.setOpen(true);
// service 命名方式
gc.setServiceName("%sService");
// service impl 命名方式
gc.setServiceImplName("%sServiceImpl");
// 自定义文件命名,注意 %s 会自动填充表实体属性!
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(false);
mpg.setGlobalConfig(gc);
// TODO 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://xxxx:xxxx/xxxxx?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("xxxx");
dsc.setPassword("xxxxx");
mpg.setDataSource(dsc);
// TODO 包配置
PackageConfig pc = new PackageConfig();
//pc.setModuleName(scanner("模块名"));
pc.setParent("com.my.mybatis");
pc.setEntity("entity");
pc.setService("service");
pc.setServiceImpl("service.impl");
mpg.setPackageInfo(pc);
// 自定义需要填充的字段
List<TableFill> tableFillList = new ArrayList<>();
//如 每张表都有一个创建时间、修改时间
//而且这基本上就是通用的了,新增时,创建时间和修改时间同时修改
//修改时,修改时间会修改,
//虽然像Mysql数据库有自动更新几只,但像ORACLE的数据库就没有了,
//使用公共字段填充功能,就可以实现,自动按场景更新了。
//如下是配置
//TableFill createField = new TableFill("gmt_create", FieldFill.INSERT);
//TableFill modifiedField = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE);
//tableFillList.add(createField);
//tableFillList.add(modifiedField);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
List<FileOutConfig> focList = new ArrayList<>();
focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return projectPath + "/src/main/resources/mapper/"
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
mpg.setTemplate(new TemplateConfig().setXml(null));
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
// 设置逻辑删除键
strategy.setLogicDeleteFieldName("deleted");
// TODO 指定生成的bean的数据库表名
strategy.setInclude("userinfo");
//strategy.setSuperEntityColumns("id");
// 驼峰转连字符
strategy.setControllerMappingHyphenStyle(true);
mpg.setStrategy(strategy);
// 选择 freemarker 引擎需要指定如下加,注意 pom 依赖必须有!
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
运行main方法生成即可.
5.配置分页插件
这里面也可以定义sql效率分析的插件 我们用了druid 所以这里不再定义了
@Configuration
public class MyBatisPlusConfig {
private final static Logger logger = LoggerFactory.getLogger(MyBatisPlusConfig.class);
/**
* @description: 配置分页插件
*
* @author:
* @date:
* @param: []
* @return: com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
logger.debug("注册分页插件");
return new PaginationInterceptor();
}
/**
* mybatis-plus SQL执行效率插件【生产环境可以关闭】
*/
/*@Bean
public SqlExplainInterceptor sqlExplainInterceptor(){
SqlExplainInterceptor sqlExplainInterceptor = new SqlExplainInterceptor();
List<ISqlParser> sqlParserList = new ArrayList<>();
sqlParserList.add(new BlockAttackSqlParser());
sqlExplainInterceptor.setSqlParserList(sqlParserList);
return sqlExplainInterceptor;
}
*/
}
6.测试
@RestController
@RequestMapping("/userinfo")
public class UserinfoController {
@Autowired
UserinfoService userinfoService;
/**
* 测试插入
* @return
*/
@RequestMapping("/testinsert")
public boolean testinsert() {
Userinfo userinfo = new Userinfo();
userinfo.setUserName("testAn");
userinfo.setPassword("123456");
userinfo.setCreateDate(new Date());
return userinfoService.save(userinfo);
}
/**
* 根据id获取
* @param id
* @return
*/
@RequestMapping("/getUserById")
public Userinfo getUser(int id) {
Userinfo userinfo = userinfoService.getById(id);
return userinfo;
}
/**
* 测试获取列表
* @return
*/
@RequestMapping("/getUser")
public List getUser() {
List<Userinfo> list = userinfoService.list();
return list;
}
/**
* 测试分页
* @param pageNum
* @return
*/
@RequestMapping("/getUserPage")
public List getUserPage(int pageNum) {
int pageSize=5;
IPage<Userinfo> page = userinfoService.page(new Page<>(pageNum, pageSize));
List<Userinfo> records = page.getRecords();
return records;
}
}
生成的userinfoService提供了一些简单的 操作单表的方法 如果需要同时操作多个表 比如复杂的查询 还需要自己去定义方法 并在UserinfoMapper.xml做对应的配置.
生成的UserinfoMapper.xml在resource下的mapper文件夹下.
至此,springBoot对mybatiPlus整合完毕了 欢迎各位关注 评论 一起学习 一起进步