简介

官网: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. Android笔记之RoundedImageView

    参考项目:GcsSloop/rclayout 实现1,利用Canvas.clipPath来实现,适用于任何View(无法去除锯齿效果) package com.bu_ish.blog; import ...

  2. Fedora25安装mariadb并设置权限

    MariaDB版本10.1.21 Fedora版本25 1.Change root user sudo -i 2. dnf install -y mysql dnf install -y mariad ...

  3. Vue项目如何关闭Eslint检测

    找到build/webpack.base.config.js文件,修改如下 将图中第二个红色框的内容 "createLintingRule()" 清空,然后保存重新启动项目即可.

  4. OC开发系列-类与对象

    面向对象 面向对象思想是一种解决问题的思想, 不在是面向过程的去思考问题怎样解决.面向对象解决问题时首先要考虑需要找几个对象能解决这个问题. 常见的概念: * Object Oriented 面向对象 ...

  5. hibernate的核心思想

    Hibernate的核心思想是ROM对象关系映射机制.它是将表与表之间的操作映射成对象与对象之间的操作.也就是从数据库中提取的信息会自动按照你设置的映射要求封装成特定的对象.所以hibernate就是 ...

  6. Neo4j 因果集群搭建及neo4j-java-driver连接

    搭建Neo4j因果集群 1.下载企业版,当前是3,5,9版本 https://neo4j.com/download-center/#enterprise 2.配置,三个核心集群为例 配置文件,conf ...

  7. Unity 手机屏幕适配

    ////如有侵权 请联系我进行删除 email:YZFHKM@163.com 1.游戏屏幕适配 屏幕适配是为了让我们的项目能够跑在各种电子设备上(手机,平板,电脑) 那么了解是适配之前首先要了解两个知 ...

  8. Redis过滤器如何与Envoy代理一起使用

    1.克隆源码到机器 [root@cx-- ~]# git clone https://github.com/envoyproxy/envoy Cloning into 'envoy'... remot ...

  9. duilib库分析1.消息流程分析

    看下CWindowWnd类与CPaintManagerUI类是咋进行消息分发的吧. 1. 先看下CPaintManagerUI类的MessageLoop函数: void CPaintManagerUI ...

  10. 适AT maven多个子项目、父项目之间的引用问题

    适AT   maven多个子项目.父项目之间的引用问题 在项目时用到maven管理项目,在一个就项目的基础上开发新的项目:关于子项目和父项目,子项目与子项目之间的调用问题,发现自己存在不足,以下是自己 ...