SpringBoot整合MybatisPlus

本文介绍了MyBatis-Plus(MP)的基本概念和特性,包括它的无侵入性、高性能以及丰富的CRUD操作支持。通过创建SpringBoot项目,导入依赖,配置文件,展示了如何进行简单的CRUD操作。此外,还详细讲解了如何使用MP进行联表查询和分页操作,包括配置分页插件,编写Mapper接口和XML文件,以及测试查询方法。
摘要由CSDN通过智能技术生成

目录

目录

1.mp简介

2.特性

3.快速入门CRUD

(1)创建springboot项目

(2)导入依赖

(3)配置文件application.properties

(4)表的实体类 

(5)表的接口

(6)测试CRUD

4.联表操作查询-----使用mp的分页对象

(1)创建MybatisPlusConfig.java

(2)StudentMapper.java中添加分页

(3)StudentMapper.xml文件

(4)测试



1.mp简介

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

愿景

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

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

3.快速入门CRUD

(1)创建springboot项目

  搭建项目http://t.csdn.cn/mwIUl

(2)导入依赖

以下是该工程所有的依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.12.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>springboot03</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot03</name>
    <description>springboot03</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>

        <!--引入QUARTZ定时器依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-quartz</artifactId>
        </dependency>

        <!--mp依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>


        <!--swagger的依赖引入-->
        <dependency>
            <groupId>io.github.jianzhichun</groupId>
            <artifactId>spring-boot-starter-swagger2</artifactId>
            <version>0.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.6</version>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.3.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

(3)配置文件application.properties

#数据源信息
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# characterEncoding防止您添加到数据的数据出现乱码。
spring.datasource.url=jdbc:mysql://localhost:3306/qy165ssm?serverTimezone=Asia/Shanghai&characterEncoding=UTF8
spring.datasource.username=root
spring.datasource.password=123456789

