简介

官网:http://baomidou.oschina.io/mybatis-plus-doc/

平时业务代码不复杂的时候我们写什么代码写的最多,就是我们的SQL语句啊,配置那么多的Mapper.xml,还要配置什么resultMap这些东西,还要去管理paramtype。就会很容易出现错误,比如什么String can not parse to Integer之类的错误。

Mybatis-Plus,有了这个框架,我们可以做什么?不用写一句SQL,全部在JAVA代码中查找完毕,对于一些只做增删改查的管理系统,可以说业务层都可以免掉了。

MP是什么:是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

MP特性:无侵入,依赖少,损耗小,防SQL注入,通用CRUD,多种主键策略,代码生成,内置分页插件。。。

通用CRUD:集成BaseMapper就可以使用MP封装的CRUD

多种主键策略:IdType.AUTO(自动),IdType.INPUT(用户输入),IdType.ID_WORKER(自动),IdType.UUID(自动)。配置方法,主键ID上加上注解:@TableId(value = “ID”, type = IdType.AUTO),一般情况下推荐大家使用自动增长主键。

内置分页插件:Page内置分页插件。

代码生成:MP自带代码生成工具,可以从Controller层直接生成到mapper层,包括实体类,让我们只关心请求地址和业务处理。

集成Mybaits-Plus

在pom.xml中导入相关jar包

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

然后新建一个com.config用来存储配置信息类的包,新建一个配置Mybatis-Plus的类MybatisPlusConfig

具体内容如下,同学们不需要记住配置的具体内容是什么,你大概能看懂是什么意思就懂了。

在SpringBoot中使用配置文件时,务必在类上加上Configuration的注解方便系统启动时加载。

只需要复制即可

@Configuration
public class MybatisPlusConfig {
@Autowired
   private DataSource dataSource;
   @Autowired
   private MybatisProperties properties;
   @Autowired
   private ResourceLoader resourceLoader = new DefaultResourceLoader();
   @Autowired(required = false)
   private Interceptor[] interceptors;
   @Autowired(required = false)
   private DatabaseIdProvider databaseIdProvider;
   /**
    *   mybatis-plus分页插件
    */
   @Bean
   public PaginationInterceptor paginationInterceptor() {
       PaginationInterceptor page = new PaginationInterceptor();
       page.setDialectType("mysql");
       return page;
   }
   /**
    * 这里全部使用mybatis-autoconfigure 已经自动加载的资源。不手动指定
    * 配置文件和mybatis-boot的配置文件同步
    * @return
    */
   @Bean
   public MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean() {
       MybatisSqlSessionFactoryBean mybatisPlus = new MybatisSqlSessionFactoryBean();
       mybatisPlus.setDataSource(dataSource);
       mybatisPlus.setVfs(SpringBootVFS.class);
       if (StringUtils.hasText(this.properties.getConfigLocation())) {
           mybatisPlus.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
       }
       mybatisPlus.setConfiguration(properties.getConfiguration());
       if (!ObjectUtils.isEmpty(this.interceptors)) {
           mybatisPlus.setPlugins(this.interceptors);
       }
       MybatisConfiguration mc = new MybatisConfiguration();
       mc.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
       mybatisPlus.setConfiguration(mc);
       if (this.databaseIdProvider != null) {
           mybatisPlus.setDatabaseIdProvider(this.databaseIdProvider);
       }
       if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {
           mybatisPlus.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
       }
       if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {
           mybatisPlus.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
       }
       if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {
           mybatisPlus.setMapperLocations(this.properties.resolveMapperLocations());
       }
       return mybatisPlus;
   }
}

到这里,Mybatis-Plus已经全部集成到系统里面去了,然后我们就来改造我们之前的UserMapper,这里也可以不是说改造,就是删除掉里面的内容然后继承至Mybatis-Plus相关内容就可以了,代码如下:

@Mapper
public interface UserMapper extends BaseMapper<User> {
}

然后我们需要对实体类进行一个简单的修饰,并且告诉MP该表的主键是什么,然后主键的生成策略是什么。

