mybatis puls介绍
mybatis puls官方(www.baomidou.com)的解释是
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 操作智能分析阻断,也可自定义拦截规则,预防误操作
支持的数据库
任何能使用 MyBatis 进行 CRUD, 并且支持标准 SQL 的数据库,具体支持情况如下,如果不在下列表查看分页部分教程 PR 您的支持。
MySQL,Oracle,DB2,H2,HSQL,SQLite,PostgreSQL,SQLServer,Phoenix,Gauss ,ClickHouse,Sybase,OceanBase,Firebird,Cubrid,Goldilocks,csiidb,informix,TDengine,redshift
达梦数据库,虚谷数据库,人大金仓数据库,南大通用(华库)数据库,南大通用数据库,神通数据库,瀚高数据库,优炫数据库,星瑞格数据库
实例
使用mybatis puls来完成对单表的增删改查操作
使用mysql数据库 准备student表
/*
Navicat Premium Data Transfer
Source Server : localhost_3306
Source Server Type : MySQL
Source Server Version : 80030
Source Host : localhost:3306
Source Schema : qy168
Target Server Type : MySQL
Target Server Version : 80030
File Encoding : 65001
Date: 21/08/2023 13:58:26
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(0) NOT NULL AUTO_INCREMENT,
`name` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`phone` varchar(11) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`email` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`profession` varchar(30) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`age` int(0) NULL DEFAULT NULL,
`gender` tinyint(0) NULL DEFAULT NULL,
`status` tinyint(0) NULL DEFAULT NULL,
`createtime` datetime(0) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `phone_index`(`phone`) USING BTREE,
INDEX `name_index`(`name`) USING BTREE,
INDEX `pro_age_status_index`(`profession`, `age`, `status`) USING BTREE,
INDEX `email_index`(`email`) USING BTREE,
INDEX `gender_index`(`gender`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES (1, '吕布', '17799990000', 'lvbu666@163.com', '软件工程', 23, 1, 6, '2001-02-02 00:00:00');
INSERT INTO `student` VALUES (2, '曹操', '17799990001', 'caocao666@qq.com', '通信工程', 33, 1, 0, '2001-03-05 00:00:00');
INSERT INTO `student` VALUES (3, '赵云', '17799990002', '17799990@139.com', '英语', 34, 1, 2, '2002-03-02 00:00:00');
INSERT INTO `student` VALUES (4, 'DD', '12345678910', '1111@qq.com', '软件工程', 22, 2, 6, '2001-07-02 00:00:00');
INSERT INTO `student` VALUES (5, '花木兰', '17799990004', '199980729@sina.com', '软件工程', 23, 2, 1, '2001-04-22 00:00:00');
INSERT INTO `student` VALUES (6, '大乔', '17799990005', 'daqiao666@sina.com', '舞蹈', 22, 2, 0, '2001-02-07 00:00:00');
INSERT INTO `student` VALUES (7, '露娜', '17799990006', 'luna_love@sina.com', '应用数学', 24, 2, 0, '2001-02-08 00:00:00');
INSERT INTO `student` VALUES (8, '程咬金', '17799990007', 'chengyaojin@163.com', '化工', 38, 1, 5, '2001-05-23 00:00:00');
INSERT INTO `student` VALUES (9, '项羽', '17799990008', 'xiaoyu666@qq.com', '金属材料', 43, 1, 0, '2022-08-25 17:00:45');
INSERT INTO `student` VALUES (10, '白起', '17799990009', 'baiqi666@sina.com', '机械工程及其自动化', 27, 1, 2, '2022-08-25 17:23:51');
INSERT INTO `student` VALUES (11, '韩信', '17799990010', 'hanxin520@163.com', '无机非金属材料工程', 27, 1, 0, '2022-08-25 17:23:51');
INSERT INTO `student` VALUES (12, '荆轲', '17799990011', 'jinke123@163.com', '会计', 29, 1, 0, '2022-08-25 17:23:51');
INSERT INTO `student` VALUES (13, '兰陵王', '17799990012', 'lanlinwang666@126.com', '工程造价', 44, 1, 1, '2022-08-25 17:23:51');
INSERT INTO `student` VALUES (14, '狂铁', '17799990013', 'kuangtie@sina.com', '应用数学', 43, 1, 2, '2022-08-25 17:23:51');
INSERT INTO `student` VALUES (15, '貂蝉', '17799990014', '84958948374@qq.com', '软件工程', 40, 1, 3, '2022-08-25 17:23:51');
INSERT INTO `student` VALUES (16, '妲己', '17799990015', '2783238293@qq.com', '软件工程', 31, 1, 0, '2022-08-25 17:23:51');
INSERT INTO `student` VALUES (17, '芈月', '17799990016', 'xiaomin2001@sina.com', '工业经济', 35, 1, 0, '2022-08-25 17:23:51');
INSERT INTO `student` VALUES (18, '嬴政', '17799990017', '8839434342@qq.com', '化工', 38, 1, 1, '2022-08-25 17:23:51');
INSERT INTO `student` VALUES (19, '狄仁杰', '17799990018', 'jujiamlm8166@163.com', '国际贸易', 30, 1, 0, '2022-08-25 17:23:51');
INSERT INTO `student` VALUES (20, '安琪拉', '17799990019', 'jdodmlh@126.com', '城市规划', 51, 1, 0, '2022-08-25 17:23:51');
INSERT INTO `student` VALUES (21, '典韦', '17799990020', 'ycaunanjian@163.com', '城市规划', 52, 1, 2, '2022-08-25 17:23:51');
INSERT INTO `student` VALUES (22, '廉颇', '17799990021', 'lianpo321@126.com', '土木工程', 19, 1, 3, '2022-08-25 17:23:51');
INSERT INTO `student` VALUES (23, '后裔', '17799990022', 'altycj2000@139.com', '城市园林', 20, 1, 0, '2022-08-25 17:23:51');
SET FOREIGN_KEY_CHECKS = 1;
首先创建一个springboot工程
引入mp的相关依赖
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.aaa</groupId>
<artifactId>springboot-crud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-crud</name>
<description>springboot-crud</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
<!--引入swagger2依赖-->
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.9.1.RELEASE</version>
</dependency>
<!--图形化依赖-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
创建实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
@TableId(type = IdType.AUTO)
private long id;
private String name;
private String phone;
private String email;
private String profession;
private long age;
private long gender;
private long status;
private Date createtime;
}
创建Dao层
@Mapper
public interface StudentDao extends BaseMapper<Student> {
}
这里的StudentDao继承了mp中的BaseMapper<T>,这时它就有了一系列的单表增删改查操作
都不需要创建mapper映射,mp直接帮你完成了。
启动类
@SpringBootApplication
@MapperScan(basePackages = "com.aaa.dao")
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
测试类直接调用mp的内置crud方法
@SpringBootTest
class SpringbootApplicationTests {
@Autowired
private StudentDao studentDao;
@Test
void testSelectById() {
Student student = studentDao.selectById(1);
System.out.println(student);
}
@Test
void testInsert() {
Student student = new Student(25, "AA", "123456789", "1111@qq.com", "软件工程", 22, 2, 6, null);
studentDao.insert(student);
System.out.println(student);
}
@Test
void testUpdate() {
Student student = new Student(25, "DD", "12345678910", "1111@qq.com", "软件工程", 22, 2, 6, null);
//studentDao.updateById(student); //根据Id修改
UpdateWrapper<Student> wrapper = new UpdateWrapper<>();
//wrapper.eq("name","BB"); //修改name为BB的student
//wrapper.ge("age",53); // where age>=53
//wrapper.between("age",10,20);// where age between 10 and 20;
//wrapper.like("name","吕");//where name like '%吕%'
//wrapper.ne("name","韩信"); //where name !='韩信'
//wrapper.lt("age",20); //where age<20;
//两个wrapper间 默认含有and
//wrapper.like("name","赵");
//wrapper.ne("name","赵云"); //where name like '%赵%' and name<>'赵云'
studentDao.update(student, wrapper);
}
@Test
public void testDelete() {
//根据主键删除
//int row = studentDao.deleteById(25);
//deleteBatchIds: 批量删除
//List<Long> ids=new ArrayList<>();
//ids.add(5L);
//ids.add(6L);
//ids.add(7L);
//studentDao.deleteBatchIds(ids); //where id in(5,6,7)
//根据其他条件删除--
UpdateWrapper<Student> wrapper = new UpdateWrapper<>();
wrapper.like("name", "子");
studentDao.delete(wrapper);
}
//根据条件多条记录
@Test
public void testSelectAll() {
QueryWrapper<Student> wrapper = new QueryWrapper<>();
wrapper.ge("age", "20");
List<Student> students = studentDao.selectList(wrapper);
System.out.println(students);
}
//分页查询. 如果想让分页有效 必须配置分页拦截器 config.MpConfig
@Test
public void testSelectByPage() {
IPage<Student> iPage = new Page(1, 5);
QueryWrapper<Student> wrapper = new QueryWrapper<>();
wrapper.orderByAsc("id");
//Page:分页对象 Wrapper:条件对象
IPage<Student> page = studentDao.selectPage(iPage, wrapper);
System.out.println("总条数:" + page.getTotal());
System.out.println("总页数:" + page.getPages());
System.out.println("当前页的记录:" + page.getRecords());
}
}
注意:使用分页功能需要有分页配置
@Configuration
public class MpConfig {
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}