Spring Boot集成Mybatis-Plus

Spring Boot集成Mybatis-Plus

1. pom.xml导包


		
            org.projectlombok
            lombok
        
        
        
        
            mysql
            mysql-connector-java
            runtime
        
        
        
            com.alibaba
            druid-spring-boot-starter
            1.2.8
        
        
        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.4.3.4
        
        
        
            com.baomidou
            mybatis-plus-generator
            3.5.1
         
        
            org.apache.commons
            commons-lang3
         
        
            org.freemarker
            freemarker
        

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路径):

Spring Boot集成Mybatis-Plus_第1张图片

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:

Spring Boot集成Mybatis-Plus_第2张图片

 Spring Boot集成Mybatis-Plus_第3张图片

package ${package.Controller};

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * 

* ${table.comment!} 前端控制器 *

* * @author ${author} * @since ${date} */ @RestController @RequestMapping("<#if package.ModuleName?? && package.ModuleName != "">/${package.ModuleName}/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}") <#if kotlin> class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}() <#else> <#if superControllerClass??> public class ${table.controllerName} extends ${superControllerClass} { <#else> public class ${table.controllerName} { @GetMapping("index") public String index() { return "index"; } }

执行代码生成器,生成了user表和role表的相关代码,如图:

Spring Boot集成Mybatis-Plus_第4张图片

5.测试:

Spring Boot集成Mybatis-Plus_第5张图片

Spring Boot集成Mybatis-Plus_第6张图片

 至此,Spring Boot集成Mybatis-Plus演示完毕

你可能感兴趣的:(spring,boot,mybatis-plus,mybatisplus)