@TableName("user")
public class User {

@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String username;
           。。。。。。

然后我们这里来执行一下条件查询,这里我们要用到Mybatis-Plus中的包装(Wrapper)去构建我们的条件查询

下面举几个Wrapper语句的示例,

Wrapper<T> wrapper = new EntityWrapper<>();           构建一个实体类的包装工具
wrapper.eq("username", "LIAOXIANG");                          做条件判断
wrapper.between("id", 0, 100);                                         做范围判断
wrapper.groupBy("username");                                        分组
wrapper.isNotNull("username");                                        不为空判断
wrapper.orderBy("id", false);                                             排序,从小打大为true,反之false
。。。。。。。。。。

service中

//直接继承了配置类的方法即可
userMapper.updateById(entity);
userMapper.insert(entity);
//分页:
@RequestMapping("selectpage")
public Object seletpage(Integer pagenum,Integer pagesize){
	Wrapper<User> Wrapper = new EntityWrapper<>();
	RowBounds roeBounds = new RowBounds((pagenum-1)*pagesize,pagesize);
	return userMapper.selectPage(rowBounds,Wrapper);
}

代码生成工具

导入pom文件

<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>

具体代码如下:

MpGenerator.java

package mybatisDemo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

public class MpGenerator {

	/**
	 * <p>
	 * MySQL 生成演示
	 * </p>
	 */
	public static void main(String[] args) {
		AutoGenerator mpg = new AutoGenerator();

		// 全局配置
		GlobalConfig gc = new GlobalConfig();
		gc.setOutputDir("F://mjxy");//生成到本地的目录中
		gc.setFileOverride(true);
		gc.setActiveRecord(true);
		gc.setEnableCache(false);// XML 二级缓存
		gc.setBaseResultMap(true);// XML ResultMap
		gc.setBaseColumnList(false);// XML columList
		gc.setAuthor("Liao");//代码中体现的作者

		mpg.setGlobalConfig(gc);

		// 数据源配置
		DataSourceConfig dsc = new DataSourceConfig();
		dsc.setDbType(DbType.MYSQL);//数据库
		dsc.setTypeConvert(new MySqlTypeConvert() {
			// 自定义数据库表字段类型转换【可选】
			@Override
			public DbColumnType processTypeConvert(String fieldType) {
				System.out.println("转换类型:" + fieldType);
				// 注意!!processTypeConvert 存在默认类型转换,如果不是你要的效果请自定义返回、非如下直接返回。
				return super.processTypeConvert(fieldType);
			}
		});
		dsc.setDriverName("com.mysql.jdbc.Driver");
		dsc.setUrl("jdbc:mysql://localhost:3306/springboot_mjxy?characterEncoding=utf8");
		dsc.setUsername("root");
		dsc.setPassword("admin");
		mpg.setDataSource(dsc);

		// 策略配置
		StrategyConfig strategy = new StrategyConfig();
		// strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意
		// strategy.setTablePrefix(new String[] { "tlog_", "tsys_" });// 此处可以修改为您的表前缀
		strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
		strategy.setInclude(new String[] { "user" }); // 需要生成的表
		strategy.setRestControllerStyle(true);
		// 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.victory");
		pc.setModuleName("team");//生成的文件夹外面的文件名,空的话就没有这层目录。
		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<FileOutConfig>();
		// 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"));
	}

}

SpringBoot学习笔记(四):SpringBoot集成Mybatis-Plus+代码生成的更多相关文章

  1. springboot学习笔记-6 springboot整合RabbitMQ

