当前位置: 首页 > news >正文

Spring Boot集成Mybatis-Plus

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演示完毕

http://www.lryc.cn/news/113240.html

相关文章:

  • 梳理日常开发涉及的负载均衡
  • IEEE 754 浮点数运算
  • 阿里巴巴Java开发手册学习记录
  • 论文阅读---《Unsupervised T ransformer-Based Anomaly Detection in ECG Signals》
  • 收藏这8个好用的原型设计工具,轻松制作原型图
  • 王道计网 第四章笔记
  • C# Blazor 学习笔记(9):动态css/class绑定
  • vue3学习-Pinia状态管理
  • TextBrewer:融合并改进了NLP和CV中的多种知识蒸馏技术、提供便捷快速的知识蒸馏框架、提升模型的推理速度,减少内存占用
  • 乍得ECTN(BESC)申请流程
  • 【100天精通python】Day28:文件与IO操作_JSON文件处理
  • 配置两台数据库为主从数据库模式
  • linux允许root远程ssh登录
  • Baumer工业相机堡盟工业相机如何通过BGAPISDK获取相机接口数据吞吐量(C++)
  • Spring @Scheduled单线程单实例的坑
  • 7-数据结构-(带头节点)单链表的增删改查
  • 每天一道leetcode:剑指 Offer 53 - II. 0~n-1中缺失的数字(适合初学者二分查找)
  • 玩机搞机---安卓新机型payload.bin刷写救砖 无需专用线刷包
  • 配置固定二级子域名远程访问内网群晖NAS 7.X版 【内网穿透】——“cpolar内网穿透”
  • 【枚举】CF1706 C
  • uniapp-疫情应急管理系统学生端
  • FreeRTOS的线程间通信
  • Linux内存管理工作原理:
  • 【并发编程】ShenyuAdmin里面数据同步用到的无锁环形队列LMAX Disruptor并发框架
  • Nginx(2)
  • 二维数组的鞍点
  • go 内置函数copy()
  • Spring简述
  • 框框大学之——教育技术学
  • Android中的Apk 包体优化