MyBatis-Plus快速入门篇

ゝ一纸荒年。 2024-03-26 09:49 195阅读 0赞

入门篇

  • 1.快速入门
    • 1.1数据库准备
    • 1.2创建SpringBoot工程,引入MyBatis-Plus和MySQL依赖,可以使用 Spring Initializer快速初始化一个 Spring Boot 工程
    • 1.3编写DataSource相关配置(配置MySQL数据库连接)
    • 1.4编码
    • 1.5测试
  • 2.使用MybatisPlus完成增删改
    • 2.1Mapper添加
    • 2.2Mapper删除
    • 2.3Mapper修改
  • 3.使用MybatisPlus完成查询
  • 4.Service封装
  • 5.逆向工程-代码生成器

1.快速入门

1.1数据库准备

现有一张tb_user表,其表结构如下:
在这里插入图片描述
对应的数据库脚本如下:

  1. DROP TABLE IF EXISTS `tb_user`;
  2. CREATE TABLE `tb_user` (
  3. `id` int(11) NOT NULL AUTO_INCREMENT,
  4. `username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  5. `password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  6. `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  7. `age` int(11) NULL DEFAULT NULL,
  8. `email` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  9. PRIMARY KEY (`id`) USING BTREE
  10. ) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

1.2创建SpringBoot工程,引入MyBatis-Plus和MySQL依赖,可以使用 Spring Initializer快速初始化一个 Spring Boot 工程

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.1.1.RELEASE</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.example</groupId>
  12. <artifactId>mybatisplus</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>mybatisplus</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <java.version>8</java.version>
  18. </properties>
  19. <dependencies>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter</artifactId>
  23. </dependency>
  24. <dependency>
  25. <groupId>mysql</groupId>
  26. <artifactId>mysql-connector-java</artifactId>
  27. <version>5.1.26</version>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.projectlombok</groupId>
  31. <artifactId>lombok</artifactId>
  32. <optional>true</optional>
  33. </dependency>
  34. <dependency>
  35. <groupId>org.springframework.boot</groupId>
  36. <artifactId>spring-boot-starter-test</artifactId>
  37. <scope>test</scope>
  38. </dependency>
  39. <dependency>
  40. <groupId>com.baomidou</groupId>
  41. <artifactId>mybatis-plus-boot-starter</artifactId>
  42. <version>3.5.2</version>
  43. </dependency>
  44. <dependency>
  45. <groupId>junit</groupId>
  46. <artifactId>junit</artifactId>
  47. <version>4.13</version>
  48. <scope>test</scope>
  49. </dependency>
  50. </dependencies>
  51. <build>
  52. <plugins>
  53. <plugin>
  54. <groupId>org.springframework.boot</groupId>
  55. <artifactId>spring-boot-maven-plugin</artifactId>
  56. <configuration>
  57. <excludes>
  58. <exclude>
  59. <groupId>org.projectlombok</groupId>
  60. <artifactId>lombok</artifactId>
  61. </exclude>
  62. </excludes>
  63. </configuration>
  64. </plugin>
  65. </plugins>
  66. </build>
  67. </project>

1.3编写DataSource相关配置(配置MySQL数据库连接)

  1. server:
  2. port: 8080
  3. spring:
  4. datasource:
  5. driver-class-name: com.mysql.jdbc.Driver
  6. username: root
  7. password: 123456
  8. url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8

1.4编码

实体类

  1. import com.baomidou.mybatisplus.annotation.TableName;
  2. import lombok.Data;
  3. @TableName("tb_user")
  4. @Data
  5. public class User {
  6. private Integer id;
  7. private String username;
  8. private String password;
  9. private String name;
  10. private Integer age;
  11. private String email;
  12. }

其中@TableName是MybatisPlus注解,内容对应MySQL表名称,@Data是Lombok的注解,该注解的主要功能是省去了getter/setter方法。

编写mapper

  1. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  2. import com.example.mybatisplus.domain.User;
  3. public interface UserMapper extends BaseMapper<User> {
  4. }

启动类增加@MapperScan注解

  1. import org.mybatis.spring.annotation.MapperScan;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. @MapperScan("com.example.mybatisplus")
  6. public class MybatisplusApplication {
  7. public static void main(String[] args) {
  8. SpringApplication.run(MybatisplusApplication.class, args);
  9. }
  10. }

1.5测试

  1. import com.example.mybatisplus.domain.User;
  2. import com.example.mybatisplus.mapper.UserMapper;
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.boot.test.context.SpringBootTest;
  7. import org.springframework.test.context.junit4.SpringRunner;
  8. @SpringBootTest(classes = MybatisplusApplication.class)
  9. @RunWith(SpringRunner.class)
  10. public class UserMapperTest {
  11. @Autowired
  12. private UserMapper userMapper;
  13. @Test
  14. public void test01(){
  15. User user = userMapper.selectById(1);
  16. System.out.println(user);
  17. }
  18. }

在这里插入图片描述

@Test需引入Junit依赖包,可以从https://mvnrepository.com/下载

2.使用MybatisPlus完成增删改

2.1Mapper添加

方法:

  1. //添加一条记录 参数:T 实体对象
  2. int insert(T entity);

测试:

  1. @Test
  2. public void testInsert(){
  3. User user=new User();
  4. user.setUsername("xy");
  5. user.setPassword("123456");
  6. user.setName("专精装项羽");
  7. user.setAge(180);
  8. int count = userMapper.insert(user);
  9. System.out.println(count);
  10. }

2.2Mapper删除

方法:

  1. //根据ID删除
  2. int deleteById(Serializable id);
  3. //根据实体类删除
  4. int deleteById(T entity);
  5. //根据columnMap条件删除
  6. int deleteByMap(@Param("cm") Map<String, Object> columnMap);
  7. //根据entiy条件,删除记录
  8. int delete(@Param("ew") Wrapper<T> queryWrapper);
  9. //根据ID批量删除
  10. int deleteBatchIds(@Param("coll") Collection<?> idList);

测试:

根据id删除

  1. @Test
  2. public void testDelete01(){
  3. int count=userMapper.deleteById(1883332609);
  4. }

根据id批量删除

  1. @Test
  2. public void testDelete02(){
  3. List list=new ArrayList();
  4. list.add(3);
  5. list.add(4);
  6. int count = userMapper.deleteBatchIds(list);
  7. }

根据map构造条件,删除

  1. @Test
  2. public void testDelete03(){
  3. Map<String,Object> map=new HashMap<>();
  4. map.put("username","dg");
  5. map.put("name","呆瓜");
  6. int count = userMapper.deleteByMap(map);
  7. }

2.3Mapper修改

方法:

  1. //根据ID修改
  2. int updateById(@Param("et") T entity);
  3. //根据whereEntiy条件修改
  4. int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper);

测试:

  1. @Test
  2. public void testUpdate01(){
  3. User user=new User();
  4. user.setId(3);
  5. user.setName("杨杨杨");
  6. int count = userMapper.updateById(user);
  7. }
  8. @Test
  9. public void testUpdate02(){
  10. User user=new User();
  11. user.setName("旺旺旺");
  12. QueryWrapper<User> qw=new QueryWrapper<>();
  13. qw.eq("id",1);
  14. int count = userMapper.update(user,qw);
  15. }

3.使用MybatisPlus完成查询

查询的方法比较多,所以单独总结一起

  1. //根据ID查询,查询出一条记录
  2. T selectById(Serializable id);
  3. //根据ID批量查询,查询出多条记录
  4. List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList);
  5. //根据entity条件,查询出多条记录
  6. List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);
  7. //根据columnMap条件,查询出多条记录
  8. List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);
  9. //根据queryWrapper条件,查询出多条记录
  10. List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper);
  11. //根据queryWrapper条件,查询出多条记录(注意:只返回第一个字段的值)
  12. List<Object> selectObjs(@Param("ew") Wrapper<T> queryWrapper);
  13. //根据entiy条件,查询出多条记录并分页
  14. <P extends IPage<T>> P selectPage(P page, @Param("ew") Wrapper<T> queryWrapper);
  15. //根据Wrapper条件,查询出多条记录并分页
  16. <P extends IPage<Map<String, Object>>> P selectMapsPage(P page, @Param("ew") Wrapper<T> queryWrapper);

分页查询
配置拦截器

  1. @Configuration
  2. public class PageConfig {
  3. /**
  4. * 3.4.0之前的版本用这个
  5. * @return
  6. */
  7. /* @Bean
  8. public PaginationInterceptor paginationInterceptor(){
  9. return new PaginationInterceptor();
  10. }*/
  11. /**
  12. * 3.4.0之后提供的拦截器的配置方式
  13. * @return
  14. */
  15. @Bean
  16. public MybatisPlusInterceptor mybatisPlusInterceptor(){
  17. MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
  18. mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
  19. return mybatisPlusInterceptor;
  20. }
  21. }

查询

  1. @Test
  2. public void testSelectPage(){
  3. int current=1;//当前页码
  4. int size=5;//每页显示条数
  5. IPage<User> page=new Page(current,size);
  6. userMapper.selectPage(page,null);
  7. List<User> records = page.getRecords();//当前页的数据
  8. long pages = page.getPages();//总页数
  9. long total = page.getTotal();//总记录数
  10. System.out.println(records);
  11. System.out.println(pages);
  12. System.out.println(total);
  13. }

条件构造器查询

  1. Wrapper:
  2. 1.QueryWrapper 查询
  3. LambdaQueryWrapper (支持Lambda表达式)
  4. 2.UpdateWrapper 更新
  5. LamdbaUpdateWrapper(支持Lamdba表达式)

基础查询
通过QueryWrapper指定查询条件

  1. sql:select * from tb_user where password='123456' and age>18
  2. eq():等于=
  3. ne():不等于=
  4. gt():大于>
  5. ge():大于等于>=
  6. lt():小于<
  7. le():小于等于<=
  8. between(): BETWEEN 1 AND 2
  9. in():in
  10. notIn():not in
  11. @Test
  12. public void testWrapper1(){
  13. //创建查询条件构造器
  14. QueryWrapper<User> wrapper=new QueryWrapper<>();
  15. //设置条件
  16. wrapper.eq("username","bq")
  17. .lt("age",23)
  18. .in("name","白起","旺旺旺");
  19. List<User> users = userMapper.selectList(wrapper);
  20. System.out.println(users);
  21. }

以上sql等同于 select * from tb_user where username=“bq” and age<23 and name in(“白起”,“旺旺旺”)

逻辑查询or
or():让紧接着下一个方法用or连接

  1. @Test
  2. public void testWrapper2(){
  3. //创建查询条件构造器
  4. QueryWrapper<User> wrapper=new QueryWrapper<>();
  5. //设置条件
  6. wrapper.eq("username","bq")
  7. .or()
  8. .lt("age",23)
  9. .in("name","王昭君","旺旺旺");
  10. List<User> users = userMapper.selectList(wrapper);
  11. System.out.println(users);
  12. }

模糊查询like

  1. like //模糊查询匹配值‘%值%’
  2. notLike //模糊查询不匹配值‘%值%’
  3. likeLeft //模糊查询匹配最后一位值‘%值’
  4. likeRight //模糊查询匹配第一位值‘值%’
  5. @Test
  6. public void testWrapper3(){
  7. //创建查询条件构造器
  8. QueryWrapper<User> wrapper=new QueryWrapper<>();
  9. //设置条件
  10. wrapper.likeLeft("name","君");
  11. List<User> users = userMapper.selectList(wrapper);
  12. System.out.println(users);
  13. }

排序查询

  1. orderBy
  2. orderByAsc
  3. orderByDESC

select:指定需要查询的字段

  1. @Test
  2. public void testWrapper4(){
  3. //创建查询条件构造器
  4. QueryWrapper<User> wrapper=new QueryWrapper<>();
  5. //设置条件
  6. wrapper.lt("age",22).select("age");
  7. List<User> users = userMapper.selectList(wrapper);
  8. System.out.println(users);
  9. }

4.Service封装

MVC架构
controller——>service(impl)———->dao(mapper)

Mybatis-Plus 为了开发更加快捷,对业务层也进行了封装,直接提供了相关的接口和实现类。我们在进行业务层开发时,可以继承它提供的接口和实现类,使得编码更加高效

    1. 定义接口继承IService
    1. 定义实现类继承ServiceImpl 实现定义的接口

接口

  1. public interface _UserService extends IService<User> {
  2. }

实现类实现接口

  1. @Service
  2. public class _UserServiceImpl extends ServiceImpl<UserMapper, User> implements _UserService {
  3. }

测试

  1. import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
  2. import com.example.mybatisplustest.MybatisPlusTestApplication;
  3. import com.example.mybatisplustest.pojo.User;
  4. import org.junit.Test;
  5. import org.junit.runner.RunWith;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import org.springframework.test.context.junit4.SpringRunner;
  9. @SpringBootTest(classes = MybatisPlusTestApplication.class)
  10. @RunWith(SpringRunner.class)
  11. public class UserServiceTest {
  12. @Autowired
  13. private UserService userService;
  14. @Test
  15. public void testFind(){
  16. UpdateWrapper<User> wrapper = new UpdateWrapper<>();
  17. wrapper.eq("id",1);
  18. User one = userService.getOne(wrapper);
  19. System.out.println(one);
  20. }
  21. }

5.逆向工程-代码生成器

AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。
安装
引入坐标依赖

  1. <dependency>
  2. <groupId>com.baomidou</groupId>
  3. <artifactId>mybatis-plus-generator</artifactId>
  4. <version>3.5.2</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.freemarker</groupId>
  8. <artifactId>freemarker</artifactId>
  9. <version>2.3.28</version>
  10. </dependency>
  11. package com.example.mybatisplus;
  12. import com.baomidou.mybatisplus.generator.FastAutoGenerator;
  13. import com.baomidou.mybatisplus.generator.config.OutputFile;
  14. import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
  15. import java.util.Collections;
  16. public class Generator {
  17. public static void main(String[] args) {
  18. FastAutoGenerator.create("jdbc:mysql://localhost:3306/test?characterEncoding=utf-8", "root", "123456")
  19. .globalConfig(builder -> {
  20. builder.author("test") // 设置作者
  21. .enableSwagger() // 开启 swagger 模式
  22. .fileOverride() // 覆盖已生成文件
  23. .outputDir("D://"); // 指定输出目录
  24. })
  25. .packageConfig(builder -> {
  26. builder.parent("com.baomidou.mybatisplus.samples.generator") // 设置父包名
  27. .moduleName("system") // 设置父包模块名
  28. .pathInfo(Collections.singletonMap(OutputFile.xml, "D://")); // 设置mapperXml生成路径
  29. })
  30. .strategyConfig(builder -> {
  31. builder.addInclude("tb_user") // 设置需要生成的表名
  32. .addTablePrefix("t_", "c_"); // 设置过滤表前缀
  33. })
  34. .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
  35. .execute();
  36. }
  37. }

生成结果
在这里插入图片描述
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,195人围观)

还没有评论,来说两句吧...

相关阅读