1 介绍
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做==增强不做改变==,为简化开发、提高效率而生。--单表操作的都不需要自己在写sql语句。--
愿景
我们的愿景是成为 MyBatis 最好的搭档,就像 魂斗罗 中的 1P、2P,基友搭配,效率翻倍。
2 特点
-
无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
-
损耗小:启动即会自动注入基本 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 操作智能分析阻断,也可自定义拦截规则,预防误操作.
4.3 如何使用
(1)创建数据库和表
DROP TABLE IF EXISTS user; CREATE TABLE user ( id BIGINT(20) NOT NULL COMMENT '主键ID', name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名', age INT(11) NULL DEFAULT NULL COMMENT '年龄', email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱', PRIMARY KEY (id) ); DELETE FROM user; INSERT INTO user (id, name, age, email) VALUES (1, 'Jone', 18, 'test1@baomidou.com'), (2, 'Jack', 20, 'test2@baomidou.com'), (3, 'Tom', 28, 'test3@baomidou.com'), (4, 'Sandy', 21, 'test4@baomidou.com'), (5, 'Billie', 24, 'test5@baomidou.com');
(2)依赖
<!--mp的依赖--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.1</version> </dependency>
(2)创建实体类
package com.ykq.entity; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; @Data //如果表名和实体类名不一致。@TableName(value = "tbl_user") public class User { //标记该属性为主键。 value:标记列名和属性名的对应 @TableId(value = "id") private Integer id; //如果属性和列名不一样 @TableField(value = "") private String name; private Integer age; private String email; }
(3)dao
//BaseMapper接口中提供了单表的所有操作。crud. @Mapper public interface UserMapper extends BaseMapper<User> { }
(4)测试
@Autowired private UserMapper userMapper; @Test void contextLoads() { User user = userMapper.selectById(1); System.out.println(user); }
5. mp-增加
/** * 主键mp提供相应的生成策略: * AUTO(0),递增策略,如果使用该策略必须要求数据表的列也是递增。 * NONE(1), * INPUT(2),没有策略,必须人为的输入id值 * ASSIGN_ID(3), 随机生成一个Long类型的值。该值一定是唯一。而且每次生成都不会相同。算法:雪花算法。 适合分布式主键。 * ASSIGN_UUID(4); 随机产生一个String类型的值。该值也是唯一的。 */ @Test public void testInsert(){ User user = new User(); user.setName("周世于02"); user.setAge(18); user.setEmail("2300316070@qq.com"); System.out.println("添加前:============"+user); int insert = userMapper.insert(user); //mp会把生成的主键值复制给对象。 System.out.println("添加后:============"+user); System.out.println(insert); }
6. mp-删除
/** * 实际开发中: 我们的删除可能是逻辑删除。所谓的逻辑删除就是修改功能。把某个列修改以删除的状态值。 * 只对自动注入的 sql 起效: * 插入: 不作限制--- * 查找: 追加 where 条件过滤掉已删除数据,且使用 wrapper.entity 生成的 where 条件会忽略该字段 * 更新: 追加 where 条件防止更新到已删除数据,且使用 wrapper.entity 生成的 where 条件会忽略该字段 * 删除: 转变为 更新 * (1)增加一个逻辑字段: isdeleted 0表示未删除 1表示删除. * (2)实体类上的字段添加 @TableLogic. */ @Test public void testDelete(){ //根据主键删除 int i = userMapper.deleteById(1551469383089573889L); System.out.println(i); }
7. mp-修改
/** * 自动填充功能: * 在阿里规则中我们的每一张表必须具备的三个字段 id,create_time,update_time. * 这两个字段要不要自己添加。 * * (1)在需要自动填充属性上@TableField(fill=) * (2)创建mp自动填充类 */ @Test public void testUpdate(){ User user = new User(); user.setId(2L); user.setName("张学友"); //根据主键进行修改 int i = userMapper.updateById(user); System.out.println(i); }
8. mp-查询
8.1 根据主键查询---省略
8.2 根据各种条件查询
@Test public void testSelectByCondition(){ //Wrapper:封装了关于查询的各种条件方法。有三个子类最常用: QueryWrapper查询条件 UpdateWrapper修改条件 LambdaQueryWrapper查询使用lambda表达式条件 QueryWrapper<User> wrapper=new QueryWrapper<>(); wrapper.between("age", 15, 25); wrapper.select("name","age"); wrapper.like("name","a"); System.out.println(userMapper.selectList(wrapper)); }
8.3 根据条件查询一条记录
@Test public void testSelectOne(){ QueryWrapper<User> wrapper=new QueryWrapper<>(); wrapper.eq("username",""); wrapper.eq("password",""); User user = userMapper.selectOne(wrapper); }
8.4 分页查询
/** * (1)添加分页拦截器 * (2)调用分页方法 */ @Test public void testPage(){ //P page, 分页对象 Page // @Param("ew") Wrapper<T> queryWrapper Page<User> page=new Page<>(3,3); userMapper.selectPage(page,null);//把查询的结果自动封装到Page对象中 System.out.println("总页码:"+page.getPages()); System.out.println("总条数:"+page.getTotal()); System.out.println("当前页记录:"+page.getRecords()); }
8.5 联表查询也使用mp的分页。
/** * 联表查询 使用mp的分页功能。 */ @Test public void testLianbiao(){ // @Param("ew") Wrapper<T> queryWrapper Page<User> page=new Page<>(1,3); QueryWrapper<User> wrapper=new QueryWrapper<>(); wrapper.eq("name","刘德华"); IPage<User> users=userMapper.selectUserWithDept(page,wrapper); System.out.println("总页码:"+page.getPages()); System.out.println("总条数:"+page.getTotal()); System.out.println("当前页记录:"+page.getRecords()); }
<resultMap id="baseMaper" type="com.ykq.entity.User" autoMapping="true"> <id property="id" column="id"/> <association property="dept" javaType="com.ykq.entity.Dept" autoMapping="true"> <id column="did" property="did"/> </association> </resultMap> <select id="selectUserWithDept" resultMap="baseMaper"> select * from user u join tbl_dept d on u.did=d.did where isdeleted=0 <if test="ew!=null"> and ${ew.sqlSegment} </if> </select>
9. mp的代码生成器
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.3</version> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.30</version> </dependency>
package com.ykq; import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException; import com.baomidou.mybatisplus.core.toolkit.StringPool; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.InjectionConfig; import com.baomidou.mybatisplus.generator.config.*; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; import java.util.ArrayList; import java.util.List; // 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中 public class CodeGenerator { /** * <p> * 读取控制台内容 * </p> */ public static void main(String[] args) { // 代码生成器 AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); gc.setOutputDir("./src/main/java"); gc.setAuthor("闫克起"); gc.setOpen(false); gc.setSwagger2(true); //实体属性 Swagger2 注解 mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/mp?serverTimezone=Asia/Shanghai"); // dsc.setSchemaName("public"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("root"); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); pc.setModuleName("system"); pc.setParent("com.ykq"); mpg.setPackageInfo(pc); // 自定义配置 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { // to do nothing } }; // 如果模板引擎是 freemarker String templatePath = "/templates/mapper.xml.ftl"; // 如果模板引擎是 velocity // String templatePath = "/templates/mapper.xml.vm"; // 自定义输出配置 List<FileOutConfig> focList = new ArrayList<>(); // 自定义配置会被优先输出 focList.add(new FileOutConfig(templatePath) { @Override public String outputFile(TableInfo tableInfo) { // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!! return "./src/main/resources/mapper/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } }); /* cfg.setFileCreate(new IFileCreate() { @Override public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) { // 判断自定义文件夹是否需要创建 checkDir("调用默认方法创建的目录,自定义目录用"); if (fileType == FileType.MAPPER) { // 已经生成 mapper 文件判断存在,不想重新生成返回 false return !new File(filePath).exists(); } // 允许生成模板文件 return true; } }); */ cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // 配置模板 TemplateConfig templateConfig = new TemplateConfig(); // 配置自定义输出模板 //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别 // templateConfig.setEntity("templates/entity2.java"); // templateConfig.setService(); // templateConfig.setController(); templateConfig.setXml(null); mpg.setTemplate(templateConfig); // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setEntityLombokModel(true); strategy.setRestControllerStyle(true); // 公共父类 // 写于父类中的公共字段 strategy.setControllerMappingHyphenStyle(true); mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } }