基本使用
mybatis-plus依赖
<!-- mybatis-plus开始 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- mybatis-plus结束 -->
application.properties配置
#下面这些内容是为了让MyBatis映射
#指定Mybatis的Mapper文件
mybatis.mapper-locations=classpath:mappers/*xml
#指定Mybatis的实体目录
mybatis.type-aliases-package=com.example.demo.entity
# 数据库配置
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai
#spring.datasource.username=root
#spring.datasource.password=123456
测试数据
CREATE TABLE `p_msg` (
`id` int NOT NULL AUTO_INCREMENT,
`tt` varchar(3000) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`author` varchar(255) DEFAULT NULL,
`tags` varchar(255) DEFAULT NULL,
`insert_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`pubtime` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8mb3;
INSERT INTO `test`.`p_msg`(`id`, `tt`, `author`, `tags`, `insert_time`, `pubtime`) VALUES (1, '“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”', 'Albert Einstein', 'change', '2022-10-07 10:32:00', NULL);
INSERT INTO `test`.`p_msg`(`id`, `tt`, `author`, `tags`, `insert_time`, `pubtime`) VALUES (2, '“It is our choices, Harry, that show what we truly are, far more than our abilities.”', 'J.K. Rowling', 'abilities', '2022-10-07 10:32:00', NULL);
INSERT INTO `test`.`p_msg`(`id`, `tt`, `author`, `tags`, `insert_time`, `pubtime`) VALUES (3, '“There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.”', 'Albert Einstein', 'inspirational', '2022-10-07 10:32:00', NULL);
代码生成器:
MyBatisPlusGenerator
使用mybatisplus-generator可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。
依赖
<!-- mybatis-plus代码生成器开始 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.1</version>
</dependency>
<!-- mybatis-plus代码生成器结束 -->
工具类
package com.example.demo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.example.demo.common.BaseController;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class MyBatisPlusGenerator {
// 处理 all 情况
protected static List<String> getTables(String tables) {
return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
}
public static void main(String[] args) {
FastAutoGenerator.create("jdbc:mysql://localhost:3306/test", "root", "123456")
// 全局配置
.globalConfig((scanner, builder) -> {
builder.author(scanner.apply("请输入作者名称?")).fileOverride();
builder.enableSwagger();
builder.outputDir("D:\\tmp\\demo\\src\\main\\java");
})
// 包配置
.packageConfig((scanner, builder) -> {
builder.parent(scanner.apply("请输入包名?"))
// .entity("entity.flink_web")
// .service("service.flink_web")
// .serviceImpl("service.impl.flink_web")
// .mapper("mapper.flink_web")
// .xml("mapper.xml")
// .controller("controller.flink_web")
// .pathInfo(Collections.singletonMap(OutputFile.mapperXml, "D:\\tmp\\demo\\src\\main\\resources\\flink_web"))
;
})
// 策略配置
.strategyConfig((scanner, builder) -> {
//controller配置
builder.addInclude(MyBatisPlusGenerator.getTables(scanner.apply("请输入表名,多个英文逗号分隔?所有输入 all")))
.controllerBuilder()
.enableRestStyle()
.enableHyphenStyle()
.superClass(BaseController.class)
.build();
//service配置
builder.serviceBuilder()
.formatServiceFileName("%sService")
.formatServiceImplFileName("%sServiceImp")
.build();
//entity的策略配置
builder.entityBuilder()
.enableLombok()
.enableTableFieldAnnotation()
.versionColumnName("version")
.logicDeleteColumnName("is_delete")
.columnNaming(NamingStrategy.underline_to_camel)
.idType(IdType.ASSIGN_ID)
.formatFileName("%sEntity")
.build();
})
.execute();
}
}
全局配置
new GlobalConfig.Builder()
.fileOverride()
.outputDir("")//输出目录
.author("wmj")
.enableKotlin()
.enableSwagger()
.dateType(DateType.TIME_PACK)
.commentDate("yyyy-MM-dd")
.build();
注意:
1.fileOverride这个参数要注意,因为各个模块代码是一起生成的,不要因为后期更新某些字段而覆盖了其他模块!
2.outputDir就是Sources代码的绝对路径。
3.enableSwagger如果不希望引入swagger这里可以设置成false。
包配置
new PackageConfig.Builder()
.moduleName("sys")
.entity("po")
.service("service")
.serviceImpl("service.impl")
.mapper("mapper")
.xml("mapper.xml")
.controller("controller")
.other("other")
.pathInfo(Collections.singletonMap(OutputFile.mapperXml, "D://"))
.build();
注意:
1.pathInfo就是xml文件的位置,一般在sources的xml下面。
2.parent就是所生成代码的父包名,比如如果parent配置为:com.example.demo,后面所成成代码的位置就是在父包之下,如果service的配置是service.test,那么最终生成的service的包就是com.example.demo.service.test。
3.如果项目中,需要操作多个数据库中的表,习惯性的是entity,service,serviceImpl等后面加上库名,比如针对test2库,不过这也仅是个人的使用习惯
new PackageConfig.Builder()
.entity("entity.test2")
.service("service.test2")
.serviceImpl("service.impl.test2")
.mapper("mapper.test2")
.xml("mapper.xml.test2")
.controller("controller.test2")
.pathInfo(Collections.singletonMap(OutputFile.mapperXml, "D:\tmp\demo\src\main\resources\test2"))
.build();
模板配置
new TemplateConfig.Builder()
.disable(TemplateType.ENTITY)
.entity("/templates/entity.java")
.service("/templates/service.java")
.serviceImpl("/templates/serviceImpl.java")
.mapper("/templates/mapper.java")
.mapperXml("/templates/mapper.xml")
.controller("/templates/controller.java")
.build();
策略配置-总
new StrategyConfig.Builder()
.enableCapitalMode()
.enableSkipView()
.disableSqlFilter()
.likeTable(new LikeTable("USER"))
.addInclude("t_simple")
.addTablePrefix("t_", "c_")
.addFieldSuffix("_flag")
.build();
entity策略配置
new StrategyConfig.Builder()
.entityBuilder()
.superClass(BaseEntity.class)
.disableSerialVersionUID()
.enableChainModel()
.enableLombok()
.enableRemoveIsPrefix()
.enableTableFieldAnnotation()
.enableActiveRecord()
.versionColumnName("version")
//.versionPropertyName("version")
.logicDeleteColumnName("deleted")
//.logicDeletePropertyName("deleteFlag")
.naming(NamingStrategy.no_change)
.columnNaming(NamingStrategy.underline_to_camel)
.addSuperEntityColumns("id", "created_by", "created_time", "updated_by", "updated_time")
.addIgnoreColumns("age")
.addTableFills(new Column("create_time", FieldFill.INSERT))
.addTableFills(new Property("updateTime", FieldFill.INSERT_UPDATE))
.idType(IdType.AUTO)
.formatFileName("%sEntity")
.build();
controller策略配置
new StrategyConfig.Builder()
.controllerBuilder()
.superClass(BaseController.class)
.enableHyphenStyle()
.enableRestStyle()
.formatFileName("%sAction")
.build();
service策略配置
new StrategyConfig.Builder()
.serviceBuilder()
.superServiceClass(BaseService.class)
.superServiceImplClass(BaseServiceImpl.class)
.formatServiceFileName("%sService")
.formatServiceImplFileName("%sServiceImp")
.build();
来源:MybatisPlus-Generator_mybatis-plus-generator-CSDN博客
MybatisPlus插件
Tool-->Config Database
Tool-->Code Generator
注意:
1.上面的数据表可以多选。
2.各个模块的代码可以自由勾选。
来源:MyBatisPlus IDEA 代码生成插件:提升开发效率的利器-百度开发者中心
Mapper的基本使用
验证代码在spring-boot.start-test中完成
<!-- spring test-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
基本crud
注意:
1.增删改直接用mapper操作,如果有查询条件需要构造QueryWrapper
package com.example.demo;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.entity.PMsgEntity;
import com.example.demo.mapper.PMsgMapper;
import org.junit.jupiter.api.Test;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
@SpringBootTest
@MapperScan("com.example.demo.mapper")
class MybatisPlusLearnApplicationTests {
@Autowired
private PMsgMapper pMsgMapper;
//写一个pMsgMapper的插入测试用例
@Test
public void testInsert() {
PMsgEntity pMsgEntity = new PMsgEntity();
pMsgEntity.setTags("hello world");
// 定义字符串
String dateString = "2024-01-01";
// 创建 DateTimeFormatter,指定日期格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 解析字符串为 LocalDate
LocalDate date = LocalDate.parse(dateString, formatter);
// 将 LocalDate 转换为 LocalDateTime,设置时间为午夜
LocalDateTime dateTime = LocalDateTime.of(date, LocalTime.MIDNIGHT);
pMsgEntity.setInsertTime(dateTime);
pMsgMapper.insert(pMsgEntity);
}
@Test
@DS("test")
public void testSelect() {
List<PMsgEntity> pMsgEntities = pMsgMapper.selectList(null);
System.out.printf("cccc===", pMsgEntities.size());
}
//我需要写一个测试,用pMsgMapper从数据表中取出id=1的数据
@Test
public void testSelectById(){
PMsgEntity pMsgEntity = pMsgMapper.selectById(1);
System.out.printf("cccc===", pMsgEntity);
}
//我需要写一个测试类,使用pMsgMapper从数据表中查询insert_time在2024-01-01到2024-01-02之间的所有数据
@Test
public void testSelectByInsertTime(){
QueryWrapper<PMsgEntity> wrapper=new QueryWrapper<>();
wrapper.gt("insert_time","2022-10-07");
wrapper.orderByAsc("id");
//根据wrapper查询数据
List<PMsgEntity> pMsgEntities = pMsgMapper.selectList(wrapper);
//打印结果
System.out.printf("cccc===", pMsgEntities);
}
//测试翻页
@Test
public void testPage(){
// 假设这是你的 Mapper 接口实例
// 设置翻页参数
int currentPage = 2; // 当前页数
int pageSize = 2; // 每页记录数
// 创建翻页对象并设置排序条件
Page<PMsgEntity> page = new Page<>(currentPage, pageSize);
page.addOrder(OrderItem.asc("id"));
QueryWrapper<PMsgEntity> wrapper=new QueryWrapper<>();
pMsgMapper.selectPage(page,wrapper);
System.out.printf("page=====>>>>>", page);
}
@Test
public void applyTest(){
QueryWrapper<PMsgEntity> queryWrapper=new QueryWrapper<>();
queryWrapper.apply("id={0} or id={1}",1,2);
List<PMsgEntity> pMsgEntities = pMsgMapper.selectList(queryWrapper);
System.out.println("pMsgEntities = " + pMsgEntities);
}
}
apply使用
apply方法用于在查询条件中拼接sql片段,这在进行复杂链表查询时候非常有用。但是使用的时候要注意sql防止sql注入。
@Test
public void applyTest(){
QueryWrapper<PMsgEntity> queryWrapper=new QueryWrapper<>();
queryWrapper.apply("id={0} or id={1}",1,2);
List<PMsgEntity> pMsgEntities = pMsgMapper.selectList(queryWrapper);
System.out.println("pMsgEntities = " + pMsgEntities);
}
@Test
public void applyInTest(){
QueryWrapper<PMsgEntity> queryWrapper=new QueryWrapper<>();
Integer[] ids={1,2,3};
StringJoiner joiner = new StringJoiner(", ");
for (Integer id : ids) {
joiner.add(id+"");
}
queryWrapper.apply("id in ({0})",joiner.toString());
List<PMsgEntity> pMsgEntities = pMsgMapper.selectList(queryWrapper);
System.out.println("pMsgEntities = " + pMsgEntities);
}
@Test
public void applyLikeTest(){
QueryWrapper<PMsgEntity> queryWrapper=new QueryWrapper<>();
queryWrapper.apply("author like CONCAT('%', {0}, '%') ","ber");
List<PMsgEntity> pMsgEntities = pMsgMapper.selectList(queryWrapper);
System.out.println("pMsgEntities = " + pMsgEntities);
}
@Test
public void selectApplyTest(){
QueryWrapper<PMsgEntity> queryWrapper=new QueryWrapper<>();
queryWrapper.select("id,author")
.apply("author like CONCAT('%', {0}, '%') ","ber");
List<PMsgEntity> pMsgEntities = pMsgMapper.selectList(queryWrapper);
System.out.println("pMsgEntities = " + pMsgEntities);
}
swagger集成
版本兼容:
SPB(SpringBoot) 2.7 以下 + Swagger-ui 和Swagger2 2.9.2
SPB(SpringBoot) 2.7 往上 + springfox-boot-starter(3.0.0包括Swagger-ui 和Swagger2 3.0.0)
maven依赖:
本次demo的spring版本是2.7.6,所以swagger使用3.0.0
<!--swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
application.properties配置
#swagger配置需要 spring.mvc.pathmatch.matching-strategy=ant_path_matcher
configuration引入
import org.springframework.context.annotation.Configuration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SpringFoxConfiguration {
}
访问地址:http://localhost:8080/swagger-ui/
测试demo
controller注解:
@RestController
@RequestMapping("/consul-entity")
@Api(tags = "项目前的环境测试接口")
public class ConsulController {
@ApiOperation(value = "测试Swagger")
@GetMapping("test1")
public String hello1(String name){
return "hello "+name;
}
@ApiOperation(value = "测试Swagger")
@GetMapping("test3")
public PMsgEntity hello3( PMsgEntity pMsgEntity){
return pMsgEntity;
}
@ApiOperation(value = "测试Swagger")
@GetMapping("test2")
public PMsgEntity hello2(@RequestBody PMsgEntity pMsgEntity){
return pMsgEntity;
}
}
注意:
1.默认Parameters输入是表单形式
2.如果输入是@RequestBody注解了,则Parameters输入是json
model注解
package com.example.demo.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* <p>
*
* </p>
*
* @author cjh
* @since 2024-10-01
*/
@Getter
@Setter
@TableName("p_msg")
public class PMsgEntity implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@ApiModelProperty("tt")
@TableField("tt")
private String tt;
@ApiModelProperty("作者")
@TableField("author")
private String author;
@ApiModelProperty("标签")
@TableField("tags")
private String tags;
@ApiModelProperty("入库时间")
@TableField("insert_time")
private LocalDateTime insertTime;
@ApiModelProperty("发布时间")
@TableField("pubtime")
private LocalDateTime pubtime;
}
来源:
一篇搞定SpringBoot任意版本集成Swagger各种版本_springboot对应swagger版本-CSDN博客
多数据源
依赖
<!--多数据源-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
数据库配置
spring.datasource.dynamic.primary=test spring.datasource.dynamic.strict=false spring.datasource.dynamic.datasource.test.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.dynamic.datasource.test.url=jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai spring.datasource.dynamic.datasource.test.username=root spring.datasource.dynamic.datasource.test.password=123456 spring.datasource.dynamic.datasource.test2.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.dynamic.datasource.test2.url=jdbc:mysql://localhost:3306/test2?serverTimezone=Asia/Shanghai spring.datasource.dynamic.datasource.test2.username=root spring.datasource.dynamic.datasource.test2.password=123456
如果是yml配置
spring:
datasource:
dynamic:
primary: master
strict: false
datasource:
master:
url: jdbc:mysql://xx.xx.xx.xx:3306/dynamic
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
slave_1:
url: jdbc:mysql://xx.xx.xx.xx:3307/dynamic
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
slave_2:
url: ENC(xxxxx)
username: ENC(xxxxx)
password: ENC(xxxxx)
driver-class-name: com.mysql.jdbc.Driver
使用@DS切换数据源
@Service
@DS("test2")
public class UserServiceImpl implements UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
@DS("slave_1")
public List selectByCondition() {
return jdbcTemplate.queryForList("select * from user where age >10");
}
}
来源:多数据源支持 | MyBatis-Plus
分页
config配置
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("com.example.demo.mapper")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
}
使用样例
@Test
public void testPage(){
// 假设这是你的 Mapper 接口实例
// 设置翻页参数
int currentPage = 2; // 当前页数
int pageSize = 2; // 每页记录数
// 创建翻页对象并设置排序条件
Page<PMsgEntity> page = new Page<>(currentPage, pageSize);
page.addOrder(OrderItem.asc("id"));
QueryWrapper<PMsgEntity> wrapper=new QueryWrapper<>();
pMsgMapper.selectPage(page,wrapper);
System.out.printf("page=====>>>>>", page);
}
BaseController
我们平时在用MybatisPlus
作为开发的时候,虽然好用,但是大多数都在对 dao 层面的增删改查,所以打算自己抽取一套在 controller 层的功能出来。只要继承一个BaseController
类,就可以拥有增删改查,查询列表,分页查询,排序,带参数查询,统计数量。
git地址
https://gitee.com/bobchen_os/mybatis-plus-pro
相关代码都被统一放在common包中,如果需要使用,直接复制这个包就可以。
注意:
本项目基于MybatisPlusPro的改进点在于在PageParamDto中新增了query_info字段,用于传递查询条件。
使用步骤
1.代码生成时候,controller生成策略配置:.superClass(BaseController.class)
2.生产的代码没有指定泛型参数,加上泛型参数
package com.example.demo.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.common.BaseController;
import com.example.demo.common.dto.PageParamDto;
import com.example.demo.common.util.ResponseUtils;
import com.example.demo.entity.Sites;
import com.example.demo.service.ISitesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* </p>
*
* @author cjh
* @since 2024-10-02
*/
@RestController
@RequestMapping("/sites")
@Api(tags="site管理")
public class SitesController extends BaseController<ISitesService, Sites> {
@ApiOperation("page3查")
@PostMapping("/page3")
public ResponseUtils rangeBySql(@RequestBody PageParamDto<Sites> pageParamDto){
QueryWrapper<Sites> wrapper=new QueryWrapper<>();
queryWrapApply(wrapper,pageParamDto.getQuery_info());
return page(pageParamDto,wrapper);
}
@ApiOperation("page4查")
@PostMapping("/page4")
public ResponseUtils rangeBySql2(@RequestBody PageParamDto<Sites> pageParamDto){
String sql = "id>{0} and name={1}";
QueryWrapper<Sites> wrapper=new QueryWrapper<>();
BaseController.applyQueryWrapper(wrapper,sql,pageParamDto.getQuery_info());
return page(pageParamDto,wrapper);
}
}
3.启动项目,访问swagger:http://localhost:8080/swagger-ui/,会看到自动绑定了相关curd的接口。
4.query_info有2中使用方式,1种是sql和参数一起传入,这种是为了更加灵活,但是不推荐使用
还有一种是,是不输入sql,只能输入指定的参数,约定参数名前有序号_的前缀,前面的序号就是传入mysql的参数顺序。这种虽然不够灵活,但是使用起来更加安全。
基于BaseController改进模板
观察发现,如果希望大规模使用BaseController,可以设置模板自动生成相关代码。
使用
1.设置idea自动导入
2.controller配置superclass
.superClass(BaseController.class)
3.调整模板配置
controller.java.vm
位置:resources/templates
package ${package.Controller};
import org.springframework.web.bind.annotation.RequestMapping;
#if(${restControllerStyle})
import org.springframework.web.bind.annotation.RestController;
#else
import org.springframework.stereotype.Controller;
#end
#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end
/**
* <p>
* $!{table.comment} 前端控制器
* </p>
*
* @author ${author}
* @since ${date}
*/
#if(${restControllerStyle})
@RestController
#else
@Controller
#end
@RequestMapping("#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end")
#if(${kotlin})
class ${table.controllerName}#if(${superControllerClass}) : ${superControllerClass}()#end
#else
#if(${superControllerClass})
public class ${table.controllerName} extends ${superControllerClass} <${table.serviceName}, ${entity}> {
#else
public class ${table.controllerName} {
#end
}
#end
修改的位置:
4.生成器调整模板配置:
//4、模版配置 .templateConfig(builder -> { builder.controller("/templates/controller.java.vm"); })
来源:MybatisPlus-Generator自定义模版生成CRUD、DTO、VO、Convert等 (qq.com)
MyBatisPlusGenerator
package com.example.demo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.example.demo.common.BaseController;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class MyBatisPlusGenerator {
// 处理 all 情况
protected static List<String> getTables(String tables) {
return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
}
public static void main(String[] args) {
FastAutoGenerator.create("jdbc:mysql://localhost:3306/test", "root", "123456")
// 全局配置
.globalConfig((scanner, builder) -> {
builder.author(scanner.apply("请输入作者名称?")).fileOverride();
builder.enableSwagger();
builder.outputDir("D:\\tmp\\demo\\src\\main\\java");
})
// 包配置
.packageConfig((scanner, builder) -> {
builder.parent(scanner.apply("请输入包名?"))
// .entity("entity.flink_web")
// .service("service.flink_web")
// .serviceImpl("service.impl.flink_web")
// .mapper("mapper.flink_web")
// .xml("mapper.xml")
// .controller("controller.flink_web")
// .pathInfo(Collections.singletonMap(OutputFile.mapperXml, "D:\\tmp\\demo\\src\\main\\resources\\flink_web"))
;
})
//4、模版配置
.templateConfig(builder -> {
builder.controller("/templates/controller.java.vm");
})
// 策略配置
.strategyConfig((scanner, builder) -> {
//controller配置
builder.addInclude(MyBatisPlusGenerator.getTables(scanner.apply("请输入表名,多个英文逗号分隔?所有输入 all")))
.controllerBuilder()
.superClass(BaseController.class)
.enableRestStyle()
.enableHyphenStyle()
.superClass(BaseController.class)
.build();
//service配置
builder.serviceBuilder()
.formatServiceFileName("%sService")
.formatServiceImplFileName("%sServiceImp")
.build();
//entity的策略配置
builder.entityBuilder()
.enableLombok()
.enableTableFieldAnnotation()
.versionColumnName("version")
.logicDeleteColumnName("is_delete")
.columnNaming(NamingStrategy.underline_to_camel)
.idType(IdType.ASSIGN_ID)
.formatFileName("%sEntity")
.build();
})
.execute();
}
}
maven依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.7.6</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mybatis-plus开始 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- mybatis-plus结束 -->
<!-- mybatis-plus代码生成器开始 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.1</version>
</dependency>
<!-- mybatis-plus代码生成器结束 -->
<!--多数据源-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<!--swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<!-- spring test-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.16</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<configuration>
<mainClass>com.example.demo.DemoApplication</mainClass>
<skip>true</skip>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
application.properties
# 应用服务 WEB 访问端口
server.port=8080
#下面这些内容是为了让MyBatis映射
#指定Mybatis的Mapper文件
mybatis.mapper-locations=classpath:mappers/*xml
#指定Mybatis的实体目录
mybatis.type-aliases-package=com.example.demo.entity
# 数据库配置
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai
#spring.datasource.username=root
#spring.datasource.password=123456
#swagger配置需要
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
spring.datasource.dynamic.primary=test
spring.datasource.dynamic.strict=false
spring.datasource.dynamic.datasource.test.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.dynamic.datasource.test.url=jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai
spring.datasource.dynamic.datasource.test.username=root
spring.datasource.dynamic.datasource.test.password=123456
spring.datasource.dynamic.datasource.haodf.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.dynamic.datasource.haodf.url=jdbc:mysql://localhost:3306/haodf?serverTimezone=Asia/Shanghai
spring.datasource.dynamic.datasource.haodf.username=root
spring.datasource.dynamic.datasource.haodf.password=123456
# MyBatis-Plus 配置
# 指定MyBatis-Plus使用StdOutImpl作为日志实现,这意味着SQL日志将输出到标准输出(通常是控制台)。
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl