SpringBoot集成Mybatis-plus并实现自动生成相关文件的示例代码
作者:荒城谋生 时间:2023-08-15 04:12:46
Mybatis-Plus是一个优秀的Mybatis增强工具,目前更新到3.1.1。Mybatis-Plus原生提供了很多单表操作的方法,极大简化了繁琐的curd的操作,同时又支持xml配置、自定义sql的编写。这篇文章介绍SpringBoot2集成Mybatis-Plus 3.1.0,同时介绍mybatis提供MysqlGenerator.java,你可以通过指定的数据库表生成对应的bean、mapper.xml、mapper.java、service.java、serviceImpl.java,甚至controller
1.pom.xml添加相关依赖,请注意版本号:
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.asiainfo</groupId>
<artifactId>rocketmq-producer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>rocketmq-producer</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!--Springboot集成mybatis-plus开始-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.5</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- 添加代码 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.7</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-filtering</artifactId>
<version>1.3</version>
</dependency>
</dependencies>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.yml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
2.application.yml
server:
port: 9999
spring:
application:
name: springboot-mybatisPlus
# database 部分注释
datasource:
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://localhost:3306/rocketmq?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconect=true&serverTimezone=GMT%2b8
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
filters: stat
maxActive: 50
initialSize: 0
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 1 from dual
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
removeAbandoned: true
removeAbandonedTimeout: 180
mybatis-plus:
global-config:
# 逻辑删除配置
db-config:
# 删除前
logic-not-delete-value: 1
# 删除后
logic-delete-value: 0
configuration:
map-underscore-to-camel-case: true
auto-mapping-behavior: full
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath:mybatisplus/mapper/*.xml
3.MyBatisPlusConfig.java
package com.asiainfo.crm.rocketmq.config;
import com.baomidou.mybatisplus.mapper.ISqlInjector;
import com.baomidou.mybatisplus.mapper.LogicSqlInjector;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
/**
* @author zhangpb
* @date 2021/12/15 14:13
* @Description:
*/
@Configuration
@Slf4j
public class MyBatisPlusConfig {
/**
* @description: 配置分页插件
*
* @author: zhangpb
* @date: 2019/1/15 10:17
* @param: []
* @return: com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
log.debug("注册分页插件");
return new PaginationInterceptor();
}
/**
* @description: SQL执行效率插件
*
* @author: zhangpb
* @date: 19-1-24 下午4:59
* @param: []
* @return: com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor
*/
@Bean
@Profile({"test"})// 设置 dev test 环境开启
public PerformanceInterceptor performanceInterceptor() {
return new PerformanceInterceptor();
}
/**
* 逻辑删除用,3.1.1之后的版本可不需要配置该bean,但项目这里用的是3.1.0的
*
* @author zhangpb
*
* @return com.baomidou.mybatisplus.core.injector.ISqlInjector
*/
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
}
4.MysqlGenerator.java
package com.asiainfo.crm.rocketmq.config;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
/**
* @author zhangpb
* @date 2021/12/15 14:14
* @Description:
*/
public class MysqlGenerator {
/**
* 每次只生成一张表的
* @param args
*/
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");
String projectPath = "E://java-workspace//rocketmq//rocketmq_space//rocketmq//rocketmq-producer";
gc.setOutputDir(projectPath + "\\src\\main\\java\\com\\asiainfo\\crm\\rocketmq\\cell");
// TODO 设置用户名
gc.setAuthor("zhangpb");
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://127.0.0.1:3306/rocketmq?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
mpg.setDataSource(dsc);
// TODO 包配置
PackageConfig pc = new PackageConfig();
//pc.setModuleName(scanner("模块名"));
// pc.setParent("com.zhangpb.demodruid");
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" + ".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("trade_coupon");
//strategy.setSuperEntityColumns("id");
// 驼峰转连字符
strategy.setControllerMappingHyphenStyle(true);
mpg.setStrategy(strategy);
// 选择 freemarker 引擎需要指定如下加,注意 pom 依赖必须有!
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
来源:https://www.cnblogs.com/zhangpb-up/p/15693258.html
标签:SpringBoot,Mybatis-plus,自动生成相关文件
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
PipedWriter和PipedReader源码分析_动力节点Java学院整理
2022-03-13 19:40:16
SpringBoot集成Redis—使用RedisRepositories详解
2023-09-04 08:55:59
![](https://img.aspxhome.com/file/2023/7/67017_0s.png)
Android编程实现Toast只显示最后一条的方法
2023-12-13 11:54:49
springboot +rabbitmq+redis实现秒杀示例
2022-04-21 02:29:28
![](https://img.aspxhome.com/file/2023/0/79940_0s.jpg)
C#实现简单的RSA非对称加密算法示例
2022-07-09 18:16:37
![](https://img.aspxhome.com/file/2023/1/106381_0s.jpg)
Android仿淘宝物流信息TimeLineView
2023-10-09 20:12:47
![](https://img.aspxhome.com/file/2023/6/111706_0s.jpg)
Android OKHttp使用简介
2022-05-01 06:28:38
一文带你搞懂Redis分布式锁
2021-09-26 12:56:14
![](https://img.aspxhome.com/file/2023/0/60920_0s.png)
MyBatis-Plus 自定义sql语句的实现
2022-12-24 23:16:16
Android开发获取重力加速度和磁场强度的方法
2022-05-27 23:07:09
![](https://img.aspxhome.com/file/2023/2/106022_0s.png)
java http token请求代码实例
2022-09-28 18:23:19
Android中ImageView实现选择本地图片并显示功能
2023-07-02 23:47:09
![](https://img.aspxhome.com/file/2023/2/138592_0s.gif)
Java之SpringBoot自定义配置与整合Druid
2022-09-28 06:23:06
![](https://img.aspxhome.com/file/2023/7/63007_0s.png)
java对指定目录下文件读写操作介绍
2023-01-26 11:53:17
Android中Glide加载圆形图片和圆角图片实例代码
2022-08-06 08:26:59
详解java8在Collection中新增加的方法removeIf
2022-06-04 20:51:45
Java日常练习题,每天进步一点点(50)
2022-05-30 13:56:08
Android编程实现全局获取Context及使用Intent传递对象的方法详解
2022-02-27 08:50:13
idea中使用(Revert Commit)图解
2023-03-22 18:45:58
![](https://img.aspxhome.com/file/2023/9/110659_0s.png)
Java数组扩容实现方法解析
2021-08-25 13:08:26