开发者

SpringBoot整合MybatisPlus的基本应用指南

目录
  • 一、MyBATisPlus简介
  • 二、SpringBoot整合MybatisPlus
    • 1、创建数据库和表
    • 2.添加数据
    • 3.创建一个SpringBoot项目
    • 4.导入依赖
    • 5.修改application.yml文件
    • 6.创建实体User的类 
    • 7.添加mapper
  • 三、基本的CRUD操作 
    • 1.查询所有用户
    • 2.插入用户 
    • 3.删除用户 
    • 4.更新用户 
    • 5.添加MybatisPlus日志
  • 四、service封装mapper
    • 1.查询所有用户
  •  五、BaseMapper常用方法

    一、MybatisPlus简介

    先来看一下官方的简介吧。

    MyBatis-Plus (简称 MP)是一个 MyBatis的增强工具,在 MyBatis 的基础上只做增强不做改变,为 简化开发、提高效率而生。Mybatis-Plus提供了通用的Mapper和Service,可以在不编写任何SQL语句的前提下,快速的实现单表的增删改查(CURD),批量,逻辑删除,分页等操作。只要把MyBatis-Plus的特性到优秀插件,以及多数据源的配置进行详细讲解。

    我们的愿景是成为 MyBatis 最好的搭档,就像魂斗罗中的 1P、2P ,基友搭配,效率翻倍。

    SpringBoot整合MybatisPlus的基本应用指南

    MybatisPlus的特性 

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

    损耗小:启动即会自动注入基本 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、SQLServejavascriptr 等多种数据库

    内置性能分析插件:可输出 SQL 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询

    内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作

    想要更多的了解MybatisPlus,可以到官网去看一下 MyBatis-Plus (baomidou.com)

    我们直接上手讲解SpringBoot项目如何整合MybatisPlus。

    二、SpringBoot整合MybatisPlus

    1、创建数据库和表

    CREATE DATABASE `mybatis_plus` /*!40100 DEFAULT CHARACTER SET utf8mb4 */; use `mybatis_plus`;
    CREATE TABLE `user` (
    `id` bigint(20) NOT NULL COMMENT '主键ID',
    `name` varchar(30) DEFAULT NULL COMMENT '姓名 ',
    `age` int(11) DEFAULT NUjavascriptLL COMMENT '年龄 ',
    `email` varchar(50) DEFAULT NULL COMMENT '邮箱 ',
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

    2.添加数据

    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');

    3.创建一个SpringBoot项目

    因为我没有配置阿里的服务器,所以创建的springboot项目没有Java8版本,我是后期自己修改的,并且使用springboot2.7.16版本,大家可以配置一下服务器URL。之后就可以创建8版本了。

    https://start.aliyun.com

    SpringBoot整合MybatisPlus的基本应用指南

    项目结构。 我把application.properties文件修改为了yml格式。

    SpringBoot整合MybatisPlus的基本应用指南

    4.导入依赖

    如果想要使用lombok插件需要在设置中找到插件,下载lombok插件。lombok可以简化我们的开发。

            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>3.5.2</version>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.5</version>
            </dependency>

    创建我们需要的包。

    SpringBoot整合MybatisPlus的基本应用指南

    5.修改application.yml文件

    这里的密码需要根据你自己的情况修改。

    spring:
      # 配置数据源信息
      datasource:
      # 配置连接数据库信息
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=false
        username: root
        password: 2020

    6.创建实体User的类 

    在domain目录下创建User类。

    @Data
    public class User {
        //设定id自增
        @TableId(type = IdType.AUTO)
        private Integer id;
        private String name;
        private Integer age;
        private String email;
    }

    7.添加mapper

    在mapper目录下创建UserMapper。UserMapper继承BaseMapper,BaseMapper中封装着一些基本的增删改查操作,这样就不用我们在自己写dao层了。

    @Mapper
    public interface UserMapper extends BaseMapper<User> {
    }

    三、基本的CRUD操作 

    我们在test方法中实现测试。

    1.查询所有用户

    调用selectList()方法,方法需要传入一个参数qphpueryWrapper,queryWrapper相当于sql语句中的一些限制条件(这里不必在意我的输出结果,数据库的表格我已经变动过了,大家只要有输出即可)。

    @Test
        void getAllUser(){
            List<User> users = userMapper.selectList(null);
            for (User user : users) {
                System.out.println(user);
            }
        }

    SpringBoot整合MybatisPlus的基本应用指南

    2.插入用户 

    这里可能会报错,提示id不存在,我们要把数据库当中的id字段改为自动递增。

     @Test
        public void testInsert(){
            User user = new User(null, "哈__", 23, "ha@test.com");
            //INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
            int result = userMapper.insert(user);
            System.out.println("受影响行数:"+result);
            System.out.println("id自动获取:"+user.getId());
        }

    SpringBoot整合MybatisPlus的基本应用指南

    3.删除用户 

    @Test
        public void testDeleteById(){
            //通过id删除用户信息
            //DELETE FROM user WHERE id=?
            int result = userMapper.deleteById(9);
            System.out.println("受影响行数:"+result);
        }

    SpringBoot整合MybatisPlus的基本应用指南

    4.更新用户 

    根据传入的user的id更新,如果user中的某些字段为null,那么mybatisplus不会把值为null的属性向数据库进行更新。

    @Test
        public void testUpdateById(){
            User user = new User(1, "admin", 22, null);
            //UPDATE user SET name=?, age=? WHEjavascriptRE id=?
            int result = userMapper.updateById(user);
            System.out.println("受影响行数:"+result);
        }

    5.添加MybatisPlus日志

    在application.pythonyml文件当中写入如下配置。

    mybatis-plus:
      configuration:
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

     看效果。

    SpringBoot整合MybatisPlus的基本应用指南

    四、service封装mapper

    在service包下创建IUserService接口。并创建impl包,在service.impl包下创建UserServiceImpl。

    public interface IUserService extends IService<User> {
    }
    @Service
    public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService{
    }

    通过service调用mapper。MybatisPlus官方已经帮我们封装好了。

    1.查询所有用户

     @Resource
        UserServiceImpl userService;
        @Test
        void getAllUser(){
            List<User> users = userService.list();
            for (User user : users) {
                System.out.println(user);
            }
        }

    SpringBoot整合MybatisPlus的基本应用指南

    其他的就不在展示了,大家可以自己探索一下。 

     五、BaseMapper常用方法

    package com.baomidou.mybatisplus.core.mapper;
     
    public interface BaseMapper<T> extends Mapper<T> {
     
    /**
    * 插入一条记录
    * @param entity 实体对象 */
    int insert(T entity);
     
    /**
    * 根据 ID 删除
    * @param id 主键ID */
    int deleteById(Serializable id);
     
    /**
    * 根据实体(ID)删除
    * @param entity 实体对象
    * @since 3.4.4 */
    int deleteById(T entity);
     
    /**
    * 根据 columnMap 条件,删除记录
    * @param columnMap 表字段 map 对象 */
    int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
     
    /**
    * 根据 entity 条件,删除记录
    * @param queryWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where
    语句)
    */
    int delete(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
     
    /**
    * 删除(根据ID 批量删除)
    * @param idList 主键ID列表(不能为 null 以及 empty) */
    int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
     
    /**
    * 根据 ID 修改
    * @param entity 实体对象 */
    int updateById(@Param(Constants.ENTITY) T entity);
     
    /**
    * 根据 whereEntity 条件,更新记录
    * @param entity        实体对象 (set 条件值 ,可以为 null)
    * @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成
    where 语句)
    */
    int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);
     
    /**
    * 根据 ID 查询
    * @param id 主键ID */
    T selectById(Serializable id);
     
    /**
    * 查询(根据ID 批量查询)
    * @param idList 主键ID列表(不能为 null 以及 empty) */
    List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
     
    /**
    * 查询(根据 columnMap 条件)
    * @param columnMap 表字段 map 对象 */
    List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
     
    /**
    * 根据 entity 条件,查询一条记录
    * <p>查询一条记录,例如 qw.last("limit 1") 限制取一条记录 , 注意:多条数据会报异常 </p>
    * @param queryWrapper 实体对象封装操作类(可以为 null)
    */
    default T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper) { List<T> ts = this.selectList(queryWrapper);
    if (CollectionUtils.isNotEmpty(ts)) {
    if (ts.size() != 1) {
    throw ExceptionUtils.mpe("One record is expected, but the query result is multiple records");
    }
    return ts.get(0);
    }
    return null;
    }
     
    /**
    * 根据 Wrapper 条件,查询总记录数
    * @param queryWrapper 实体对象封装操作类(可以为 null) */
    Long selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
     
    /**
    * 根据 entity 条件,查询全部记录
    * @param queryWrapper 实体对象封装操作类(可以为 null) */
    List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
     
    /**
    * 根据 Wrapper 条件,查询全部记录
    * @param queryWrapper 实体对象封装操作类(可以为 null) */
    List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
     
    /**
    * 根据 Wrapper 条件,查询全部记录
    * <p>注意: 只返回第一个字段的值</p>
    * @param queryWrapper 实体对象封装操作类(可以为 null) */
    List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
     
    /**
    * 根据 entity 条件,查询全部记录(并翻页)
    * @param page         分页查询条件(可以为 RowBounds.DEFAULT)
    * @param queryWrapper 实体对象封装操作类(可以为 null) */
    <P extends IPage<T>> P selectPage(P page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
     
    /**
    * 根据 Wrapper 条件,查询全部记录(并翻页)
    * @param page         分页查询条件
    * @param queryWrapper 实体对象封装操作类 */
    <P extends IPage<Map<String, Object>>> P selectMapsPage(P page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    以上就是SpringBoot整合MybatisPlus的基本应用指南的详细内容,更多关于SpringBoot整合MybatisPlus的资料请关注编程客栈(www.devze.com)其它相关文章!

    0

    上一篇:

    下一篇:

    精彩评论

    暂无评论...
    验证码 换一张
    取 消

    最新开发

    开发排行榜