#指定映射文件的路径--链表操作
mybatis-plus.mapper-locations=classpath:/mapper/*.xml

#sql日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

(4)表的实体类 

@Data //学生信息表
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "student")  //解决表名与实体类名不一致
public class Student {
    @TableId(type = IdType.AUTO)
    private Integer sid;
    private String sname;
    private Integer age;
    private String sex;
    private Integer class_id;
    @TableField(value = "headImg")
    private String headImg="https://aaa165.oss-cn-beijing.aliyuncs.com/wz.jpg"; //随便填一个照片路径,目前用于测试
    @TableField(exist = false)
    private Clazz clazz;
}





@Data  //班级表
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "class")  //解决表名与实体类名不一致
public class Clazz {
    private Integer cid;
    private String cname;
}

  • @TableName(value = "") //如果没有添加该注解默认实体类映射对应的表名
  • @TableId(value = "") //标记该属性为表的主键列,属性名和主键列名映射
  • @TableField(value = "")让属性名和列名映射
     

(5)表的接口

@Mapper
public interface StudentMapper extends BaseMapper<Student> {

   
}

(6)测试CRUD

@SpringBootTest
class Springboot04ApplicationTests {


    @Autowired
    private StudentDao studentMapper;

    //根据id查询
    @Test
    void selectById() {
        Student student = studentMapper.selectById(3);
        System.out.println(student);
    }

    //添加
    @Test
    void testInsert() {
        Student student = new Student();
        student.setSid(null);
        student.setSname("张三01");
        student.setAge(30);
        student.setSex("男");
        student.setClass_id(1);
        student.setHeadImg(null);

        int insert = studentMapper.insert(student);
        System.out.println(insert);
    }

    //删
    @Test
    void deleteById() {
        //根据id删除
//        int i = studentDao.deleteById(9);
//        System.out.println(i);


        //批量删除
//        List<Integer> ids= Arrays.asList(10,11,12);
//        int i1 = studentDao.deleteBatchIds(ids);
//        System.out.println("受影响的行数:"+i1);

        //条件删除
        UpdateWrapper<Student> wrapper = new UpdateWrapper<>(); //修改的条件构造器
        wrapper.like("sname", "王"); //模糊查询
        wrapper.gt("age", 18);   //大于18   ge:大于等于   lt:小于   le:小于等于   ne:不等于
        wrapper.between("age", 18, 25);  //年龄区间:18-25之间
        studentMapper.delete(wrapper); //wrapper对象:条件构造器

    }

    //改
    @Test
    void testUpdate() {
        Student student = new Student();
        student.setSid(6);
        student.setSname("张三01");
        student.setAge(30);
        student.setSex("男");
        student.setClass_id(1);
        student.setHeadImg(null);

        int i = studentMapper.updateById(student);
        System.out.println("受影响的行数:" + i);
    }



    //条件查询
    @Test
    void testSelect() {
        //批量查询
//        List<Integer> ids = Arrays.asList(3,5,6);
//        List<Student> studentList = studentDao.selectBatchIds(ids);
//        System.out.println(studentList);

        //根据条件查询
//        QueryWrapper<Student> wrapper = new QueryWrapper<>();
//        wrapper.select("sname","age");  //查询指定的列
//        wrapper.orderByDesc("age");   //排序
//       // wrapper.groupBy("sname"); //分组
//        List<Student> students = studentDao.selectList(wrapper); //根据条件查询,如果传递的对象为null则查询全部
//        System.out.println(students);

        //根据条件查询一条记录  selectOne
        QueryWrapper<Student>wrapper1 = new QueryWrapper<>();
        wrapper1.eq("sname","张三");
        Student student = studentMapper.selectOne(wrapper1);
        System.out.println(student);
    }
}

4.联表操作查询-----使用mp的分页对象

(1)创建MybatisPlusConfig.java

@Configuration
public class MybatisPlusConfig {

    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.setUseDeprecatedExecutor(false);
    }
}

(2)StudentMapper.java中添加分页

@Mapper
public interface StudentMapper extends BaseMapper<Student> {

    /*分页*/
    IPage<Student>findPage(IPage<Student> iPage , @Param("ew") Wrapper<Student> wrapper);

}

(3)StudentMapper.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.wqg.mapper.StudentMapper">



        <resultMap id="BaseResultMap" type="com.wqg.pojo.Student">
            <id property="sid" column="sid" jdbcType="INTEGER"/>
            <result property="sname" column="sname" jdbcType="VARCHAR"/>
            <result property="age" column="age" jdbcType="INTEGER"/>
            <result property="sex" column="sex" jdbcType="CHAR"/>
            <result property="class_id" column="class_id" jdbcType="INTEGER"/>
            <result property="headImg" column="headImg" jdbcType="VARCHAR"/>
            <association property="clazz" javaType="com.wqg.pojo.Clazz"
                         autoMapping="true">
                <id column="cid" property="cid"/>
            </association>
        </resultMap>
        <sql id="Base_Column_list">
            sid,sname,age,sex,class_id,headImg,cid,cname
        </sql>

        <select id="findPage" resultMap="BaseResultMap">
            select
            <include refid="Base_Column_list"/>
            from student  join class
            on class_id = cid
            <if test="ew != null and ew.CustomSqlSegment != null">
             ${ew.customSqlSegment}
            </if>
        </select>


</mapper>

(4)测试


    //联表操作查询-----使用mp的分页对象
    @Test
    void testPage2() {
        Page<Student> page = new Page<>(1, 3);
        QueryWrapper<Student> wrapper = new QueryWrapper<>();
        studentMapper.findPage(page, wrapper);
        //====可以加条件====
        System.out.println("当前页的记录:" + page.getRecords()); //获取当前页的记录
        System.out.println("总页数:" + page.getPages()); //获取总页数
        System.out.println("总条数:" + page.getTotal()); //获取总条数
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值