文章目录

  • Spring Boot —— Mybatis-Plus
    • 简介
    • 集成步骤
      • 加依赖
      • 加配置
      • 加注解
      • 使用生成器
      • 执行生成器
    • 测试的数据结构SQL
    • demo地址

Spring Boot —— Mybatis-Plus


简介

通过MybatisPlus实现CRUD

集成步骤

加依赖

<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>2.3</version>
</dependency>
<!-- freemarker -->
<dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId>
</dependency>
<!-- fastjson -->
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.70</version>
</dependency>

加配置

# mysql
spring:datasource:url: jdbc:mysql://localhost:3306/frank-dao-user?useUnicode=true&characterEncoding=utf8username: rootpassword: rootdriver-class-name: com.mysql.jdbc.Driver# mybaties-plus
mybatis-plus:mapper-locations: classpath:com/frank/mybatisplus/mapper/xml/*.xmltype-aliases-package: com.frank.mybatisplus.entityconfiguration:map-underscore-to-camel-case: true

加注解

没注解需要加

使用生成器


package com.frank.mybatisplus.config;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.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;/**** 代码生成器** @author cy* @version MpGenerator.java, v 0.1 2020年10月20日 15:40 cy Exp $*/
public class MpGenerator {public static void main(String[] args) {//        assert (false) : "代码生成属于危险操作,请确定配置后取消断言执行代码生成!";AutoGenerator mpg = new AutoGenerator();// 选择 freemarker 引擎,默认 Velocitympg.setTemplateEngine(new FreemarkerTemplateEngine());// 全局配置GlobalConfig gc = new GlobalConfig();gc.setAuthor("Cyoung");gc.setOutputDir("/Users/cy/project/spring-boot-frank/spring-boot-mybatis-plus/src/main/java");gc.setFileOverride(false);// 是否覆盖同名文件,默认是falsegc.setActiveRecord(true);// 不需要ActiveRecord特性的请改为falsegc.setEnableCache(false);// XML 二级缓存gc.setBaseResultMap(true);// XML ResultMapgc.setBaseColumnList(false);// XML columList/* 自定义文件命名,注意 %s 会自动填充表实体属性! */// gc.setMapperName("%sDao");// gc.setXmlName("%sDao");// gc.setServiceName("MP%sService");// gc.setServiceImplName("%sServiceDiy");// gc.setControllerName("%sAction");mpg.setGlobalConfig(gc);// 数据源配置DataSourceConfig dsc = new DataSourceConfig();dsc.setDbType(DbType.MYSQL);dsc.setTypeConvert(new MySqlTypeConvert() {// 自定义数据库表字段类型转换【可选】@Overridepublic DbColumnType processTypeConvert(String fieldType) {System.out.println("转换类型:" + fieldType);// 注意!!processTypeConvert 存在默认类型转换,如果不是你要的效果请自定义返回、非如下直接返回。return super.processTypeConvert(fieldType);}});dsc.setDriverName("com.mysql.jdbc.Driver");dsc.setUsername("root");dsc.setPassword("root");dsc.setUrl("jdbc:mysql://localhost:3306/frank-dao-user?useUnicode=true&characterEncoding=utf8");mpg.setDataSource(dsc);// 策略配置StrategyConfig strategy = new StrategyConfig();// strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意strategy.setTablePrefix(new String[] { "permission_", "role_", "user_", "user_group_", "user_login_" });// 此处可以修改为您的表前缀strategy.setNaming(NamingStrategy.nochange);// 表名生成策略strategy.setInclude(new String[] { "permission", "role", "user", "user_group", "user_login" }); // 需要生成的表// strategy.setExclude(new String[]{"test"}); // 排除生成的表// 自定义实体父类// strategy.setSuperEntityClass("com.baomidou.demo.TestEntity");// 自定义实体,公共字段// strategy.setSuperEntityColumns(new String[] { "test_id", "age" });// 自定义 mapper 父类// strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");// 自定义 service 父类// strategy.setSuperServiceClass("com.baomidou.demo.TestService");// 自定义 service 实现类父类// strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");// 自定义 controller 父类// strategy.setSuperControllerClass("com.baomidou.demo.TestController");// 【实体】是否生成字段常量(默认 false)// public static final String ID = "test_id";// strategy.setEntityColumnConstant(true);// 【实体】是否为构建者模型(默认 false)// public User setName(String name) {this.name = name; return this;}// strategy.setEntityBuilderModel(true);mpg.setStrategy(strategy);// 包配置PackageConfig pc = new PackageConfig();pc.setParent("com.frank.mybatisplus");// pc.setModuleName("test");mpg.setPackageInfo(pc);// 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】// InjectionConfig cfg = new InjectionConfig() {// @Override// public void initMap() {// Map<String, Object> map = new HashMap<String, Object>();// map.put("abc", this.getConfig().getGlobalConfig().getAuthor() +// "-mp");// this.setMap(map);// }// };//// // 自定义 xxList.jsp 生成// List<FileOutConfig> focList = new ArrayList<>();// focList.add(new FileOutConfig("/template/list.jsp.vm") {// @Override// public String outputFile(TableInfo tableInfo) {// // 自定义输入文件名称// return "D://my_" + tableInfo.getEntityName() + ".jsp";// }// });// cfg.setFileOutConfigList(focList);// mpg.setCfg(cfg);//// // 调整 xml 生成目录演示// focList.add(new FileOutConfig("/templates/mapper.xml.vm") {// @Override// public String outputFile(TableInfo tableInfo) {// return "/develop/code/xml/" + tableInfo.getEntityName() + ".xml";// }// });// cfg.setFileOutConfigList(focList);// mpg.setCfg(cfg);//// // 关闭默认 xml 生成,调整生成 至 根目录// TemplateConfig tc = new TemplateConfig();// tc.setXml(null);// mpg.setTemplate(tc);// 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,// 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称// TemplateConfig tc = new TemplateConfig();// tc.setController("...");// tc.setEntity("...");// tc.setMapper("...");// tc.setXml("...");// tc.setService("...");// tc.setServiceImpl("...");// 如上任何一个模块如果设置 空 OR Null 将不生成该模块。// mpg.setTemplate(tc);// 执行生成mpg.execute();// 打印注入设置【可无】// System.err.println(mpg.getCfg().getMap().get("abc"));}}

执行生成器

执行生成器main函数,就会生成对应的代码了,注意修改生成器的配置,以及yaml中的配置路径

测试的数据结构SQL

/*Navicat Premium Data TransferSource Server         : frank_mysqlSource Server Type    : MySQLSource Server Version : 50728Source Host           : localhostSource Database       : frank-dao-userTarget Server Type    : MySQLTarget Server Version : 50728File Encoding         : utf-8Date: 10/20/2020 16:01:33 PM
*/SET NAMES utf8;
SET FOREIGN_KEY_CHECKS = 0;-- ----------------------------
--  Table structure for `permission`
-- ----------------------------
DROP TABLE IF EXISTS `permission`;
CREATE TABLE `permission` (`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',`creator` bigint(20) unsigned NOT NULL COMMENT '创建者的用户ID',`description` varchar(64) COLLATE utf8_bin NOT NULL COMMENT '权限描述',`gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',`gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间',`modifier` bigint(20) unsigned NOT NULL COMMENT '最后修改者的用户ID',`status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '状态值,0表示已删除,1表示正常',PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;-- ----------------------------
--  Table structure for `role`
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',`creator` bigint(20) unsigned NOT NULL COMMENT '创建者的用户ID',`description` varchar(64) COLLATE utf8_bin NOT NULL COMMENT '角色描述',`gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',`gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间',`modifier` bigint(20) unsigned NOT NULL COMMENT '最后修改者的用户ID',`role_id` bigint(20) NOT NULL COMMENT '角色主键',`status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '状态值,0表示已删除,1表示正常',PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;-- ----------------------------
--  Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',`address` varchar(128) COLLATE utf8_bin DEFAULT NULL COMMENT '地址',`age` tinyint(3) DEFAULT NULL COMMENT '年龄',`creator` bigint(20) unsigned NOT NULL COMMENT '创建者的用户ID',`gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',`gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间',`modifier` bigint(20) unsigned NOT NULL COMMENT '最后修改者的用户ID',`signature_of_personality` varchar(128) COLLATE utf8_bin DEFAULT NULL COMMENT '个性签名',`status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '状态值,0表示已删除,1表示正常',`user_name` varchar(32) COLLATE utf8_bin NOT NULL COMMENT '用户名',PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;-- ----------------------------
--  Table structure for `user_group`
-- ----------------------------
DROP TABLE IF EXISTS `user_group`;
CREATE TABLE `user_group` (`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',`creator` bigint(20) unsigned NOT NULL COMMENT '创建者的用户ID',`description` varchar(64) COLLATE utf8_bin NOT NULL COMMENT '用户组描述',`gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',`gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间',`modifier` bigint(20) unsigned NOT NULL COMMENT '最后修改者的用户ID',`status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '状态值,0表示已删除,1表示正常',PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;-- ----------------------------
--  Table structure for `user_login`
-- ----------------------------
DROP TABLE IF EXISTS `user_login`;
CREATE TABLE `user_login` (`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',`account` varchar(32) COLLATE utf8_bin NOT NULL COMMENT '账号',`creator` bigint(20) unsigned NOT NULL COMMENT '创建者的用户ID',`gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',`gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间',`modifier` bigint(20) unsigned NOT NULL COMMENT '最后修改者的用户ID',`name` varchar(32) COLLATE utf8_bin NOT NULL COMMENT '名称',`passwd` varchar(32) COLLATE utf8_bin NOT NULL COMMENT '密码(加盐后MD5)',`status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '状态值,0表示已删除,1表示正常',`type` varchar(16) COLLATE utf8_bin NOT NULL COMMENT '类型(admin:管理员;operator:运营;scm:软件配置管理员(配置管理员))',PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;SET FOREIGN_KEY_CHECKS = 1;

demo地址

https://github.com/FrankCy/spring-boot-frank/tree/master/spring-boot-mybatis-plus

Spring Boot —— Mybatis-Plus(小试小刀)相关推荐

  1. Eclipse + Spring boot +mybatis + mysql

    Eclipse + Spring boot +mybatis + mysql 如题.使用Springboot 2.0 版本进行网页的开发.原理和优点很多博文已经讲过了,这里不再赘述.但是很多项目按照他 ...

  2. spring boot+mybatis整合

    LZ今天自己搭建了下Spring boot+Mybatis,比原来的Spring+SpringMVC+Mybatis简单好多.其实只用Spring boot也可以开发,但是对于多表多条件分页查询,Sp ...

  3. Spring Boot + Mybatis 实现动态数据源

    动态数据源 在很多具体应用场景的时候,我们需要用到动态数据源的情况,比如多租户的场景,系统登录时需要根据用户信息切换到用户对应的数据库.又比如业务A要访问A数据库,业务B要访问B数据库等,都可以使用动 ...

  4. Spring boot Mybatis 整合(注解版)

    之前写过一篇关于springboot 与 mybatis整合的博文,使用了一段时间spring-data-jpa,发现那种方式真的是太爽了,mybatis的xml的映射配置总觉得有点麻烦.接口定义和映 ...

  5. 在Spring Boot + Mybatis 中,使用@Repository失效

    在Spring Boot + Mybatis 中,使用@Repository失效 在springboot 中,给mapper的接口上加上@Repository,无法生成相应的bean,从而无法@Aut ...

  6. Spring Boot + Mybatis 快速整合

    引言 最近在工作结束后抽时间学习了一下mybatis的知识,因为之前有学习过,但是经久不用,也未曾踏实地整理,因此有所淡忘. super meeting会议管理系统是我厂最近开发的一套会议预约平台.持 ...

  7. Spring Boot MyBatis

    MyBatis简介 MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache 迁移到了google code,并且改名为MyBatis . 集成spring bo ...

  8. spring boot + mybatis + layui + shiro后台权限管理系统

    后台管理系统 版本更新 后续版本更新内容 链接入口: springboot + shiro之登录人数限制.登录判断重定向.session时间设置:https://blog.51cto.com/wyai ...

  9. 从零搭建一个 Spring Boot 开发环境!Spring Boot+Mybatis+Swagger2 环境搭建

    从零搭建一个 Spring Boot 开发环境!Spring Boot+Mybatis+Swagger2 环境搭建 本文简介 为什么使用Spring Boot 搭建怎样一个环境 开发环境 导入快速启动 ...

最新文章

  1. 在ASP.NET下实现数字和字符相混合的验证码
  2. cvGEMM()函数(矩阵通用乘法运算)
  3. npm无法安装node-sass的解决方法
  4. 动态修改数据窗口的数据源
  5. android中的broadcastReceiver
  6. Vboxmanage改动uuid报错的解决的方法
  7. initial、inherit、unset、revert和all
  8. Linux 文件的压缩与解压
  9. 对互联网中常见地图的坐标系探讨
  10. 持续集成工具集之二 Jenkins安装
  11. 一个自动化测试的案例之记事狗微博篇
  12. QlikView线图高亮选择尺寸
  13. 利用数组求前n个质数
  14. java安全证书配置
  15. 关于软件设计文档编写
  16. 【2018年11月12日】其他化学制品行业的股票估值和排名
  17. android中截屏功能实现,android代码实现截屏功能
  18. ospf在NBMA网络中的配置
  19. 均值回归,逆市中的投资机会
  20. [Python] 让AI来解决数独和数独谜题

热门文章

  1. 【观察】戴尔科技:“强平台+即服务”创新模式,重新定义混合多云之路
  2. 计算机操作试题word,计算机操作基础word练习题答案
  3. 贴片陶瓷天线原理 与 HFSS模型建立和仿真分析总结
  4. 【redis-02】redis的五种数据类型和对应的操作方法,补充RedisUtil模板
  5. 如何利用复制就好工具做英标和生词表--写给自己
  6. 智能建筑系统(中英)
  7. 关于QQ和360的口水战
  8. ftp爆破FunboxLunchbreaker
  9. Greenplum优化--SQL调优篇
  10. MPLS Virtual Private Network