Skip to content

Commit 91e45e7

Browse files
zihongzihong
zihong
authored and
zihong
committed
feat: springboot mybatis plus 的应用
1 parent 9786467 commit 91e45e7

File tree

18 files changed

+546
-2
lines changed

18 files changed

+546
-2
lines changed

README.md

+6
Original file line numberDiff line numberDiff line change
@@ -147,5 +147,11 @@ SpringBoot 使用Gradle做依赖管理时,配置打包docker镜像的DEMO
147147
#### SpringBoot-Thrift-Client(Thrift 实现远程服务调用 客戶端)
148148
SpringBoot基于Thrift实现RPC客户端
149149

150+
#### SpringBoot-Mybatis-Plus
151+
SpringBoot 集成Mybatis Plus,内置乐观锁,crud,自动填充示例
152+
153+
#### SpringBoot-Alibaba-Sentinel
154+
SpringBoot 使用 Alibaba开源监控平台 sentinel 示例
155+
150156
#### SpringBoot-Utils
151157
各项目的依赖模块,存放一些工具类

SpringBoot-Mybatis-Plus/.gitignore

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
HELP.md
2+
.gradle
3+
build/
4+
!gradle/wrapper/gradle-wrapper.jar
5+
!**/src/main/**
6+
!**/src/test/**
7+
8+
### STS ###
9+
.apt_generated
10+
.classpath
11+
.factorypath
12+
.project
13+
.settings
14+
.springBeans
15+
.sts4-cache
16+
17+
### IntelliJ IDEA ###
18+
.idea
19+
*.iws
20+
*.iml
21+
*.ipr
22+
out/
23+
24+
### NetBeans ###
25+
/nbproject/private/
26+
/nbbuild/
27+
/dist/
28+
/nbdist/
29+
/.nb-gradle/
30+
31+
### VS Code ###
32+
.vscode/

SpringBoot-Mybatis-Plus/README.md

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
### SpringBoot 集成 Mybatis Plus 示例
2+
3+
#### 简介
4+
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
5+
#### 特性
6+
7+
无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
8+
损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
9+
强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
10+
支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
11+
支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
12+
支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
13+
支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
14+
内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
15+
内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
16+
分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
17+
内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
18+
内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作
19+
20+
21+
详情可参考Mybatis plus 官网,链接:
22+
https://mp.baomidou.com/guide/quick-start.html

SpringBoot-Mybatis-Plus/build.gradle

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
dependencies {
2+
compile project(':SpringBoot-Utils')
3+
compile 'com.baomidou:mybatis-plus-boot-starter:3.0.1'
4+
//代码生成器
5+
compile 'com.baomidou:mybatis-plus-generator:3.0.1'
6+
compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.46'
7+
compile 'org.apache.velocity:velocity-engine-core:2.1'
8+
testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '2.0.4.RELEASE'
9+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
package com.dashuai.learning.mybatisplus;
2+
3+
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
4+
import com.baomidou.mybatisplus.core.toolkit.StringPool;
5+
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
6+
import com.baomidou.mybatisplus.generator.AutoGenerator;
7+
import com.baomidou.mybatisplus.generator.InjectionConfig;
8+
import com.baomidou.mybatisplus.generator.config.*;
9+
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
10+
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
11+
12+
import java.util.ArrayList;
13+
import java.util.List;
14+
import java.util.Scanner;
15+
16+
public class CodeGenerator {
17+
/**
18+
* <p>
19+
* 读取控制台内容
20+
* </p>
21+
*/
22+
public static String scanner(String tip) {
23+
Scanner scanner = new Scanner(System.in);
24+
System.out.println("请输入" + tip + ":");
25+
if (scanner.hasNext()) {
26+
String ipt = scanner.next();
27+
if (StringUtils.isNotEmpty(ipt)) {
28+
return ipt;
29+
}
30+
}
31+
throw new MybatisPlusException("请输入正确的" + tip + "!");
32+
}
33+
34+
public static void main(String[] args) {
35+
// 代码生成器
36+
AutoGenerator mpg = new AutoGenerator();
37+
38+
// 全局配置
39+
GlobalConfig gc = new GlobalConfig();
40+
String projectPath = System.getProperty("user.dir");
41+
gc.setOutputDir(projectPath + "/SpringBoot-Mybatis-Plus/src/main/java");
42+
gc.setAuthor("zoey");
43+
gc.setOpen(false);
44+
// gc.setSwagger2(true); 实体属性 Swagger2 注解
45+
mpg.setGlobalConfig(gc);
46+
47+
// 数据源配置
48+
DataSourceConfig dsc = new DataSourceConfig();
49+
dsc.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8");
50+
// dsc.setSchemaName("public");
51+
dsc.setDriverName("com.mysql.jdbc.Driver");
52+
dsc.setUsername("root");
53+
dsc.setPassword("root");
54+
mpg.setDataSource(dsc);
55+
56+
// 包配置
57+
PackageConfig pc = new PackageConfig();
58+
pc.setModuleName(scanner("模块名"));
59+
pc.setParent("com.dashuai.learning.mybatisplus");
60+
mpg.setPackageInfo(pc);
61+
62+
// 自定义配置
63+
InjectionConfig cfg = new InjectionConfig() {
64+
@Override
65+
public void initMap() {
66+
// to do nothing
67+
}
68+
};
69+
70+
// 如果模板引擎是 freemarker
71+
// String templatePath = "/templates/mapper.xml.ftl";
72+
// 如果模板引擎是 velocity
73+
String templatePath = "/templates/mapper.xml.vm";
74+
75+
// 自定义输出配置
76+
List<FileOutConfig> focList = new ArrayList<>();
77+
// 自定义配置会被优先输出
78+
focList.add(new FileOutConfig(templatePath) {
79+
@Override
80+
public String outputFile(TableInfo tableInfo) {
81+
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
82+
return projectPath + "/SpringBoot-Mybatis-Plus/src/main/resources/mapper/" + pc.getModuleName()
83+
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
84+
}
85+
});
86+
/*
87+
cfg.setFileCreate(new IFileCreate() {
88+
@Override
89+
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
90+
// 判断自定义文件夹是否需要创建
91+
checkDir("调用默认方法创建的目录");
92+
return false;
93+
}
94+
});
95+
*/
96+
cfg.setFileOutConfigList(focList);
97+
mpg.setCfg(cfg);
98+
99+
// 配置模板
100+
TemplateConfig templateConfig = new TemplateConfig();
101+
102+
// 配置自定义输出模板
103+
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
104+
// templateConfig.setEntity("templates/entity2.java");
105+
// templateConfig.setService();
106+
// templateConfig.setController();
107+
108+
templateConfig.setXml(null);
109+
mpg.setTemplate(templateConfig);
110+
111+
// 策略配置
112+
StrategyConfig strategy = new StrategyConfig();
113+
strategy.setNaming(NamingStrategy.underline_to_camel);
114+
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
115+
// strategy.setSuperEntityClass("com.dashuai.learning.mybatisplus.common.BaseEntity");
116+
strategy.setEntityLombokModel(true);
117+
strategy.setRestControllerStyle(true);
118+
// 公共父类
119+
// strategy.setSuperControllerClass("com.dashuai.learning.mybatisplus.common.BaseController");
120+
// 写于父类中的公共字段
121+
strategy.setSuperEntityColumns("id");
122+
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
123+
strategy.setControllerMappingHyphenStyle(true);
124+
strategy.setTablePrefix(pc.getModuleName() + "_");
125+
mpg.setStrategy(strategy);
126+
// mpg.setTemplateEngine(new FreemarkerTemplateEngine());
127+
mpg.execute();
128+
}
129+
130+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.dashuai.learning.mybatisplus;
2+
3+
import org.mybatis.spring.annotation.MapperScan;
4+
import org.springframework.boot.SpringApplication;
5+
import org.springframework.boot.autoconfigure.SpringBootApplication;
6+
7+
@SpringBootApplication
8+
@MapperScan("com.dashuai.learning.mybatisplus.user.mapper")
9+
public class MybatisPlusApplication {
10+
11+
public static void main(String[] args) {
12+
SpringApplication.run(MybatisPlusApplication.class, args);
13+
}
14+
15+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.dashuai.learning.mybatisplus.config;
2+
3+
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
4+
import org.apache.ibatis.reflection.MetaObject;
5+
import org.slf4j.Logger;
6+
import org.slf4j.LoggerFactory;
7+
import org.springframework.stereotype.Component;
8+
9+
import java.util.Date;
10+
11+
/**
12+
* Created in 2019.12.12
13+
* 配置自动填充
14+
*
15+
* @author Liaozihong
16+
*/
17+
@Component
18+
public class MyMetaObjectHandler implements MetaObjectHandler {
19+
private static final Logger LOGGER = LoggerFactory.getLogger(MyMetaObjectHandler.class);
20+
21+
@Override
22+
public void insertFill(MetaObject metaObject) {
23+
LOGGER.info("start insert fill ....");
24+
this.setFieldValByName("createAt", new Date(), metaObject);
25+
}
26+
27+
@Override
28+
public void updateFill(MetaObject metaObject) {
29+
LOGGER.info("start update fill ....");
30+
this.setFieldValByName("updateAt", new Date(), metaObject);
31+
}
32+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.dashuai.learning.mybatisplus.config;
2+
3+
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
4+
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
5+
import org.springframework.context.annotation.Bean;
6+
import org.springframework.context.annotation.Configuration;
7+
8+
@Configuration
9+
public class MybatisPlusConfig {
10+
/**
11+
* 乐观锁配置,记得需要使用乐观锁的实体添加@Version,系统会自动帮你添加version
12+
*
13+
* @return
14+
*/
15+
@Bean
16+
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
17+
return new OptimisticLockerInterceptor();
18+
}
19+
20+
/**
21+
* 可配置多租户信息等
22+
*
23+
* @return
24+
*/
25+
@Bean
26+
public PaginationInterceptor paginationInterceptor() {
27+
PaginationInterceptor page = new PaginationInterceptor();
28+
//设置方言类型
29+
page.setDialectType("mysql");
30+
return page;
31+
}
32+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.dashuai.learning.mybatisplus.user.controller;
2+
3+
4+
import org.springframework.web.bind.annotation.RestController;
5+
6+
/**
7+
* <p>
8+
* 前端控制器
9+
* </p>
10+
*
11+
* @author zoey
12+
* @since 2019-12-12
13+
*/
14+
@RestController
15+
public class UserController {
16+
17+
}
18+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.dashuai.learning.mybatisplus.user.entity;
2+
3+
import com.baomidou.mybatisplus.annotation.FieldFill;
4+
import com.baomidou.mybatisplus.annotation.TableField;
5+
import com.baomidou.mybatisplus.annotation.TableId;
6+
import com.baomidou.mybatisplus.annotation.Version;
7+
import lombok.Data;
8+
import lombok.experimental.Accessors;
9+
10+
import java.util.Date;
11+
12+
/**
13+
* <p>
14+
*
15+
* </p>
16+
*
17+
* @author zoey
18+
* @since 2019-12-12
19+
*/
20+
@Accessors(chain = true)
21+
@Data
22+
public class User {
23+
24+
private static final long serialVersionUID = 1L;
25+
26+
27+
@TableId
28+
private Long id;
29+
/**
30+
* 姓名
31+
*/
32+
private String name;
33+
34+
/**
35+
* 年龄
36+
*/
37+
private Integer age;
38+
39+
/**
40+
* 邮箱
41+
*/
42+
private String email;
43+
44+
@TableField(fill = FieldFill.INSERT)
45+
private Date createAt;
46+
47+
@TableField(fill = FieldFill.UPDATE)
48+
private Date updateAt;
49+
50+
@Version
51+
private Integer version;
52+
53+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.dashuai.learning.mybatisplus.user.mapper;
2+
3+
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
4+
import com.dashuai.learning.mybatisplus.user.entity.User;
5+
6+
/**
7+
* <p>
8+
* Mapper 接口
9+
* </p>
10+
*
11+
* @author zoey
12+
* @since 2019-12-12
13+
*/
14+
public interface UserMapper extends BaseMapper<User> {
15+
16+
17+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package com.dashuai.learning.mybatisplus.user.service;
2+
3+
import com.baomidou.mybatisplus.extension.service.IService;
4+
import com.dashuai.learning.mybatisplus.user.entity.User;
5+
6+
/**
7+
* <p>
8+
* 服务类
9+
* </p>
10+
*
11+
* @author zoey
12+
* @since 2019-12-12
13+
*/
14+
public interface IUserService extends IService<User> {
15+
16+
}

0 commit comments

Comments
 (0)