MyBatis-Plus:快速入门

1. 概念

MyBatis-Plus(简称 MP)是一个MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。其突出的特性如下:

* **无侵入**:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑

* **强大的 CRUD 操作**:内置通用 Mapper、通用 Service,提供了大量的通用的CRUD方法,因此可以省去大量手写sql的语句的工作。

* **条件构造器**:提供了强大的条件构造器,可以构造各种复杂的查询条件,以应对各种复杂查询。

* **内置分页插件**:配置好插件之后,写分页等同于普通 List 查询,无需关注分页逻辑。

2. 与springboot集成

导入依赖

XML 复制代码
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.3.2</version>
</dependency>

3. 创建实体类

java 复制代码
@Data
@TableName("user")
public class User {

    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    @TableField("name")
    private String name;

    @TableField("age")
    private Integer age;

    @TableField("email")
    private String email;
}

* @TableName`:表名注解,用于标识实体类所对应的表

* `value`:用于声明表名

* `@TableId`:主键注解,用于标识主键字段

* `value`:用于声明主键的字段名

* `type`:用于声明主键的生成策略,常用的策略有`AUTO`、`ASSIGN_UUID`、`INPUT`等等

* `@TableField`:普通字段注解,用于标识属性所对应的表字段

* `value`:用于声明普通字段的字段名

4. 通用Mapper

  1. 创建Mapper接口,并继承由Mybatis-plus提供的BaseMapper<T>接口
java 复制代码
@Mapper
public interface UserMapper extends BaseMapper<User> {

    IPage<User> selectUserPage(IPage<User> page);
}

若Mapper接口过多,可不用逐一配置`@Mapper`注解,而使用`@MapperScan`注解指定包扫描路径进行统一管理,例如

java 复制代码
@SpringBootApplication
@MapperScan("com.itgyl.mapper")
public class HelloMpApplication {

    public static void main(String[] args) {
        SpringApplication.run(HelloMpApplication.class, args);
    }

}
  1. 测试Mapper
java 复制代码
@SpringBootTest
class UserMapperTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testSelectUser() {
        List<User> users = userMapper.selectList(null);
        users.forEach(System.out::println);

        Long count = userMapper.selectCount(null);
        System.out.println("count=" + count);
    }
}

5. 通用Service

通用Service进一步封装了通用Mapper的CRUD方法,并提供了例如`saveOrUpdate`、`saveBatch`等高级方法。

1.定义service接口

java 复制代码
//定义业务接口,需要继承IService类
public interface UserService extends IService<User> {
}

2.创建service实体类

java 复制代码
//服务层
@Service
//mybatis-plus:业务实现类需继承ServiceImpl类,并将Mapper接口类和pojo类传入
//底层是将Mapper类进一步封装而来使得业务层直接调用
//并且实现业务接口类,即使得控制层调用业务方法也形成规范
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

}

测试

java 复制代码
@SpringBootTest
class UserServiceImplTest {

    @Autowired
    private UserServiceImpl userService;

    @Test
    public void testUserService() {
        Optional<User> optById = userService.getOptById(1);
        System.out.println(optById);
    }
}

6. 条件构造器

复制代码
@SpringBootTest
public class WrapperTest {

    @Autowired
    UserService userService;

    @Autowired
    private ServiceImpl service;

    //QueryWrapper条件构造器,通过该构造器构造查询的过滤条件
    @Test
    public void testQueryWrapper() {
        //wrapper会将过滤条件添加到sql语句中
        //1.查询name=Tom的数据
        QueryWrapper<User> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("name", "Tom");

        //2.模糊匹配
        QueryWrapper<User> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.like("email", ".com");

        //3.根据年龄降序排序并将结果打印
        QueryWrapper<User> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.orderByDesc("age");

        //4.查询年龄大于等于20小于等于30
        QueryWrapper<User> queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.ge("age", 20).le("age", 30);

        //5.查询年龄小于20或者大于30的用户数据
        QueryWrapper<User> queryWrapper5 = new QueryWrapper<>();
        queryWrapper5.le("age", 20).or().ge("age", 30);

        //6.查询以.com结尾 and (age < 20 or age > 30)
        //and里面传递参数为要过滤的条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("email", ".com").and(QueryWrapper -> QueryWrapper.le("age", 20).or().ge("age", 30));
        List list = service.list(queryWrapper);
        list.forEach(System.out::println);
    }


    //UpdateWrapper更新删除的条件构造器
    @Test
    public void testUpdateWrapper() {
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("name", "Tom").set("name", "ESon");
        boolean update = service.update(updateWrapper);
        System.out.println("update=" + update);
    }


    //LambdaQueryWrapper构造器,里面通过方法引用传递参数
    //优点:减少手敲字段带来不必要的错误,提高开发效率
    @Test
    public void testLambdaQueryWrapper() {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User :: getName, "ESon");
        List<User> list = userService.list(lambdaQueryWrapper);
        list.forEach(System.out :: println);
    }

    //LambdaUpdateWrapper构造器
    @Test
    public void testLambdaUpdateWrapper() {
        LambdaUpdateWrapper<User> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(User :: getName, "ESon").set(User :: getName, "Tom");
        boolean update = userService.update(lambdaUpdateWrapper);
        System.out.println("update=" + update);
    }
}

7. 分页插件

1.配置分页插件

复制代码
@Configuration
public class MPConfiguration {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

核心

| 属性名 | 类型 | 默认值 | 描述 |

| ------- | ---- | --------- | ---------------------- |

| records | List | emptyList | 查询数据列表 |

| total | Long | 0 | 查询列表总记录数 |

| size | Long | 10 | 每页显示条数,默认`10` |

| current | Long | 1 | 当前页 |

分页对象既作为分页查询的参数,也作为分页查询的返回结果,当作为查询参数时,通常只需提供`current`和`size`属性,如下

```java

