概览:使用MybatisPlus和它的代码生成整合SpringBoot可以实现快速的业务功能开发,具体步骤如下

一、添加依赖

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency> <!-- Mybait-Plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.0</version>
</dependency> <!-- Mybait-Plus代码生成 begin -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!-- Mybait-Plus代码生成 end -->

二、配置Mybaits-Plus

## MyBatis-Plus(如果用MyBatis只需去掉plus后缀)
mybatis-plus.mapper-locations=classpath:mapper/*.xml
mybatis-plus.type-aliases-package=cn.bounter.mybatisplus.entity
mybatis-plus.configuration.map-underscore-to-camel-case=true
mybatis-plus.configuration.use-column-label=true

三、配置代码生成器 MysqlGenerator

package cn.bounter.mybatisplus;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; import java.util.ArrayList;
import java.util.List;
import java.util.Scanner; /**
* <p>
* mysql 代码生成器演示例子
* </p>
*
*/
public class MysqlGenerator { /**
* <p>
* 读取控制台内容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
} /**
* RUN THIS
*/
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator(); // 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
// String modelName = "";
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("simon");
gc.setOpen(false);
gc.setFileOverride(true);// 是否覆盖同名文件,默认是false
gc.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false
gc.setEnableCache(false);// XML 二级缓存
gc.setBaseResultMap(false);// XML ResultMap
gc.setBaseColumnList(false);// XML columList
mpg.setGlobalConfig(gc); // 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://47.98.151.249:3306/bounter?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=PRC&useSSL=false");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("bounter");
dsc.setPassword("111111@Bounter"); mpg.setDataSource(dsc); // 包配置
PackageConfig pc = new PackageConfig();
// pc.setModuleName(scanner("模块名"));
pc.setParent("cn.bounter.mybatisplus");
pc.setController("controller");
pc.setEntity("entity");
pc.setMapper("dao");
pc.setService("service");
pc.setServiceImpl("service.impl" );
mpg.setPackageInfo(pc); // 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig); // 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
// strategy.setTablePrefix("t_");
strategy.setRestControllerStyle(true);
mpg.setStrategy(strategy);
// 选择 freemarker 引擎需要指定如下加,注意 pom 依赖必须有!
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
} }

四、生成代码,实现相应的Controller

package cn.bounter.mybatisplus.controller;

import cn.bounter.mybatisplus.common.PageReq;
import cn.bounter.mybatisplus.entity.Bounter;
import cn.bounter.mybatisplus.service.IBounterService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; /**
* <p>
* 前端控制器
* </p>
*
* @author simon
* @since 2019-05-09
*/
@RestController
@RequestMapping("/api/bounter")
public class BounterController { @Autowired
private IBounterService bounterService; /**
* 列表&搜索
* @param pageReq
* @return
*/
@PostMapping("/list")
public R<?> list(@RequestBody PageReq<Bounter> pageReq) {
Bounter bounter = pageReq.getReqObj() == null ? new Bounter() : pageReq.getReqObj();
return R.ok(bounterService.page(new Page<>(pageReq.getPageNum(), pageReq.getPageSize()),
Wrappers.<Bounter>lambdaQuery().eq(Bounter::getId, bounter.getId())));
} /**
* 详情
* @param id
* @return
*/
@GetMapping("/{id}")
public R<?> detail(@PathVariable Long id) {
return R.ok(bounterService.getById(id));
} /**
* 新增
* @param bounter
* @return
*/
@PostMapping
public R<?> save(@RequestBody Bounter bounter) {
return R.ok(bounterService.save(bounter));
} /**
* 修改
* @param bounter
* @return
*/
@PutMapping
public R<?> update(@RequestBody Bounter bounter){
return R.ok(bounterService.updateById(bounter));
} /**
* 删除
* @param id
* @return
*/
@DeleteMapping("/{id}")
public R<?> delete(@PathVariable Long id) {
return R.ok(bounterService.removeById(id));
}
}
 
到此为止就实现了一个完整业务的增删改查了,是不是觉得挺简单哉,那就赶快自己动手试试吧!
需要完整源码的见下面GIthub传送门:

