SpringBoot学习笔记(四):SpringBoot集成Mybatis-Plus+代码生成
简介
官网: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+代码生成的更多相关文章
- springboot学习笔记-6 springboot整合RabbitMQ
一 RabbitMQ的介绍 RabbitMQ是消息中间件的一种,消息中间件即分布式系统中完成消息的发送和接收的基础软件.这些软件有很多,包括ActiveMQ(apache公司的),RocketMQ(阿 ...
- SpringBoot入门笔记(四)、通常Mybatis项目目录结构
1.工程启动类(AppConfig.java) 2.实体类(domain) 3.数据访问层(dao) 4.数据服务层(service) 5.前端控制器(controller) 6.工具类(util) ...
- SpringBoot学习笔记四之后台登录页面的实现
注:图片如果损坏,点击文章链接: https://www.toutiao.com/i6803542216150090252/ 继续之前完成的内容,首先创建一个常量类 常量类的内容 服务器端渲染 前后端 ...
- SpringBoot学习笔记(9)----SpringBoot中使用关系型数据库以及事务处理
在实际的运用开发中,跟数据库之间的交互是必不可少的,SpringBoot也提供了两种跟数据库交互的方式. 1. 使用JdbcTemplate 在SpringBoot中提供了JdbcTemplate模板 ...
- springboot学习笔记-5 springboot整合shiro
shiro是一个权限框架,具体的使用可以查看其官网 http://shiro.apache.org/ 它提供了很方便的权限认证和登录的功能. 而springboot作为一个开源框架,必然提供了和sh ...
- Shiro学习笔记四(Shiro集成WEB)
这两天由于家里出了点事情,没有准时的进行学习.今天补上之前的笔记 -----没有学不会的技术,只有不停找借口的人 学习到的知识点: 1.Shiro 集成WEB 2.基于角色的权限控制 3.基于权限的控 ...
- 【转】SpringBoot学习笔记(7) SpringBoot整合Dubbo(使用yml配置)
http://blog.csdn.net/a67474506/article/details/61640548 Dubbo是什么东西我这里就不详细介绍了,自己可以去谷歌 SpringBoot整合Dub ...
- SpringBoot学习笔记(10)-----SpringBoot中使用Redis/Mongodb和缓存Ehcache缓存和redis缓存
1. 使用Redis 在使用redis之前,首先要保证安装或有redis的服务器,接下就是引入redis依赖. pom.xml文件如下 <dependency> <groupId&g ...
- SpringBoot学习笔记(6) SpringBoot数据缓存Cache [Guava和Redis实现]
https://blog.csdn.net/a67474506/article/details/52608855 Spring定义了org.springframework.cache.CacheMan ...
- SpringBoot学习笔记(16)----SpringBoot整合Swagger2
Swagger 是一个规范和完整的框架,用于生成,描述,调用和可视化RESTful风格的web服务 http://swagger.io Springfox的前身是swagger-springmvc,是 ...
随机推荐
- numpy基本函数
在学习python的时候常常需要numpy这个库,每次都是用一个查一个,这个,终于见到一个完整的总结了http://blog.csdn.net/blog_empire/article/details/ ...
- 15-Ubuntu-文件和目录命令-查看目录内容-ls-2
4. ls和通配符的使用 通配符适用的地方:shell命令行或者shell脚本中. 正则表达式适用的地方:字符串处理时,一般有一般正则和Perl正则. 正则表达式与通配符有相同的符号但是意义不同!! ...
- 数组模拟stack
package com.cxy.springdataredis.data; import java.util.Scanner; public class StackDemo { public stat ...
- jdbc出现中文乱码的解决办法
- ES6 学习 -- Class
Class的基本语法(1)// 定义类class Point { test() { console.log("hello test"); }}通过 new 定义好的类即可生成一个类 ...
- Apache Spark 2.2.0 中文文档 - Spark RDD(Resilient Distributed Datasets)
Spark RDD(Resilient Distributed Datasets)论文 概要 1: 介绍 2: Resilient Distributed Datasets(RDDs) 2.1 RDD ...
- std::unorder_set你插入元素的顺序不一定就是元素在里面的元素
去看了下cppreference,里面写了 根据哈希值排序了
- laravel 优化小记
laravel 优化 7 Performance Optimization Tips for the Laravel Developer 运行 php artisan optimize php art ...
- leetcode-17-电话号码的字母组合’
题目描述: 方法一:回溯 class Solution: def letterCombinations(self, digits): """ :type digits: ...
- thinkphp 闭包支持
闭包定义 我们可以使用闭包的方式定义一些特殊需求的路由,而不需要执行控制器的操作方法了,例如: 'URL_ROUTE_RULES'=>array( 'test' => function() ...