    一 RabbitMQ的介绍 RabbitMQ是消息中间件的一种,消息中间件即分布式系统中完成消息的发送和接收的基础软件.这些软件有很多,包括ActiveMQ(apache公司的),RocketMQ(阿 ...

  2. SpringBoot入门笔记(四)、通常Mybatis项目目录结构

    1.工程启动类(AppConfig.java) 2.实体类(domain) 3.数据访问层(dao) 4.数据服务层(service) 5.前端控制器(controller) 6.工具类(util) ...

  3. SpringBoot学习笔记四之后台登录页面的实现

    注:图片如果损坏,点击文章链接: https://www.toutiao.com/i6803542216150090252/ 继续之前完成的内容,首先创建一个常量类 常量类的内容 服务器端渲染 前后端 ...

  4. SpringBoot学习笔记(9)----SpringBoot中使用关系型数据库以及事务处理

    在实际的运用开发中,跟数据库之间的交互是必不可少的,SpringBoot也提供了两种跟数据库交互的方式. 1. 使用JdbcTemplate 在SpringBoot中提供了JdbcTemplate模板 ...

  5. springboot学习笔记-5 springboot整合shiro

    shiro是一个权限框架,具体的使用可以查看其官网 http://shiro.apache.org/  它提供了很方便的权限认证和登录的功能. 而springboot作为一个开源框架,必然提供了和sh ...

  6. Shiro学习笔记四(Shiro集成WEB)

    这两天由于家里出了点事情,没有准时的进行学习.今天补上之前的笔记 -----没有学不会的技术,只有不停找借口的人 学习到的知识点: 1.Shiro 集成WEB 2.基于角色的权限控制 3.基于权限的控 ...

  7. 【转】SpringBoot学习笔记(7) SpringBoot整合Dubbo(使用yml配置)

    http://blog.csdn.net/a67474506/article/details/61640548 Dubbo是什么东西我这里就不详细介绍了,自己可以去谷歌 SpringBoot整合Dub ...

  8. SpringBoot学习笔记(10)-----SpringBoot中使用Redis/Mongodb和缓存Ehcache缓存和redis缓存

    1. 使用Redis 在使用redis之前,首先要保证安装或有redis的服务器,接下就是引入redis依赖. pom.xml文件如下 <dependency> <groupId&g ...

  9. SpringBoot学习笔记(6) SpringBoot数据缓存Cache [Guava和Redis实现]

    https://blog.csdn.net/a67474506/article/details/52608855 Spring定义了org.springframework.cache.CacheMan ...

  10. SpringBoot学习笔记(16)----SpringBoot整合Swagger2

    Swagger 是一个规范和完整的框架,用于生成,描述,调用和可视化RESTful风格的web服务 http://swagger.io Springfox的前身是swagger-springmvc,是 ...

随机推荐

  1. 【ARC072E】Alice in linear land

    题目 瑟瑟发抖,这竟然只是个蓝题 题意大概就是初始在\(0\),要到坐标为\(D\)的地方去,有\(n\)条指令,第\(i\)条为\(d_i\).当收到一条指令\(x\)后,如果向\(D\)方向走\( ...

  2. HTML5的特殊标签与IE浏览器的兼容

    注释标签 ruby: 行级元素 横排显示 试图写多个汉字和注释,需要多个ruby. 直接上代码: - css样式: 页面效果: 重点标记 mark: 以灰常黄的黄色来重点标记 页面代码: 类似于进度条 ...

  3. mysql 04_章基本查询

    当我们使用select查询语句向数据库发送一个查询请求,数据库会根据请求执行查询,并返回一个虚拟表,其数据来源于真实的数据表. 一.查询所有数据:所有的字段.所有的记录 格式:SELECT * FRO ...

  4. js正则表达式常见面试题

    1 . 给一个连字符串例如:get-element-by-id转化成驼峰形式. var str = "get-element-by-id"; var reg = /-\w/g; / ...

  5. iOS开发系列-修改项目工程名

    当前有项目工程名为iOS,需要修改工程名为IFLY.在修改前注意备份项目 修改项目名 出现弹框,点击Rename 修改工程目录文件名 注意Tests与UITests不要删除 选中IFLY.xcodep ...

  6. 时间 '2018-08-06T10:00:00.000Z' 格式转化为本地时间(转)

    原文:https://blog.csdn.net/sxf_123456/article/details/81582964 from datetime import datetime,timedelta ...

  7. CodeForces - 803F

    http://codeforces.com/problemset/problem/803/F #include <iostream> #include <cstdio> #in ...

  8. MySQL 其他基础知识

    -- 查询存储引擎show engines;-- 显示可用存储引擎show variables like 'have%'; -- concat多个字段联合select tname ,cname ,co ...

  9. 期望dp+高斯消元优化——uvalive4297好题

    非常好的题!期望+建矩阵是简单的,但是直接套高斯消元会T 所以消元时要按照矩阵的形态 进行优化 #include<bits/stdc++.h> using namespace std; ; ...

  10. 训练计划Day1

    Day1:二分答案,三分查找,快速幂,欧拉筛素数 | 题目:火星人,Bridge,GCD,Prime Path 二分答案 [JSOI 2008] 火星人 对于第一个操作用\(hash + 二分\)来求 ...