IPage<T> page = new Page<>(current, size);

```

注:`IPage`为分页接口,`Page`为`IPage`接口的一个实现类。

自定义分页查询

在Mapper接口中定义分页查询方法

java 复制代码
@Mapper
public interface UserMapper extends BaseMapper<User> {

    IPage<User> selectUserPage(IPage<User> page);
}

创建`resources/mapper/UserMapper.xml`文件,内容如下

XML 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itgyl.mapper.UserMapper">
    <select id="selectUserPage" resultType="com.itgyl.entity.User">
        select *
        from user
    </select>
</mapper>

**注意**:Mybatis-Plus中`Mapper.xml`文件路径默认为:`classpath*:/mapper/**/*.xml`,可在`application.yml`中配置以下参数进行修改

XML 复制代码
mybatis-plus:
  mapper-locations: classpath*:/mapper/**/*.xml

2.测试

复制代码
@SpringBootTest
public class PageTest {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    @Test
    public void testPageService() {
        //创建分页对象,将按照传递的参数进行分页,此时展示第二页的两条数据(current:展示第几页 size:每页多少条数据)
        Page<User> userPage = new Page<>(2, 2);
        //调用通用service层方法进行分页查询,最终将分页结果返回
        Page<User> result = userService.page(userPage);
        result.getRecords().forEach(System.out::println);
    }

    @Test
    public void testPageMapper() {
        Page<User> userPage = new Page<>(2, 2);
        Page<User> result = userMapper.selectPage(userPage, null);
        result.getRecords().forEach(System.out::println);
    }

    //自定义分页查询,可用于处理复杂业务
    @Test
    public void testSelectPage() {
        Page<User> userPage = new Page<>(2,2);
        IPage<User> result = userMapper.selectUserPage(userPage);
        result.getRecords().forEach(System.out::println);
    }
}
相关推荐
DieSnowK4 分钟前
[C++][设计模式][备忘录模式]详细讲解
开发语言·c++·设计模式·重构·面向对象·备忘录模式·新手向
左手の明天19 分钟前
【Python网络爬虫案例】python爬虫之模拟登录
开发语言·爬虫·python·模拟登录
游王子34 分钟前
Springboot与xxl-job
java·spring boot·后端
秋刀prince40 分钟前
【JD-GUI】MacOS 中使用Java反编译工具JD-GUI
java·macos·策略模式
mumu_wangwei1 小时前
【PHP】实现类的无缝动态扩展,设计模式,php工厂模式应用场景,以下代码是工厂模式在框架设计中的真实使用案例代码
开发语言·设计模式·php
lsjweiyi1 小时前
sitemap.xml生成(go语言版)
开发语言·golang·sitemap.xml
CoCo玛奇朵1 小时前
CleanMyMacX2024免费且强大的mac电脑系统优化工具
开发语言·javascript·macos·ffmpeg·ecmascript·百度云
Itmastergo1 小时前
零基础小白学习 Python,应该如何配置 Python 开发环境?(包含Windows、MacOS、Linux)
开发语言·python·学习
Dongliner~1 小时前
【C++:list】
开发语言·c++
nbplus_0071 小时前
golang跨平台GUI框架fyne介绍与使用详解,开放案例
开发语言·后端·安全·golang·个人开发