Spring Boot集成Mybatis-Plus
1. pom.xml导包
<!--lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><!--mysql驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><!--druid连接池--><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.2.8</version></dependency><!--mybatis-plus--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.4.3.4</version></dependency><!--mybatis-plus代码生成器--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.5.1</version></dependency> <dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId></dependency> <dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId></dependency>
2.application.properties
spring.application.name=springboot-mybatis-plus-proxy
server.port=8088#datasource
spring.datasource.druid.url=jdbc:mysql://localhost:3308/demo?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
spring.datasource.druid.username=root
spring.datasource.druid.password=123456
spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.druid.initial-size=30
spring.datasource.druid.max-active=100
spring.datasource.druid.min-idle=10
spring.datasource.druid.max-wait=60000
spring.datasource.druid.time-between-eviction-runs-millis=60000
spring.datasource.druid.min-evictable-idle-time-millis=300000
spring.datasource.druid.validation-query=SELECT 1 FROM DUAL
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.test-on-borrow=false
spring.datasource.druid.test-on-return=false
spring.datasource.druid.filters=stat,wall#mybatis-plus config
mybatis-plus.configuration.map-underscore-to-camel-case=true
mybatis-plus.configuration.auto-mapping-behavior=full
mybatis-plus.mapper-locations=classpath*:mapper/**/*.Mapper.xml
3.启动类添加扫描mapper注解(在写完mapper文件或生成代码之后的mapper路径):
4.编写mapper以及相关controller、service相关代码,此处本人使用代码生成器生成MybatisPlusGenerator.java:
import java.util.Collections;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.querys.MySqlQuery;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.generator.keywords.MySqlKeyWordsHandler;public class MybatisPlusGenerator {private static final DataSourceConfig.Builder dataSourceConfig = new DataSourceConfig.Builder("jdbc:mysql://localhost:3308/demo?useUnicode=true&characterEncoding=utf-8&useSSL=false", "root", "123456").dbQuery(new MySqlQuery()).schema("Demonor-Proxy").typeConvert(new MySqlTypeConvert()).keyWordsHandler(new MySqlKeyWordsHandler());public static void main(String[] args) {String projectPath = System.getProperty("user.dir");String javaRoot = (projectPath+"/src/main/java").replaceAll("\\\\", "/");String resourcesRoot = (projectPath+"/src/main/resources").replaceAll("\\\\", "/"); String[] tables = new String[] {"user","role"};//System.out.println(outputDir);//代码生成器 FastAutoGenerator.create(dataSourceConfig).globalConfig((scanner,builder)->{builder.fileOverride().outputDir(javaRoot)//指定输出目录.author("Demonor")//作者名 .dateType(DateType.TIME_PACK)//时间策略,DateType.ONLY_DATE 默认值: DateType.TIME_PACK.commentDate("yyyy-MM-dd")//注释日期,默认值: yyyy-MM-dd.build();}).packageConfig((scanner,builder)->{ builder.parent("com.lee.demo.mybatisplus_datasourceproxy").controller("controller") //默认:controller.service("service") //默认:service.serviceImpl("service.impl") //默认:service.impl.entity("entity") //默认:entity.mapper("mapper") //默认:mapper .xml(null) //默认:mapper.xml目录.pathInfo(Collections.singletonMap(OutputFile.mapperXml, resourcesRoot+"/mapper")) //指定xml输出目录.build();}).templateConfig((scanner, builder)->{ //配置相关模板,不配置则按照默认builder.controller("/templates/controller.java").build();//不需要生成xml、controller、service、serviceImpl
// builder.mapperXml(null)
// .controller(null)
// .service(null)
// .serviceImpl(null)
// .entity(null)
// .mapper(null)
// .build();}).strategyConfig((scanner, builder)->{builder.enableCapitalMode().enableSkipView().addInclude(tables) //设置需要生成的表名.entityBuilder().enableLombok().naming(NamingStrategy.underline_to_camel).columnNaming(NamingStrategy.underline_to_camel).superClass("com.baomidou.mybatisplus.extension.activerecord.Model").build();}).templateEngine(new FreemarkerTemplateEngine()).execute();}}
这里我添加了自定义的Controller控制器模板,可以在依赖的mybatis-plus-generator.jar下复制相关templates:
package ${package.Controller};import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;/*** <p>* ${table.comment!} 前端控制器* </p>** @author ${author}* @since ${date}*/@RestController
@RequestMapping("<#if package.ModuleName?? && package.ModuleName != "">/${package.ModuleName}</#if>/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}</#if>")
<#if kotlin>
class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if>
<#else>
<#if superControllerClass??>
public class ${table.controllerName} extends ${superControllerClass} {
<#else>
public class ${table.controllerName} {
</#if>@GetMapping("index")public String index() {return "index";}}
</#if>
执行代码生成器,生成了user表和role表的相关代码,如图:
5.测试:
至此,Spring Boot集成Mybatis-Plus演示完毕