mybatisPlus学习

10 篇文章 0 订阅
4 篇文章 0 订阅

mybatisPlus学习

mybatisPlus:https://mp.baomidou.com/guide/

第一章 快速入门

1.1 简介

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

1.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 操作智能分析阻断,也可自定义拦截规则,预防误操作

1.3 快速入门

  • 创建数据库

    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)
    );
    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');
    
  • 初始化工程

    创建一个空的 Spring Boot 工程

  • 添加依赖

    <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>Latest Version</version>
    </dependency>
    <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.23</version>
    </dependency>
    <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.20</version>
                <scope>provided</scope>
    </dependency>
    
  • 配置

    #application.yml
    #端口配置
    server:
      port: 8008
      
    #数据库连接配置
    spring:
      datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        username: root
        password: 123456
        url: jdbc:mysql://localhost:3306/xxx?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2b8
        
    #配置日志:sql不可见,若想知道执行流程,配置日志;开发需要,上线不需要;缺点:浪费时间
    mybatis-plus:
      configuration:
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    ....
    

​ 在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 文件夹:

  • 编码

    • 编写实体类 entity

      @Data
      public class User {
          private Long id;
          private String name;
          private Integer age;
          private String email;
      }
      
    • 编写mapper类

      public interface UserMapper extends BaseMapper<User> {
      
      }
      
    • 编写测试类

      @SpringBootTest
      public class SampleTest {
      
          @Autowired
          private UserMapper userMapper;
          
          @Test
          public void testSelect() {
              List<User> userList = userMapper.selectList(null);
             for(User user:userList){
                 System.out.println(user);
             }
          }
      }
      
    • 运行窗口

      /*运行窗口*/
      Creating a new SqlSession
      SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2152ab30] was not registered for synchronization because synchronization is not active
      2021-06-01 12:51:23.979  INFO 14976 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
      2021-06-01 12:51:24.771  INFO 14976 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
      JDBC Connection [HikariProxyConnection@1802415698 wrapping com.mysql.cj.jdbc.ConnectionImpl@d4df0e] will not be managed by Spring
      ==>  Preparing: SELECT id,name,age,email FROM tb_user
      ==> Parameters: 
      <==    Columns: id, name, age, email
      <==        Row: 1, Jone, 18, test1@baomidou.com
      <==        Row: 2, Jack, 20, test2@baomidou.com
      <==        Row: 3, Tom, 28, test3@baomidou.com
      <==        Row: 4, Sandy, 21, test4@baomidou.com
      <==        Row: 5, Billie, 24, test5@baomidou.com
      <==      Total: 5
      Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2152ab30]
      User(id=1, name=Jone, age=18, email=test1@baomidou.com)
      User(id=2, name=Jack, age=20, email=test2@baomidou.com)
      User(id=3, name=Tom, age=28, email=test3@baomidou.com)
      User(id=4, name=Sandy, age=21, email=test4@baomidou.com)
      User(id=5, name=Billie, age=24, email=test5@baomidou.com)
      

1.4 常用注解

  • @TableName 表名注解

    属性类型描述
    valueString表名
  • @TableId 主键注解

    属性类型描述可选值
    valueString主键字段名
    typeEnum主键类型IdType.AUTO …数据库id自增,表id需设为自增
  • @TableField 字段注解(非主键)

    属性类型描述
    valueString数据库字段名
    existBoolean是否为数据库表字段

1.5 条件构造器

适用于复杂的SQL,支持链式

  • AbstractWrapper
//名字、邮箱不为空且年龄为大于12
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.isNotNull("name")
       .isNotNull("email")
       .ge("age",12);
List<User> users = userMapper.selectList(wrapper);
for(User user:users){
    System.out.println(user);
}
函数说明举例
eq、ne= 、 !=eq("name", "老王")—>name = '老王'
It 、Ie< 、 <=lt(“age”, 18)--->age < 18
gt、ge> 、 >=ge("age", 18)—>age >= 18
like、notLikeLIKE ‘%值%’like(“name”, “王”)--->name like ‘%王%’
isNotNull字段 IS NULLisNotNull(“name”)--->name is not null
betweenBETWEEN 值1 AND 值2between(“age”, 18, 30)--->age between 18 and 30
orderByDesc降序orderByDesc(“score”)--->order by Score DESC

第二章 核心功能

2.1 CRUD接口

2.1.1 Mapper CRUD接口
/*
说明:
(1)通用CRUD封装BaseMapper接口,为Mybatis-Plus启动时自动解析实体表关系映射转换为Mybatis内部对象注入容器
(2)泛型T为任意实体对象
(3)参数Serializable为任意类型主键 
(4)Mybatis-Plus不推荐使用复合主键,约定每一张表都有自己的唯一id主键
(5)对象Wrapper为条件构造器,可为null
*/
int insert(T entity);//插入一条记录

int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);// 根据 entity 条件,删除记录
int deleteById(Serializable id);// 根据 ID 删除

int updateById(@Param(Constants.ENTITY) T entity);// 根据ID修改


T selectById(Serializable id);// 根据 ID 查询
T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);//根据entity条件,查询一条记录
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);//查询所有
2.1.2 Service CRUD接口
/*
说明:
(1)Service CRUD封装IService接口,进一步封装CRUD采用
    get查询单行 、remove删除 、list查询集合 、page 分页 
(2)泛型T为任意实体对象
(3)对象Wrapper为条件构造器,可为null
*/
UserService.java
public interface UserService extends IService<User> {}

UserServiceImpl.java
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {}
boolean save(T entity);// 插入一条记录(选择字段,策略插入)


boolean remove(Wrapper<T> queryWrapper);// 根据 entity 条件,删除记录
boolean removeById(Serializable id);// 根据 ID 删除

boolean update(Wrapper<T> updateWrapper);//根据UpdateWrapper条件,更新记录需要设置sqlset
boolean updateById(T entity);// 根据ID选择修改


T getById(Serializable id);// 根据 ID 查询
T getOne(Wrapper<T> queryWrapper);
List<T> list();// 查询所有

IPage<T> page(IPage<T> page);// 无条件分页查询
IPage<T> page(IPage<T> page, Wrapper<T> queryWrapper);// 条件分页查询

int count();// 查询总记录数

运行窗口

Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@70c69586] was not registered for synchronization because synchronization is not active
2021-06-01 19:49:39.644  INFO 8288 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2021-06-01 19:49:42.239  INFO 8288 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
JDBC Connection [HikariProxyConnection@825605925 wrapping com.mysql.cj.jdbc.ConnectionImpl@22ad1bae] will not be managed by Spring
==>  Preparing: INSERT INTO tb_user ( name, age, email ) VALUES ( ?, ?, ? )
==> Parameters: 王与(String), 20(Integer), 1838649203@qq.com(String)
<==    Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@70c69586]
true

2.2 分页插件

编写配置类

//Spring boot方式
@Configuration
public class MyConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

测试

 @Test
    void test6() {
        IPage<User> userPage = new Page<>(1, 2);//参数一是当前页,参数二是每页个数
        userPage = userMapper.selectPage(userPage, null);
        List<User> users = userPage.getRecords();
        for (User user : users) {
            System.out.println(user);
        }
    }
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值