SpringBoot从入门到精通教程(二十五)- Mybatis-Plus快速开发框架用法

需求背景

Springboot集成:Mybatis-Plus快速开发框架用法

框架介绍

MyBatis-Plus 荣获【2018年度开源中国最受欢迎的中国软件】 TOP5,为简化开发而生

框架有以下三个特点:

1. 润物无声
只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑。

2. 效率至上
只需简单配置,即可快速进行 CRUD 操作,从而节省大量时间。

3. 丰富功能
热加载、代码生成、分页、性能分析等功能一应俱全。

当前最新版本

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>3.2.0</version>
</dependency>

准备工作

1. 提前准备好一个mysql连接库,导入db.sql文件内容

代码演示

1. 项目目录结构

2. pom.xml依赖组件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>com.md</groupId>
		<artifactId>spring-boot2-parent</artifactId>
		<version>0.0.1-SNAPSHOT</version>
		<relativePath>../pom.xml</relativePath>
	</parent>

	<artifactId>spring-boot2-mybatis-plus</artifactId>
	<packaging>jar</packaging>

	<name>spring-boot2-mybatis-plus</name>
	<description>Spring Boot, MVC, Rest API for App</description>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.8</java.version>
		<swagger.version>2.9.2</swagger.version>
		<mybatisplus.version>3.2.0</mybatisplus.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<!-- 构建成可运行的Web项目 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib-ext-spring</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
		</dependency>
		<!-- swagger集成 -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>${swagger.version}</version>
		</dependency>
		<!-- 默认swagger-ui -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>${swagger.version}</version>
		</dependency>
		<!-- 更易用第三方swagger-ui组件 -->
		<dependency>
			<groupId>com.github.xiaoymin</groupId>
			<artifactId>swagger-bootstrap-ui</artifactId>
			<version>1.9.3</version>
		</dependency>
		<!-- mybatis-plus集成 -->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-generator</artifactId>
			<version>${mybatisplus.version}</version>
		</dependency>
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>${mybatisplus.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-freemarker</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

3. 自动生成代码类

CodeGenerator.java,相关注释说明已有

package com.md.demo.auto;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

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.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
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.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

/**
 * 代码生成器
 * 
 * @author Minbo
 *
 */
public class CodeGenerator {

	/**
	 * RUN THIS
	 */
	public static void main(String[] args) {
		AutoGenerator mpg = new AutoGenerator();

		// 全局配置
		GlobalConfig gc = new GlobalConfig();
		String projectPath = System.getProperty("user.dir");
		gc.setOutputDir(projectPath + "/src/main/java");
		gc.setAuthor(scanner("开发者"));
		gc.setOpen(false);
		// 是否启动Swagger2
		gc.setSwagger2(true);
		// 默认不覆盖,如果文件存在,将不会再生成,配置true就是覆盖
		gc.setFileOverride(true);
		mpg.setGlobalConfig(gc);

		// 数据源配置
		DataSourceConfig dsc = new DataSourceConfig();
		dsc.setUrl("jdbc:mysql://localhost:33061/test?useUnicode=true&useSSL=false&characterEncoding=utf8");
		dsc.setDriverName("com.mysql.jdbc.Driver");
		dsc.setUsername("root");
		dsc.setPassword("hs2019");
		mpg.setDataSource(dsc);

		// 包配置
		PackageConfig pc = new PackageConfig();
		pc.setModuleName(scanner("模块名"));
		pc.setParent("com.md.demo").setEntity("entity.vo").setMapper("dao");
		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/" + pc.getModuleName() + "/"
						+ 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.setRestControllerStyle(true);

		strategy.setInclude(scanner("表名"));
		strategy.setControllerMappingHyphenStyle(true);
		strategy.setTablePrefix(pc.getModuleName() + "_");

		mpg.setStrategy(strategy);
		// 选择 freemarker 引擎需要指定如下加,注意 pom 依赖必须有!
		mpg.setTemplateEngine(new FreemarkerTemplateEngine());

		mpg.execute();
	}

	/**
	 * <p>
	 * 读取控制台内容
	 * </p>
	 */
	@SuppressWarnings("resource")
	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 + "!");
	}
}

4. 运行上面的类

控制台会提示你输入开发者名,模块名,表名,此框架会自动给你生成相应的类

控制台输出:

项目最终图:

通过此框架,能节省大量类似重复的操作事项等

5. 相关类代码展示

比如:实体类Myuser.java(这里用到了lombok组件,不再需要写getter/setter方法)

6. 新增访问接口

MyuserController.java

package com.md.demo.test.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.md.demo.test.entity.vo.Myuser;
import com.md.demo.test.service.IMyuserService;
import com.md.demo.util.JsonResult;
import com.md.demo.util.ResultCode;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author MMinbo
 * @since 2019-10-25
 */
@RestController
@RequestMapping("/test/myuser")
public class MyuserController {

	@Autowired
	private IMyuserService myuserService;

	@ApiOperation(value = "获得用户列表", notes = "", httpMethod = "GET")
	@RequestMapping(value = "/listUser")
	public JsonResult listUser() {
		// 框架自带的方法
		List<Myuser> list = this.myuserService.list(null);
		return new JsonResult(ResultCode.SUCCESS, list);
	}

	@ApiOperation(value = "根据用户名获得用户记录", notes = "名称不能为空", httpMethod = "GET")
	@ApiImplicitParam(dataType = "string", name = "name", value = "用户名", required = true)
	@RequestMapping(value = "/getUserByName")
	public JsonResult getUserByName(String name) {
		// 自定义的方法
		Myuser myuser = this.myuserService.getUserByName(name);
		return new JsonResult(ResultCode.SUCCESS, myuser);
	}
}

7. 在线接口测试

启动项目,访问swagger2地址(Swagger2集成教程用法):

http://localhost:9090/doc.html

完整源码下载

我的Github源码地址:

https://github.com/hemin1003/spring-boot-study/tree/master/spring-boot2-study/spring-boot2-parent/spring-boot2-mybatis-plus

注意事项

1. Application.java启动类中,需要配置@MapperScan注解,扫描mapper定义的类,否则报错

2019-10-25 01:22:02,702 [main] [org.springframework.boot.SpringApplication] [ERROR] (SpringApplication.java:837)- Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myuserController': Unsatisfied dependency expressed through field 'myuserService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myuserServiceImpl': Unsatisfied dependency expressed through field 'baseMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.md.demo.test.dao.MyuserMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:584)
	at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:370)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1336)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:572)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)
	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)

2. 之所以能有框架很多自带的方法,是因为继承了IService和BaseMapper两个接口,可见源码

3. 虽然框架支持jpa方法定义sql(如下图所示),但这里还是建议使用xml sql的方式,因为对于后续扩展和查障相对来说,会方便很多,所以不建议使用jpa这种方式

其他资料

Mybatis-Plus官方

Swagger2集成教程用法

下一章教程

SpringBoot从入门到精通教程(二十六)- 全局header/body接口请求参数+Swagger2集成/接口规范用法

该系列教程

SpringBoot从入门到精通教程

 

 

 

至此,全部介绍就结束了

 

------------------------------------------------------

------------------------------------------------------

 

关于我(个人域名)

我的开源项目集Github

 

期望和大家一起学习,一起成长,共勉,O(∩_∩)O谢谢

欢迎交流问题,可加个人QQ 469580884,

或者,加我的群号 751925591,一起探讨交流问题

不讲虚的,只做实干家

Talk is cheap,show me the code

©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页