MybatisPlus - 2小时入门 前置:ssm springboot学完。 ORM
目标:
了解mybatisplus的特点 能够掌握mybatisplus快速入门 能够掌握mybatisplus常用注解 能够掌握mybatisplus常用的增删改查 能够掌握mybatisplus自动代码生成 1. 概述 代码回顾mybatis用法。资料-》代码文件夹。
mybatis xml配置太过于繁琐 写基本sql
•MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
•官网: https://mp.baomidou.com/open in new window
image-20211018190541640 版本
From: 元动力 1 2 3 4 5 < dependency> < groupId> com.baomidou< /groupId> < artifactId> mybatis-plus< /artifactId> < version> 3.4.0< /version> < /dependency>
2. 快速入门 需求:SpringBoot 整合 MyBatis-Plus,并实现根据Id查询功能。
From: 元动力 1 2 3 4 5 ①数据库环境准备 ②创建SpringBoot工程,引入MyBatis-Plus起步依赖 ③编写DataSource相关配置 ④编写mapper ⑤测试
2.1 数据库环境准备 2.2 创建SpringBoot工程,引入MyBatis-Plus起步依赖
From: 元动力 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 < ?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.4.RELEASE< /version> < relativePath/> < !-- lookup parent from repository --> < /parent> < groupId> com.example< /groupId> < artifactId> mybatis-plus-test< /artifactId> < version> 0.0.1-SNAPSHOT< /version> < name> mybatis-plus-test< /name> < description> Demo project for Spring Boot< /description> < properties> < java.version> 1.8< /java.version> < /properties> < dependencies> < dependency> < groupId> org.springframework.boot< /groupId> < artifactId> spring-boot-starter< /artifactId> < /dependency> < dependency> < groupId> org.projectlombok< /groupId> < artifactId> lombok< /artifactId> < optional> true< /optional> < /dependency> < dependency> < groupId> org.springframework.boot< /groupId> < artifactId> spring-boot-starter-test< /artifactId> < scope> test< /scope> < /dependency> < !-- mysql 驱动--> < dependency> < groupId> mysql< /groupId> < artifactId> mysql-connector-java< /artifactId> < version> 5.1.26< /version> < /dependency> < !--mybatisplus起步依赖--> < dependency> < groupId> com.baomidou< /groupId> < artifactId> mybatis-plus-boot-starter< /artifactId> < version> 3.4.0< /version> < /dependency> < /dependencies> < build> < plugins> < plugin> < groupId> org.springframework.boot< /groupId> < artifactId> spring-boot-maven-plugin< /artifactId> < /plugin> < /plugins> < /build> < /project>
注意 :mysql驱动包和本地mysql版本对应。
2.3 编写DataSource相关配置 application.yml
From: 元动力 1 2 3 4 5 6 7 spring: datasource: url: jdbc:mysql://localhost:3306/mp?characterEncoding=utf-8&serverTimezone=Asia/Shanghai username: root password: root driver-class-name: com.mysql.jdbc.Driver
注意:链接的数据库是8 时区必须加上。驱动com.mysql.cj.jdbc.Driver
2.4 编码 实体类
From: 元动力 1 2 3 4 5 6 7 8 9 10 @TableName("tb_user") @Data public class User { private Long id; private String userName; private String password; private String name; private Integer age; private String email; }
编写mapper
From: 元动力 1 2 3 4 5 6 public interface UserMapper extends BaseMapper <User> { }
启动类增加 @MapperScan 注解
From: 元动力 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 package com.example.mybatisplustest;import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.ComponentScan;@SpringBootApplication @MapperScan("com.ydl.mp.mapper") public class MybatisPlusTestApplication { public static void main (String[] args) { SpringApplication.run(MybatisPlusTestApplication.class, args); } }
2.5 测试 测试代码中创建测试类 com.ydl.mp.UserMapperTest
From: 元动力 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 package com.example.mybatisplustest.mapper;import com.example.mybatisplustest.MybatisPlusTestApplication;import com.example.mybatisplustest.pojo.User;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;@SpringBootTest(classes = MybatisPlusTestApplication.class) @RunWith(SpringRunner.class) public class UserMapperTest { @Autowired private UserMapper userMapper; @Test public void testSelectById () { User user = userMapper.selectById(1L ); System.out.println(user); } }
3. CRUD 3.1 添加 3.1.1 方法解析 image-20201008114929998 3.1.2 测试
From: 元动力 1 2 3 4 5 6 7 8 9 @Test public void testInsert () { User user = new User (); user.setUserName("itlils" ); user.setPassword("ydl" ); int count = userMapper.insert(user); System.out.println(count); }
3.1.3 说明1, 实体类上的注解 @TableField
From: 元动力 1 2 3 4 5 6 7 8 9 1) @TableField("user_name") 指定映射关系 实体类的属性名和数据库的字段名自动映射: * 名称一样 * 数据库字段使用_分割,实体类属性名使用驼峰名称 否则需要使用 @TableField("user_name") 指定映射关系 2) 忽略某个字段的查询和 插入 @TableField(exist = false) 3) 设置id生成策略:AUTO 数据库自增 @TableId(type = IdType.AUTO)
3.1.4 说明2, 配置
From: 元动力 1 2 3 4 5 6 7 8 9 10 mybatis-plus: global-config: db-config: table-prefix: tb_ id-type: auto configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
From: 元动力 1 2 3 4 mybatis-plus.global-config.db-config.table-prefix =tb_ mybatis-plus.global-config.db-config.id-type =auto mybatis-plus.configuration.log-impl =org.apache.ibatis.logging.stdout.StdOutImpl
3.1.5 具体使用如下
From: 元动力 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 @TableName("tb_user") @Data public class User { @TableId(type = IdType.AUTO) private Long id; private String userName; private String password; private String name; private Integer age; private String email; }
3.2 删除 image-20201008114022226 3.2.1 根据id删除
From: 元动力 1 int count = userMapper.deleteById(8L );
3.2.1 根据id集合批量删除
From: 元动力 1 2 3 4 5 List ids = new ArrayList (); ids.add(6 ); ids.add(7 ); userMapper.deleteBatchIds(ids);
3.2.1 根据map构造条件,删除
From: 元动力 1 2 3 4 5 6 7 Map<String, Object> map = new HashMap <>(); map.put("user_name" ,"itlils" ); map.put("age" ,"18" ); userMapper.deleteByMap(map);
3.3 更新 image-20201008114912504
From: 元动力 1 2 3 4 5 6 7 @Test public void testUpdateById () { User user = new User (); user.setId(2L ); user.setPassword("1111111" ); int count = userMapper.updateById(user); }
4 查询 image-20201008115031886 4.1 分页查询 配置 拦截器
From: 元动力 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 @Configuration public class PageConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor () { MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor (); mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor ()); return mybatisPlusInterceptor; } }
查询
From: 元动力 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 @Test public void testSelectPage () { int current = 1 ; int size = 5 ; IPage<User> page = new Page (current,size); userMapper.selectPage(page,null ); List<User> records = page.getRecords(); long pages = page.getPages(); long total = page.getTotal(); System.out.println(records); System.out.println(pages); System.out.println(total); }
4.2 条件构造器查询 4.2.1 基础查询 通过 QueryWrapper 指定查询条件
sql:select * from tb_user where password='123456' and age>18
From: 元动力 1 2 3 4 5 6 7 8 9 10 eq( ) : 等于 = ne( ) : 不等于 <> gt( ) : 大于 > ge( ) : 大于等于 >= lt( ) : 小于 < le( ) : 小于等于 <= between ( ) : BETWEEN 值1 AND 值2 notBetween ( ) : NOT BETWEEN 值1 AND 值2 in( ) : in notIn( ) :not in
From: 元动力 1 2 3 4 5 6 7 8 9 10 11 12 @Test public void testWrapper1 () { QueryWrapper<User> wrapper = new QueryWrapper <>(); wrapper.eq("user_name" ,"lisi" ) .lt("age" ,23 ) .in("name" ,"李四" ,"王五" ); List<User> users = userMapper.selectList(wrapper); System.out.println(users); }
4.2.2 逻辑查询 or
From: 元动力 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 @Test public void testWrapper2 () { QueryWrapper<User> wrapper = new QueryWrapper <>(); wrapper.eq("user_name" ,"lisi" ) .or() .lt("age" ,23 ) .in("name" ,"李四" ,"王五" ); List<User> users = userMapper.selectList(wrapper); System.out.println(users); }
4.2.3 模糊查询 like
From: 元动力 1 2 3 4 like notLike likeLeft likeRight
From: 元动力 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 @Test public void testWrapper3 () { QueryWrapper<User> wrapper = new QueryWrapper <>(); wrapper.likeLeft("user_name" ,"zhang" ); List<User> users = userMapper.selectList(wrapper); System.out.println(users); }
4.2.4 排序查询
From: 元动力 1 2 3 orderBy orderByAsc orderByDesc
From: 元动力 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 @Test public void testWrapper4 () { QueryWrapper<User> wrapper = new QueryWrapper <>(); wrapper.eq("user_name" ,"lisi" ) .or() .lt("age" ,23 ) .or() .in("name" ,"李四" ,"王五" ) .orderByDesc("age" ); List<User> users = userMapper.selectList(wrapper); System.out.println(users); }
4.2.5 select:指定需要查询的字段
From: 元动力 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 @Test public void testWrapper5 () { QueryWrapper<User> wrapper = new QueryWrapper <>(); wrapper.eq("user_name" ,"lisi" ) .or() .lt("age" ,23 ) .or() .in("name" ,"李四" ,"王五" ) .orderByDesc("age" ) .select("id" ,"user_name" ); List<User> users = userMapper.selectList(wrapper); System.out.println(users); }
4.2.6 分页条件查询
From: 元动力 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 @Test public void testWrapper6 () { int current = 1 ; int size = 2 ; Page<User> page = new Page <>(current,size); QueryWrapper<User> wrapper = new QueryWrapper (); wrapper.lt("age" ,23 ); userMapper.selectPage(page,wrapper); List<User> records = page.getRecords(); long total = page.getTotal(); long pages = page.getPages(); System.out.println(records); System.out.println(total); System.out.println(pages); }
4.2.7 LambdaQueryWrapper:消除代码中的硬编码
From: 元动力 1 2 3 4 5 6 @Test public void testWrapper7 () { LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper <>(); wrapper.eq(User::getUserName,"zhangsan" ); userMapper.selectOne(wrapper); }
4.2.8 条件 删除 image-20201008121325431
From: 元动力 1 2 3 4 5 6 @Test public void testWrapper8 () { QueryWrapper<User> wrapper = new QueryWrapper <>(); wrapper.eq("user_name" ,"bbb" ); userMapper.delete(wrapper); }
4.2.9 条件 update image-20201008121332555
From: 元动力 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 @Test public void testWrapper9 () { UpdateWrapper<User> wrapper = new UpdateWrapper <>(); wrapper.eq("user_name" ,"lisi" ) .set("password" ,"22222" ); userMapper.update(null ,wrapper); } @Test public void testWrapper10 () { UpdateWrapper<User> wrapper = new UpdateWrapper <>(); wrapper.eq("user_name" ,"lisi" ); User user = new User (); user.setPassword("3333" ); user.setAge(33 ); userMapper.update(user,wrapper); }
5 service 封装 MVC架构
前端----》controller---->service(impl)------->dao(mapper)
Mybatis-Plus 为了开发更加快捷,对业务层也进行了封装,直接提供了相关的接口和实现类。我们在进行业务层开发时,可以继承它提供的接口和实现类,使得编码更加高效
From: 元动力 1 2 - 1. 定义接口继承IService - 2. 定义实现类继承ServiceImpl<Mapper,Entity> 实现定义的接口
接口
From: 元动力 1 2 public interface _UserService extends IService <User> { }
实现类封装
From: 元动力 1 2 @Service public class _UserServiceImpl extends ServiceImpl <UserMapper, User> implements _UserService {}
From: 元动力 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 package com.example.mybatisplustest.service;import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;import com.example.mybatisplustest.MybatisPlusTestApplication;import com.example.mybatisplustest.pojo.User;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;@SpringBootTest(classes = MybatisPlusTestApplication.class) @RunWith(SpringRunner.class) public class UserServiceTest { @Autowired private UserService userService; @Test public void testFind () { UpdateWrapper<User> wrapper = new UpdateWrapper <>(); wrapper.eq("id" ,1 ); User one = userService.getOne(wrapper); System.out.println(one); } }
6. 逆向工程-代码生成器 AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。
6.1 导入坐标
From: 元动力 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 < ?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.4.RELEASE< /version> < relativePath/> < !-- lookup parent from repository --> < /parent> < groupId> com.example< /groupId> < artifactId> mybatis-plus-test< /artifactId> < version> 0.0.1-SNAPSHOT< /version> < name> mybatis-plus-test< /name> < description> Demo project for Spring Boot< /description> < properties> < java.version> 1.8< /java.version> < /properties> < dependencies> < dependency> < groupId> org.springframework.boot< /groupId> < artifactId> spring-boot-starter< /artifactId> < /dependency> < dependency> < groupId> org.projectlombok< /groupId> < artifactId> lombok< /artifactId> < optional> true< /optional> < /dependency> < dependency> < groupId> org.springframework.boot< /groupId> < artifactId> spring-boot-starter-test< /artifactId> < scope> test< /scope> < /dependency> < !-- mysql 驱动--> < dependency> < groupId> mysql< /groupId> < artifactId> mysql-connector-java< /artifactId> < version> 5.1.26< /version> < /dependency> < !--mybatisplus起步依赖--> < dependency> < groupId> com.baomidou< /groupId> < artifactId> mybatis-plus-boot-starter< /artifactId> < version> 3.4.0< /version> < /dependency> < !--mp 代码生成器--> < dependency> < groupId> com.baomidou< /groupId> < artifactId> mybatis-plus-generator< /artifactId> < version> 3.4.0< /version> < /dependency> < dependency> < groupId> org.freemarker< /groupId> < artifactId> freemarker< /artifactId> < version> 2.3.30< /version> < /dependency> < /dependencies> < build> < plugins> < plugin> < groupId> org.springframework.boot< /groupId> < artifactId> spring-boot-maven-plugin< /artifactId> < /plugin> < /plugins> < /build> < /project>
6.2 执行main 方法
From: 元动力 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 package com.example.mybatisplustest;import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;import com.baomidou.mybatisplus.core.toolkit.StringPool;import com.baomidou.mybatisplus.core.toolkit.StringUtils;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;import java.util.Scanner;public class CodeGenerator { public static String scanner (String tip) { Scanner scanner = new Scanner (System.in); StringBuilder help = new StringBuilder (); help.append("请输入" + tip + ":" ); System.out.println(help.toString()); if (scanner.hasNext()) { String ipt = scanner.next(); if (StringUtils.isNotBlank(ipt)) { return ipt; } } throw new MybatisPlusException ("请输入正确的" + tip + "!" ); } public static void main (String[] args) { AutoGenerator mpg = new AutoGenerator (); GlobalConfig gc = new GlobalConfig (); String projectPath = System.getProperty("user.dir" ); System.out.println(projectPath); gc.setOutputDir(projectPath + "/src/main/java" ); gc.setAuthor("ydl" ); gc.setOpen(false ); mpg.setGlobalConfig(gc); DataSourceConfig dsc = new DataSourceConfig (); dsc.setUrl("jdbc:mysql://localhost:3306/mp" ); dsc.setDriverName("com.mysql.jdbc.Driver" ); dsc.setUsername("root" ); dsc.setPassword("root" ); mpg.setDataSource(dsc); PackageConfig pc = new PackageConfig (); pc.setModuleName(scanner("模块名" )); pc.setParent("com.ydl" ); mpg.setPackageInfo(pc); InjectionConfig cfg = new InjectionConfig () { @Override public void initMap () { } }; String templatePath = "/templates/mapper.xml.ftl" ; List<FileOutConfig> focList = new ArrayList <>(); focList.add(new FileOutConfig (templatePath) { @Override public String outputFile (TableInfo tableInfo) { return projectPath + "/src/main/resources/mapper/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); TemplateConfig templateConfig = new TemplateConfig (); 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.setSuperEntityColumns("id" ); strategy.setInclude(scanner("表名,多个英文逗号分割" ).split("," )); strategy.setControllerMappingHyphenStyle(true ); strategy.setTablePrefix(pc.getModuleName() + "_" ); mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine ()); mpg.execute(); } }