• 在若依Ruoyi-Vue中集成mybatisplus实现mybatis增强


    本文相关视频:https://www.bilibili.com/video/BV1Fi4y1q74p?p=50&vd_source=2894aa0e46c09ba98269f266128b6c6e

    若依(Ruoyi)作为一款优秀的基于Spring Boot和Vue.js的企业级后台管理系统,其良好的架构设计和丰富的功能组件深受开发者喜爱。然而,为了进一步强化数据访问能力,本文将详细介绍如何在若依-Ruoyi-Vue项目中集成MyBatisPlus,实现MyBatis的增强。

    一、MyBatisPlus简介

    MyBatisPlus是基于MyBatis的一款优秀持久层框架增强工具,它在MyBatis的基础上提供了丰富而强大的CRUD操作、条件构造器、全局通用操作、代码生成器等特性,极大地简化了开发过程,提升了开发效率。MyBatisPlus通过无侵入式的设计理念,使得在享受其带来的便利同时,无需对现有MyBatis项目进行大规模改造。

    二、集成步骤

    1. 添加依赖

    ruoyi-common\pom.xml模块添加整合依赖

    
    <dependency>
    	<groupId>com.baomidougroupId>
    	<artifactId>mybatis-plus-boot-starterartifactId>
    	<version>3.5.1version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    2. 配置MyBatisPlus

    ruoyi-admin文件application.yml,修改mybatis配置为mybatis-plus

    # MyBatis Plus配置
    mybatis-plus:
      # 搜索指定包别名
      typeAliasesPackage: com.ruoyi.**.domain
      # 配置mapper的扫描,找到所有的mapper.xml映射文件
      mapperLocations: classpath*:mapper/**/*Mapper.xml
      # 加载全局的配置文件
      configLocation: classpath:mybatis/mybatis-config.xml
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    3. 添加Mybatis Plus配置MybatisPlusConfig.java

    特别注意:原来的MyBatisConfig.java需要删除掉

    package com.ruoyi.framework.config;
    
    import com.baomidou.mybatisplus.annotation.DbType;
    import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
    import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
    import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
    import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.transaction.annotation.EnableTransactionManagement;
    
    /**
     * Mybatis Plus 配置
     * 
     * @author ruoyi
     */
    @EnableTransactionManagement(proxyTargetClass = true)
    @Configuration
    public class MybatisPlusConfig
    {
        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor()
        {
            MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
            // 分页插件
            interceptor.addInnerInterceptor(paginationInnerInterceptor());
            // 乐观锁插件
            interceptor.addInnerInterceptor(optimisticLockerInnerInterceptor());
            // 阻断插件
            interceptor.addInnerInterceptor(blockAttackInnerInterceptor());
            return interceptor;
        }
    
        /**
         * 分页插件,自动识别数据库类型 https://baomidou.com/guide/interceptor-pagination.html
         */
        public PaginationInnerInterceptor paginationInnerInterceptor()
        {
            PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
            // 设置数据库类型为mysql
            paginationInnerInterceptor.setDbType(DbType.MYSQL);
            // 设置最大单页限制数量,默认 500 条,-1 不受限制
            paginationInnerInterceptor.setMaxLimit(-1L);
            return paginationInnerInterceptor;
        }
    
        /**
         * 乐观锁插件 https://baomidou.com/guide/interceptor-optimistic-locker.html
         */
        public OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor()
        {
            return new OptimisticLockerInnerInterceptor();
        }
    
        /**
         * 如果是对全表的删除或更新操作,就会终止该操作 https://baomidou.com/guide/interceptor-block-attack.html
         */
        public BlockAttackInnerInterceptor blockAttackInnerInterceptor()
        {
            return new BlockAttackInnerInterceptor();
        }
    }
    
    • 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

    4. 添加测试表

    drop table if exists sys_student;
    create table sys_student (
      student_id           int(11)         auto_increment    comment '编号',
      student_name         varchar(30)     default ''        comment '学生名称',
      student_age          int(3)          default null      comment '年龄',
      student_hobby        varchar(30)     default ''        comment '爱好(0代码 1音乐 2电影)',
      student_sex          char(1)         default '0'       comment '性别(0男 1女 2未知)',
      student_status       char(1)         default '0'       comment '状态(0正常 1停用)',
      student_birthday     datetime                          comment '生日',
      primary key (student_id)
    ) engine=innodb auto_increment=1 comment = '学生信息表';
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    5. 新增测试代码验证

    新增 ruoyi-system\com\ruoyi\system\domain\SysStudent.java

    package com.ruoyi.system.domain;
    
    import java.io.Serializable;
    import java.util.Date;
    import org.apache.commons.lang3.builder.ToStringBuilder;
    import org.apache.commons.lang3.builder.ToStringStyle;
    import com.baomidou.mybatisplus.annotation.IdType;
    import com.baomidou.mybatisplus.annotation.TableField;
    import com.baomidou.mybatisplus.annotation.TableId;
    import com.baomidou.mybatisplus.annotation.TableName;
    import com.fasterxml.jackson.annotation.JsonFormat;
    import com.ruoyi.common.annotation.Excel;
    
    /**
     * 学生信息对象 sys_student
     *
     * @author ruoyi
     */
    @TableName(value = "sys_student")
    public class SysStudent implements Serializable
    {
        @TableField(exist = false)
        private static final long serialVersionUID = 1L;
    
        /** 编号 */
        @TableId(type = IdType.AUTO)
        private Long studentId;
    
        /** 学生名称 */
        @Excel(name = "学生名称")
        private String studentName;
    
        /** 年龄 */
        @Excel(name = "年龄")
        private Integer studentAge;
    
        /** 爱好(0代码 1音乐 2电影) */
        @Excel(name = "爱好", readConverterExp = "0=代码,1=音乐,2=电影")
        private String studentHobby;
    
        /** 性别(0男 1女 2未知) */
        @Excel(name = "性别", readConverterExp = "0=男,1=女,2=未知")
        private String studentSex;
    
        /** 状态(0正常 1停用) */
        @Excel(name = "状态", readConverterExp = "0=正常,1=停用")
        private String studentStatus;
    
        /** 生日 */
        @JsonFormat(pattern = "yyyy-MM-dd")
        @Excel(name = "生日", width = 30, dateFormat = "yyyy-MM-dd")
        private Date studentBirthday;
    
        public void setStudentId(Long studentId)
        {
            this.studentId = studentId;
        }
    
        public Long getStudentId()
        {
            return studentId;
        }
        public void setStudentName(String studentName)
        {
            this.studentName = studentName;
        }
    
        public String getStudentName()
        {
            return studentName;
        }
        public void setStudentAge(Integer studentAge)
        {
            this.studentAge = studentAge;
        }
    
        public Integer getStudentAge()
        {
            return studentAge;
        }
        public void setStudentHobby(String studentHobby)
        {
            this.studentHobby = studentHobby;
        }
    
        public String getStudentHobby()
        {
            return studentHobby;
        }
        public void setStudentSex(String studentSex)
        {
            this.studentSex = studentSex;
        }
    
        public String getStudentSex()
        {
            return studentSex;
        }
        public void setStudentStatus(String studentStatus)
        {
            this.studentStatus = studentStatus;
        }
    
        public String getStudentStatus()
        {
            return studentStatus;
        }
        public void setStudentBirthday(Date studentBirthday)
        {
            this.studentBirthday = studentBirthday;
        }
    
        public Date getStudentBirthday()
        {
            return studentBirthday;
        }
    
        @Override
        public String toString() {
            return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
                    .append("studentId", getStudentId())
                    .append("studentName", getStudentName())
                    .append("studentAge", getStudentAge())
                    .append("studentHobby", getStudentHobby())
                    .append("studentSex", getStudentSex())
                    .append("studentStatus", getStudentStatus())
                    .append("studentBirthday", getStudentBirthday())
                    .toString();
        }
    }
    
    • 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

    新增 ruoyi-system\com\ruoyi\system\mapper\SysStudentMapper.java

    package com.ruoyi.system.mapper;
    
    import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    import com.ruoyi.system.domain.SysStudent;
    
    /**
     * 学生信息Mapper接口
     *
     * @author ruoyi
     */
    public interface SysStudentMapper extends BaseMapper<SysStudent>
    {
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    新增 ruoyi-system\com\ruoyi\system\service\impl\SysStudentServiceImpl.java

    package com.ruoyi.system.service.impl;
    
    import java.util.List;
    import org.springframework.stereotype.Service;
    import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    import com.baomidou.mybatisplus.core.toolkit.Wrappers;
    import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    import com.ruoyi.common.utils.StringUtils;
    import com.ruoyi.system.domain.SysStudent;
    import com.ruoyi.system.mapper.SysStudentMapper;
    
    /**
     * 学生信息Service业务层处理
     *
     * @author ruoyi
     */
    @Service
    public class SysStudentServiceImpl extends ServiceImpl<SysStudentMapper, SysStudent>
    {
        public List<SysStudent> queryList(SysStudent sysStudent)
        {
            // 注意:mybatis-plus lambda 模式不支持 eclipse 的编译器
            // LambdaQueryWrapper queryWrapper = Wrappers.lambdaQuery();
            // queryWrapper.eq(SysStudent::getStudentName, sysStudent.getStudentName());
            QueryWrapper<SysStudent> queryWrapper = Wrappers.query();
            if (StringUtils.isNotEmpty(sysStudent.getStudentName()))
            {
                queryWrapper.eq("student_name", sysStudent.getStudentName());
            }
            if (StringUtils.isNotNull(sysStudent.getStudentAge()))
            {
                queryWrapper.eq("student_age", sysStudent.getStudentAge());
            }
            if (StringUtils.isNotEmpty(sysStudent.getStudentHobby()))
            {
                queryWrapper.eq("student_hobby", sysStudent.getStudentHobby());
            }
            return this.list(queryWrapper);
        }
    }
    
    • 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

    编写测试类测试:

    package com.ruoyi.service;
    
    import com.ruoyi.RuoYiApplication;
    import com.ruoyi.system.domain.SysStudent;
    import com.ruoyi.system.service.impl.SysStudentServiceImpl;
    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;
    
    import java.util.List;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = RuoYiApplication.class)
    public class SysStudentServiceTest {
        @Autowired
        private SysStudentServiceImpl sysStudentService;
    
        @Test
        public void test() {
            SysStudent student = new SysStudent();
            List<SysStudent> sysStudents = sysStudentService.queryList(student);
            sysStudents.forEach(System.out::println);
        }
    }
    
    
    • 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

    在这里插入图片描述

    三、MyBatisPlus增强特性应用

    集成MyBatisPlus后,即可在项目中充分利用其增强特性,提升开发效率和代码质量。以下列举部分典型应用场景:

    1. CRUD操作

    MyBatisPlus提供了诸如insert(), deleteById(), updateById(), selectById()等基本CRUD方法,只需简单调用即可完成对应操作,无需编写SQL语句。

    2. 条件构造器

    通过Wrappers.lambdaQuery()Wrappers.query()可以构建复杂查询条件,支持动态拼接SQL,如:

    List<User> users = userMapper.selectList(
        Wrappers.lambdaQuery(User.class)
            .eq(User::getId, userId)
            .like(User::getUsername, "%admin%")
    );
    
    • 1
    • 2
    • 3
    • 4
    • 5

    3. 全局通用操作

    MyBatisPlus提供了诸如list(), page(), count()等全局通用方法,可快速进行列表查询、分页查询、统计计数等操作。

    4. 代码生成器

    利用MyBatisPlus的代码生成器,可以一键生成实体类、Mapper接口、Mapper XML文件、Service接口、ServiceImpl类、Controller类等全套代码,极大减轻重复劳动。

  • 相关阅读:
    cookie加密解密和保证数据完整性(不被篡改)
    conda 基本用法
    java毕业设计智能分析的简单聚众筹平台Mybatis+系统+数据库+调试部署
    在亚马逊购买产品时怎么选择自动收货方式
    上周热点回顾(6.27-7.3)
    reportportal 集成 robotframework 自动化执行及结果可视化
    java毕业设计中华美食文化网站Mybatis+系统+数据库+调试部署
    CodeTON Round 2补题(A-E)
    PCB走线的传输延时有多少
    Java安全之Mojarra JSF反序列化
  • 原文地址:https://blog.csdn.net/qq_27575627/article/details/138164844