SpringBoot整合MyBatis-Plus实现快速业务功能开发的更多相关文章

  1. SpringBoot整合Mybatis之项目结构、数据源

    已经有好些日子没有总结了,不是变懒了,而是我一直在奋力学习springboot的路上,现在也算是完成了第一阶段的学习,今天给各位总结总结. 之前在网上找过不少关于springboot的教程,都是一些比 ...

  2. SpringBoot整合Mybatis之进门篇

    已经有好些日子没有总结了,不是变懒了,而是我一直在奋力学习springboot的路上,现在也算是完成了第一阶段的学习,今天给各位总结总结. 之前在网上找过不少关于springboot的教程,都是一些比 ...

  3. 001 SringBoot基础知识及SpringBoot整合Mybatis

    1.原有Spring优缺点分析 (1)优点 Spring是Java企业版(Java Enterprise Edition,JEE,也称J2EE)的轻量级代替品.无需开发重量级的Enterprise J ...

  4. SpringBoot整合Mybatis【非注解版】

    接上文:SpringBoot整合Mybatis[注解版] 一.项目创建 新建一个工程 ​ 选择Spring Initializr,配置JDK版本 ​ 输入项目名 ​ 选择构建web项目所需的state ...

  5. SpringBoot系列七:SpringBoot 整合 MyBatis(配置 druid 数据源、配置 MyBatis、事务控制、druid 监控)

    1.概念:SpringBoot 整合 MyBatis 2.背景 SpringBoot 得到最终效果是一个简化到极致的 WEB 开发,但是只要牵扯到 WEB 开发,就绝对不可能缺少数据层操作,所有的开发 ...

  6. SpringBoot整合Mybatis完整详细版二:注册、登录、拦截器配置

    接着上个章节来,上章节搭建好框架,并且测试也在页面取到数据.接下来实现web端,实现前后端交互,在前台进行注册登录以及后端拦截器配置.实现简单的未登录拦截跳转到登录页面 上一节传送门:SpringBo ...

  7. 【SpringBoot系列1】SpringBoot整合MyBatis

    前言: 一直看网上说SpringBoot是解锁你的配置烦恼,一种超级快速开发的框架.一直挺想学的,正好最近也有时间,就学了下 这个是SpringBoot整合MyBatis的一个教程,用了阿里的drui ...

  8. SpringBoot整合mybatis、shiro、redis实现基于数据库的细粒度动态权限管理系统实例

    1.前言 本文主要介绍使用SpringBoot与shiro实现基于数据库的细粒度动态权限管理系统实例. 使用技术:SpringBoot.mybatis.shiro.thymeleaf.pagehelp ...

  9. SpringBoot 整合 Mybatis + Mysql——XML配置方式

    一.介绍 SpringBoot有两种方法与数据库建立连接,一种是集成Mybatis,另一种用JdbcTemplate,本文主要讨论集成Mybatis方式. SpringBoot整合Mybatis也有两 ...

随机推荐

  1. leetcode-mid-array-334 Increasing Triplet Subsequence-NO

    mycode   time limited class Solution(object): def increasingTriplet(self, nums): """ ...

  2. ORACLE Physical Standby 级联备库搭建

    搭建oracle 级联DG 现有架构:physical standby 一主二备,在此基础上,在主库下新建备库standby3.级联备库cascade 数据库版本 11.2.0.4 db_name=p ...

  3. vue-element-template模板项目使用记录(持续更新)

    1. npm 使用注意事项: a. node.js 使用 v8.16.0 版本,使用 v10 版本会有各种莫名其妙的报错 b. 开箱先改淘宝镜像: npm config set registry ht ...

  4. jenkins执行 pod install 报错 CocoaPods requires your terminal to be using UTF-8 encoding. Consider adding the following to ~/.profile:

    错误提示是: CocoaPods 需要终端使用utf-8编码 解决办法

  5. spring监听机制——观察者模式的应用

    使用方法 spring监听模式需要三个组件: 1. 事件,需要继承ApplicationEvent,即观察者模式中的"主题",可以看做一个普通的bean类,用于保存在事件监听器的业 ...

  6. jt获取鼠标指针的位置

    屏幕 screenX和screenY属性表示鼠标在整个显示屏的位置,从屏幕(而不是浏览器)的左上角开始计算的. 页面 pageX和pageY属性表示鼠标指针在这个页面的位置.页面的顶部可能在可见区域之 ...

  7. [转载]Parsing X.509 Certificates with OpenSSL and C

    Parsing X.509 Certificates with OpenSSL and C Zakir Durumeric | October 13, 2013 While OpenSSL has b ...

  8. PHP 实现并发-进程控制 PCNTL

    参考 基于PCNTL的PHP并发编程 PCNTL 是 PHP 中的一组进程控制函数,可以用来 fork(创建)进程,传输控制信号等. 在PHP中,进程控制支持默认关闭.编译时通过 --enable-p ...

  9. C# datatable 导出到Excel

    datatable导出到Excel /// <summary> /// 将DataTable导出为Excel文件(.xls) /// </summary> /// <pa ...

  10. 二维数组中的查找-剑指 offerP38

    题目: 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数. 解题思路:<剑指 ...