MybatisPlus代码生成器和SpringBoot整合(原创)
一、代码生成器
直接上代码
1.新建一个maven项目
2.pom.xml
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wqky</groupId>
<artifactId>generator4mybatisPlus</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- mp依赖
mybatisPlus 会自动的维护Mybatis 以及MyBatis-spring相关的依赖
-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>2.3</version>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<!-- Apache velocity -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
<!-- sfl4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.7</version>
</dependency>
</dependencies>
</project>
3.建一个类
package com.wqky;
import com.baomidou.mybatisplus.enums.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
public class CodeGenerator {
public static void main(String[] args) {
//1. 全局配置
GlobalConfig config = new GlobalConfig();
// String path = "C:\\Users\\Flynn\\Desktop";// 生成路径,可设置为项目路径
String path = System.getProperty("user.dir")+"\\src\\main\\java";//设置为当前项目里面,刷新项目可见
String author = "wqky";//设置作者
config.setActiveRecord(true) // 是否支持AR模式
.setAuthor(author) // 作者
.setOutputDir(path) // 生成路径,可设置为项目路径
.setFileOverride(true) // 文件覆盖
.setIdType(IdType.ID_WORKER) // 主键策略
//①auto:数据库ID自增;
//②input:用户输入ID;
//③id_worker:全局唯一ID(64位),内容为空自动填充(默认);
//④uuid:全局唯一ID(32位),内容为空自动填充
.setServiceName("%sService") // 设置生成的service接口的名字的首字母是否为I,这样设置就没有I
.setBaseResultMap(true)
.setEnableCache(false)// XML 二级缓存
.setOpen(false)//生成后打开文件夹
.setBaseColumnList(true);
//2. 数据源配置
DataSourceConfig dsConfig = new DataSourceConfig();
dsConfig.setDbType(DbType.MYSQL) // 设置数据库类型
.setDriverName("com.mysql.jdbc.Driver")
.setUrl("jdbc:mysql://rm-bp1fb9sj8vk658l4xyo.mysql.rds.aliyuncs.com:3306/apollo_test")
.setUsername("wanqihulian")
.setPassword("wqhl@20180604");
//3. 策略配置
StrategyConfig stConfig = new StrategyConfig();
stConfig.setCapitalMode(true) //全局大写命名
.setDbColumnUnderline(true) // 指定表名 字段名是否使用下划线
.setNaming(NamingStrategy.underline_to_camel) // 数据库表映射到实体的命名策略
.setTablePrefix("t_") //以什么表开头
.setInclude("t_user"); // 生成的表
//4. 包名策略配置
PackageConfig pkConfig = new PackageConfig();
pkConfig.setParent("io.renren")//父包名
.setMapper("mapper")
.setService("service")
.setServiceImpl("service.impl")
.setController("controller")
.setEntity("entity")
.setXml("mapper");
//5. 整合配置
AutoGenerator ag = new AutoGenerator();
ag.setGlobalConfig(config)
.setDataSource(dsConfig)
.setStrategy(stConfig)
.setPackageInfo(pkConfig);
//6. 执行
ag.execute();
System.err.println(author+"攻城狮,您的代码自动生成完毕,路径为:"+path);
}
}
4.log4j.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
</layout>
</appender>
<logger name="java.sql">
<level value="debug" />
</logger>
<logger name="org.apache.ibatis">
<level value="info" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>
到此,MybatisPlus代码生成器完毕!!!
二、MybatisPlus和SpringBoot整合
直接上代码
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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.fly</groupId>
<artifactId>MybatisPlusSpringBoot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>MybatisPlusSpringBoot</name>
<description>Test MybatisPlus project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 热部署 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.Copy代码生成器的代码到SpringBoot项目中
3.配置好数据源和MybatisPlus相对应配置
mybatis-plus:
#在 Mapper 中有自定义方法
mapper-locations: classpath:mybatis/*.xml
#通过该属性可以给包中的类注册别名
type-aliases-package: com.wqky.entity
4.SQL执行效率插件和分页插件
package com.wqky.config;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
@EnableTransactionManagement
@Configuration
@MapperScan("com.wqky.service.*.mapper*")
public class MybatisPlusConfig {
/**
* SQL执行效率插件
*/
@Bean
public PerformanceInterceptor performanceInterceptor() {
return new PerformanceInterceptor()
.setFormat(true)//参数:format SQL SQL是否格式化,默认false
.setMaxTime(1000);//参数:maxTime SQL 执行最大时长,超过自动停止运行,有助于发现问题。
}
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
5.测试使用
package com.wqky.controller;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wqky.entity.User;
import com.wqky.service.UserService;
/**
* <p>
* 用户表 前端控制器
* </p>
*
* @author wqky
* @since 2018-11-12
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@ResponseBody
@GetMapping("/getUserById")
public User getUserById(String id) {
User user = userService.getById(id);
return user;
}
@ResponseBody
@GetMapping("/save")
public String save() {
User user = new User();
// user.setUserId(UUID.randomUUID().toString());
user.setAge(44);
user.setCreateTime(new Date());
userService.save(user);
return user.getUserId();
}
@ResponseBody
@GetMapping("/update")
public User update() {
User user = new User();
user.setUserId("1");
user.setUserName("flynn");
userService.updateById(user);
return user;
}
@ResponseBody
@GetMapping("/delete")
public void delete() {
userService.removeById("8958cb42-2ca5-4b6d-ae4e-3ca9135a14c8");
}
@ResponseBody
@GetMapping("/page")
public List<User> page(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.orderByDesc("create_time");
IPage<User> page = userService.page(new Page<>(0,3), wrapper);
List<User> list = page.getRecords();
return list;
}
}
到此,MybatisPlus和SpringBoot整合完毕!!!