MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
特性:
无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作
目录
1、ruoyi-common\pom.xml模块添加整合依赖
2、ruoyi-admin文件application.yml,修改mybatis配置为mybatis-plus
3、添加Mybatis Plus配置MybatisPlusConfig.java。
1、ruoyi-common\pom.xml
模块添加整合依赖
com.baomidou
mybatis-plus-boot-starter
3.4.2
org.projectlombok
lombok
1.16.20
provided
完整的
4.0.0
com.ruoyi
ruoyi
3.6.0
jar
ruoyi
http://www.ruoyi.vip
若依管理系统
org.springframework.boot
spring-boot-starter-parent
2.2.13.RELEASE
UTF-8
UTF-8
1.8
3.1.1
2.1.4
1.3.1
1.2.76
1.2.6
2.10.0
1.4
3.2.2
1.21
0.9.1
2.3.2
3.0.0
4.1.2
5.7.5
5.8.0
1.7
com.baomidou
mybatis-plus-boot-starter
3.4.2
org.projectlombok
lombok
1.16.20
provided
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-aop
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-devtools
true
org.springframework.boot
spring-boot-starter-security
org.springframework.boot
spring-boot-starter-data-redis
org.apache.commons
commons-pool2
mysql
mysql-connector-java
runtime
org.mybatis.spring.boot
mybatis-spring-boot-starter
${mybatis.spring.boot.starter.version}
com.github.pagehelper
pagehelper-spring-boot-starter
${pagehelper.spring.boot.starter.version}
com.alibaba
druid-spring-boot-starter
${druid.version}
org.apache.commons
commons-lang3
commons-io
commons-io
${commons.io.version}
commons-fileupload
commons-fileupload
${commons.fileupload.version}
eu.bitwalker
UserAgentUtils
${bitwalker.version}
com.alibaba
fastjson
${fastjson.version}
org.springframework
spring-context-support
io.jsonwebtoken
jjwt
${jwt.version}
io.springfox
springfox-boot-starter
${swagger.version}
io.swagger
swagger-models
io.swagger
swagger-models
1.6.2
com.github.oshi
oshi-core
${oshi.version}
org.apache.poi
poi-ooxml
${poi.version}
org.apache.velocity
velocity
${velocity.version}
commons-collections
commons-collections
commons-collections
commons-collections
${commons.collections.version}
org.quartz-scheduler
quartz
com.mchange
c3p0
com.github.penggle
kaptcha
${kaptcha.version}
javax.servlet-api
javax.servlet
${project.artifactId}
org.springframework.boot
spring-boot-maven-plugin
true
public
aliyun nexus
http://maven.aliyun.com/nexus/content/groups/public/
true
public
aliyun nexus
http://maven.aliyun.com/nexus/content/groups/public/
true
false
2、ruoyi-admin
文件application.yml
,修改mybatis配置为mybatis-plus
# MyBatis Plus配置
mybatis-plus:
# 搜索指定包别名
typeAliasesPackage: com.ruoyi.project.**.domain
# 配置mapper的扫描,找到所有的mapper.xml映射文件
mapperLocations: classpath*:mybatis/**/*Mapper.xml
# 加载全局的配置文件
configLocation: classpath:mybatis/mybatis-config.xml
Mybatis Plus
配置MybatisPlusConfig.java
。 tip:原来的MyBatisConfig.java
可以移除掉
package com.ruoyi.framework.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* Mybatis Plus 配置
*
* @author ruoyi
*/
@EnableTransactionManagement(proxyTargetClass = true)
@Configuration
public class MybatisPlusConfig
{
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor()
{
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 分页插件
interceptor.addInnerInterceptor(paginationInnerInterceptor());
// 乐观锁插件
interceptor.addInnerInterceptor(optimisticLockerInnerInterceptor());
// 阻断插件
interceptor.addInnerInterceptor(blockAttackInnerInterceptor());
return interceptor;
}
/**
* 分页插件,自动识别数据库类型 https://baomidou.com/guide/interceptor-pagination.html
*/
public PaginationInnerInterceptor paginationInnerInterceptor()
{
PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
// 设置数据库类型为mysql
paginationInnerInterceptor.setDbType(DbType.MYSQL);
// 设置最大单页限制数量,默认 500 条,-1 不受限制
paginationInnerInterceptor.setMaxLimit(-1L);
return paginationInnerInterceptor;
}
/**
* 乐观锁插件 https://baomidou.com/guide/interceptor-optimistic-locker.html
*/
public OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor()
{
return new OptimisticLockerInnerInterceptor();
}
/**
* 如果是对全表的删除或更新操作,就会终止该操作 https://baomidou.com/guide/interceptor-block-attack.html
*/
public BlockAttackInnerInterceptor blockAttackInnerInterceptor()
{
return new BlockAttackInnerInterceptor();
}
}
测试
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
domain 文件
package com.ruoyi.project.system.domain;
import lombok.Data;
@Data
public class User {
private Long id;
private String name;
private Integer age;
}
mapper文件
package com.ruoyi.project.system.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ruoyi.project.system.domain.User;
public interface UserMapper extends BaseMapper {
}
在验证码请求中加入mapper
package com.ruoyi.project.common;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.ruoyi.project.system.domain.User;
import com.ruoyi.project.system.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.google.code.kaptcha.Producer;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.IdUtils;
import com.ruoyi.common.utils.sign.Base64;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.service.ISysConfigService;
/**
* 验证码操作处理
*
* @author ruoyi
*/
@RestController
public class CaptchaController
{
@Resource(name = "captchaProducer")
private Producer captchaProducer;
@Resource(name = "captchaProducerMath")
private Producer captchaProducerMath;
@Resource
private UserMapper userMapper;
@Autowired
private RedisCache redisCache;
// 验证码类型
@Value("${ruoyi.captchaType}")
private String captchaType;
@Autowired
private ISysConfigService configService;
/**
* 生成验证码
*/
@GetMapping("/captchaImage")
public AjaxResult getCode(HttpServletResponse response) throws IOException
{
userMapper.selectList(null);
AjaxResult ajax = AjaxResult.success();
boolean captchaOnOff = configService.selectCaptchaOnOff();
ajax.put("captchaOnOff", captchaOnOff);
if (!captchaOnOff)
{
return ajax;
}
// 保存验证码信息
String uuid = IdUtils.simpleUUID();
String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
String capStr = null, code = null;
BufferedImage image = null;
// 生成验证码
if ("math".equals(captchaType))
{
String capText = captchaProducerMath.createText();
capStr = capText.substring(0, capText.lastIndexOf("@"));
code = capText.substring(capText.lastIndexOf("@") + 1);
image = captchaProducerMath.createImage(capStr);
}
else if ("char".equals(captchaType))
{
capStr = code = captchaProducer.createText();
image = captchaProducer.createImage(capStr);
}
redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
// 转换流信息写出
FastByteArrayOutputStream os = new FastByteArrayOutputStream();
try
{
ImageIO.write(image, "jpg", os);
}
catch (IOException e)
{
return AjaxResult.error(e.getMessage());
}
ajax.put("uuid", uuid);
ajax.put("img", Base64.encode(os.toByteArray()));
return ajax;
}
}
访问 http://localhost:8080/captchaImage
01:14:25.121 [Quartz Scheduler [RuoyiScheduler]] INFO o.q.c.QuartzScheduler - [start,547] - Scheduler RuoyiScheduler_$_WIN-M3L5SSEDUVE1627146862448 started.
01:14:30.770 [http-nio-8080-exec-2] INFO o.a.c.c.C.[.[.[/] - [log,173] - Initializing Spring DispatcherServlet 'dispatcherServlet'
01:14:30.816 [http-nio-8080-exec-2] DEBUG c.r.p.s.m.U.selectList - [debug,137] - ==> Preparing: SELECT id,name,age FROM user
01:14:30.816 [http-nio-8080-exec-2] DEBUG c.r.p.s.m.U.selectList - [debug,137] - ==> Parameters:
01:14:30.820 [http-nio-8080-exec-2] DEBUG c.r.p.s.m.U.selectList - [debug,137] - <== Total: 0
01:14:30.824 [http-nio-8080-exec-2] DEBUG c.r.p.s.m.S.selectConfig - [debug,137] - ==> Preparing: select config_id, config_name, config_key, config_value, config_type, create_by, create_time, update_by, update_time, remark from sys_config WHERE config_key = ?
01:14:30.825 [http-nio-8080-exec-2] DEBUG c.r.p.s.m.S.selectConfig - [debug,137] - ==> Parameters: sys.account.captchaOnOff(String)
01:14:30.826 [http-nio-8080-exec-2] DEBUG c.r.p.s.m.S.selectConfig - [debug,137] - <== Total: 0
01:16:25.129 [QuartzScheduler_RuoyiScheduler-WIN-M3L5SSEDUVE1627146862448_ClusterManager] WARN c.a.d.p.DruidAbstractDataSource - [testConnectionInternal,1494] - discard long time none received connection. , jdbcUrl : jdbc:mysql://localhost:3306/ry-vue?us