Mybatis-Plus入门案例以及使用方法

Mybatis-Plus简介

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

特性

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本 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 操作智能分析阻断,也可自定义拦截规则,预防误操作

支持的数据库

  • MySQL,Oracle,DB2,H2,HSQL,SQLite,PostgreSQL,SQLServer,Phoenix,Gauss ,ClickHouse,Sybase,OceanBase,Firebird,Cubrid,Goldilocks,csiidb
  • 达梦数据库,虚谷数据库,人大金仓数据库,南大通用(华库)数据库,南大通用数据库,神通数据库,瀚高数据库

框架结构

framework

入门案例

开发环境

JDK:JDK8+

构建工具:maven 3.5.4

MySQL版本:MySQL 8

Spring:5.3.1

MyBatis-Plus:3.4.3.4

创建数据库和表

  • 创建表
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 NULL COMMENT '年龄',
	`email` VARCHAR ( 50 ) DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY ( `id` ) 
) ENGINE = INNODB DEFAULT CHARSET = utf8;
  • 添加数据
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' );

创建maven工程

打包方式为jar

引入依赖

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.atguigu</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <spring.version>5.3.1</spring.version>
    </properties>

    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency> <!-- 连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency> <!-- junit测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency> <!-- MySQL驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.27</version>
        </dependency> <!-- 日志 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.30</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency> <!-- lombok用来简化实体类 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.16</version>
        </dependency> <!--MyBatis-Plus的核心依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>3.4.3.4</version>
        </dependency>
    </dependencies>

</project>

创建实体类User

package com.atguigu.mybatis.pojo;

import java.util.Objects;

public class User {
    private long id;
    private String name;
    private Integer age;
    private String email;

    public User() {
    }

    public User(long id, String name, Integer age, String email) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.email = email;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", email='" + email + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return id == user.id && Objects.equals(name, user.name) && Objects.equals(age, user.age) && Objects.equals(email, user.email);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name, age, email);
    }
}

创建mapper接口和映射文件

mapper

package com.atguigu.mybatisplus.mapper;

import com.atguigu.mybatisplus.pojo.User;

import java.util.List;

public interface UserMapper {
    /**
     * 查询所有用户
     * @return
     */
    List<User> getAllUser();
}

mapper映射文件

在resources下的com/atguigu/mybatisplus/mapper目录下创建UserMapper.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.atguigu.mybatisplus.mapper.UserMapper">
    <sql id="BaseColumns">id,name,age,email</sql>

    <!--List<User> getAllUser();-->
    <select id="getAllUser" resultType="user">
        select <include refid="BaseColumns"></include> from user
    </select>
</mapper>

创建Mybatis的核心配置文件

在resource下创建mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties resource="jdbc.properties"/>
    <typeAliases>
        <!--为所有实体类设置别名-->
        <package name="com.atguigu.mybatisplus.pojo"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <!--以包为单位引入映射文件-->
        <!--
            1、mapper接口要和映射文件的名字一致
            2、mapper接口所在的包路径和映射文件的包路径要一致
            注:在resources中创建包时,用/分割不是.
        -->
        <package name="com.atguigu.mybatisplus.mapper"/>
    </mappers>
</configuration>

创建jdbc.properties

resource下

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
jdbc.username=root
jdbc.password=root

创建spring的配置文件

在resources下创建applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 引入jdbc.properties -->
    <context:property-placeholder
            location="classpath:jdbc.properties"></context:property-placeholder> 
    <!-- 配置Druid数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean> 
    <!-- 配置用于创建SqlSessionFactory的工厂bean -->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 设置MyBatis配置文件的路径(可以不设置) -->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property> 
        <!-- 设置数据源 -->
        <property name="dataSource" ref="dataSource"></property> 
        <!-- 设置类型别名所对应的包 -->
        <property name="typeAliasesPackage"
                  value="com.atguigu.mybatisplus.pojo"></property>
        <!--设置映射文件的路径 若映射文件所在路径和mapper接口所在路径一致,则不需要设置 --> 
        <!--<property name="mapperLocations" value="classpath:mapper/*.xml"> </property> -->
    </bean> 
    <!--配置mapper接口的扫描配置 由mybatis-spring提供,可以将指定包下所有的mapper接口创建动态代理 并将这些动态代理作为IOC容器的bean管理 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.atguigu.mybatisplus.mapper"></property>
    </bean>
</beans>

添加日志功能

在resources下创建logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
    <!--定义日志文件的存储地址 logs为当前项目的logs目录 还可以设置为../logs -->
    <property name="LOG_HOME" value="logs"/>
    <!--控制台日志, 控制台输出 -->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符 宽度,%msg:日志消息,%n是换行符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
    </appender> <!--myibatis log configure-->
    <logger name="com.apache.ibatis" level="TRACE"/>
    <logger name="java.sql.Connection" level="DEBUG"/>
    <logger name="java.sql.Statement" level="DEBUG"/>
    <logger name="java.sql.PreparedStatement" level="DEBUG"/>
    <!-- 日志输出级别 -->
    <root level="DEBUG">
        <appender-ref ref="STDOUT"/>
    </root>
</configuration>

测试

方式一:通过IOC容器

package com.atguigu.mybatisplus.mapper;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UserMapperTest {
    @Test
    public void testgetAllUser() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper mapper = ac.getBean(UserMapper.class);
        mapper.getAllUser().forEach(user -> System.out.println(user));
    }
}

Spring整合Junit

package com.atguigu.mybatisplus.mapper;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

//在Spring的环境中进行测试
@RunWith(SpringJUnit4ClassRunner.class)
//指定Spring的配置文件
@ContextConfiguration("classpath:applicationContext.xml")
public class UserMapperTestBySpringAndJunit {
    @Autowired
    private UserMapper userMapper;

    @Test
    public void testMyBatisBySpring() {
        userMapper.getAllUser().forEach(user -> System.out.println(user));
    }
}

加入Mybatis-Plus

修改applicationContext.xml

加入mybatis-plus之后的配置文件,org.mybatis.spring.SqlSessionFactoryBean换成了com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 引入jdbc.properties -->
    <context:property-placeholder
            location="classpath:jdbc.properties"></context:property-placeholder>
    <!-- 配置Druid数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!-- 配置用于创建SqlSessionFactory的工厂bean -->
<!--    <bean class="org.mybatis.spring.SqlSessionFactoryBean">-->
<!--        &lt;!&ndash; 设置MyBatis配置文件的路径(可以不设置) &ndash;&gt;-->
<!--        <property name="configLocation" value="classpath:mybatis-config.xml"></property>-->
<!--        &lt;!&ndash; 设置数据源 &ndash;&gt;-->
<!--        <property name="dataSource" ref="dataSource"></property>-->
<!--        &lt;!&ndash; 设置类型别名所对应的包 &ndash;&gt;-->
<!--        <property name="typeAliasesPackage"-->
<!--                  value="com.atguigu.mybatisplus.pojo"></property>-->
<!--        &lt;!&ndash;设置映射文件的路径 若映射文件所在路径和mapper接口所在路径一致,则不需要设置 &ndash;&gt;-->
<!--        &lt;!&ndash;<property name="mapperLocations" value="classpath:mapper/*.xml"> </property> &ndash;&gt;-->
<!--    </bean>-->
    <!--配置mapper接口的扫描配置 由mybatis-spring提供,可以将指定包下所有的mapper接口创建动态代理 并将这些动态代理作为IOC容器的bean管理 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.atguigu.mybatisplus.mapper"></property>
    </bean>

    <!-- 此处使用的是MybatisSqlSessionFactoryBean -->
    <bean class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
        <!-- 设置MyBatis配置文件的路径(可以不设置) -->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <!-- 设置数据源 -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- 设置类型别名所对应的包 -->
        <property name="typeAliasesPackage"
                  value="com.atguigu.mp.pojo"></property>
        <!--设置映射文件的路径 若映射文件所在路径和mapper接口所在路径一致,则不需要设置 -->
        <!--<property name="mapperLocations" value="classpath:mapper/*.xml"> </property> -->
    </bean>
</beans>

此处使用的是MybatisSqlSessionFactoryBean

经观察,目前bean中配置的属性和SqlSessionFactoryBean一致

MybatisSqlSessionFactoryBean是在SqlSessionFactoryBean的基础上进行了增强

即具有SqlSessionFactoryBean的基础功能,又具有MyBatis-Plus的扩展配置

创建Mapper接口

BaseMapper是MyBatis-Plus提供的基础mapper接口,泛型为所操作的实体类型,其中包含CRUD的各个方法,我们的mapper继承了BaseMapper之后,就可以直接使用BaseMapper所提供的各种方法,而不需要编写映射文件以及SQL语句,大大的提高了开发效率。

package com.atguigu.mybatisplus.mapper;

import com.atguigu.mybatisplus.pojo.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

public interface UserMapperByMybatisPlus extends BaseMapper<User> {
}

测试

package com.atguigu.mybatisplus.mapper;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestUserMapperByMybatisPlus {
    @Autowired
    private UserMapperByMybatisPlus userMapperByMybatisPlus;

    @Test
    public void testMyBatisPlus() {
        //根据id查询用户信息
        System.out.println(userMapperByMybatisPlus.selectById(1));
    }

BaseMaper

MyBatis-Plus中的基本CRUD在内置的BaseMapper中都已得到了实现,我们可以直接使用,接口如下:

/*
 * Copyright (c) 2011-2021, baomidou (jobob@qq.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.baomidou.mybatisplus.core.mapper;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Param;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;

/*

               :`
                    .:,
                     :::,,.
             ::      `::::::
             ::`    `,:,` .:`
             `:: `::::::::.:`      `:';,`
              ::::,     .:::`   `@++++++++:
               ``        :::`  @+++++++++++#
                         :::, #++++++++++++++`
                 ,:      `::::::;'##++++++++++
                 .@#@;`   ::::::::::::::::::::;
                  #@####@, :::::::::::::::+#;::.
                  @@######+@:::::::::::::.  #@:;
           ,      @@########':::::::::::: .#''':`
           ;##@@@+:##########@::::::::::: @#;.,:.
            #@@@######++++#####'::::::::: .##+,:#`
            @@@@@#####+++++'#####+::::::::` ,`::@#:`
            `@@@@#####++++++'#####+#':::::::::::@.
             @@@@######+++++''#######+##';::::;':,`
              @@@@#####+++++'''#######++++++++++`
               #@@#####++++++''########++++++++'
               `#@######+++++''+########+++++++;
                `@@#####+++++''##########++++++,
                 @@######+++++'##########+++++#`
                @@@@#####+++++############++++;
              ;#@@@@@####++++##############+++,
             @@@@@@@@@@@###@###############++'
           @#@@@@@@@@@@@@###################+:
        `@#@@@@@@@@@@@@@@###################'`
      :@#@@@@@@@@@@@@@@@@@##################,
      ,@@@@@@@@@@@@@@@@@@@@################;
       ,#@@@@@@@@@@@@@@@@@@@##############+`
        .#@@@@@@@@@@@@@@@@@@#############@,
          @@@@@@@@@@@@@@@@@@@###########@,
           :#@@@@@@@@@@@@@@@@##########@,
            `##@@@@@@@@@@@@@@@########+,
              `+@@@@@@@@@@@@@@@#####@:`
                `:@@@@@@@@@@@@@@##@;.
                   `,'@@@@##@@@+;,`
                        ``...``

 _ _     /_ _ _/_. ____  /    _
/ / //_//_//_|/ /_\  /_///_/_\      Talk is cheap. Show me the code.
     _/             /
 */

/**
 * Mapper 继承该接口后,无需编写 mapper.xml 文件,即可获得CRUD功能
 * <p>这个 Mapper 支持 id 泛型</p>
 *
 * @author hubin
 * @since 2016-01-23
 */
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);
}

插入

最终执行的结果,所获取的id为1580845779620233217,这是因为MyBatis-Plus在实现插入数据时,会默认基于雪花算法的策略生成id。

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

删除

通过id删除记录
@Test
    public void testDeleteById() {
    //通过id删除用户信息
    //DELETE FROM user WHERE id=?
        int result = userMapperByMybatisPlus.deleteById(1580845779620233217L);
        System.out.println("受影响行数:" + result);
    }
通过id批量删除记录
@Test
    public void testDeleteBatchIds() {
        //通过多个id批量删除
        //DELETE FROM user WHERE id IN ( ? , ? , ? )
        List<Long> idList = Arrays.asList(1L, 2L, 3L);
        int result = userMapperByMybatisPlus.deleteBatchIds(idList);
        System.out.println("受影响行数:" + result);
    }
通过map条件删除记录
@Test
    public void testDeleteByMap() {
        //根据map集合中所设置的条件删除记录
        //DELETE FROM user WHERE name = ? AND age = ?
        Map<String, Object> map = new HashMap<>();
        map.put("age", 21);
        map.put("name", "Sandy");
        int result = userMapperByMybatisPlus.deleteByMap(map);
        System.out.println("受影响行数:" + result);
    }

修改

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

查询

根据id查询用户
@Test
    public void testSelectById() {
        //根据id查询用户信息
        //SELECT id,name,age,email FROM user WHERE id=?
        User user = userMapperByMybatisPlus.selectById(4L);
        System.out.println(user);
    }
根据多个id查询多个用户信息
@Test
    public void testSelectBatchIds() {
        //根据多个id查询多个用户信息
        //SELECT id,name,age,email FROM user WHERE id IN ( ? , ? )
        List<Long> idList = Arrays.asList(4L, 5L);
        List<User> list = userMapperByMybatisPlus.selectBatchIds(idList);
        list.forEach(System.out::println);
    }
通过map条件查询用户信息
@Test
    public void testSelectByMap() {
        //通过map条件查询用户信息
        //SELECT id,name,age,email FROM user WHERE name = ? AND age = ?
        Map<String, Object> map = new HashMap<>();
        map.put("age", 22);
        map.put("name", "admin");
        List<User> list = userMapperByMybatisPlus.selectByMap(map);
        list.forEach(System.out::println);
    }
查询所有数据
@Test
public void testSelectList(){
//查询所有用户信息
//SELECT id,name,age,email FROM user 
    List<User> list = userMapper.selectList(null);
    list.forEach(System.out::println);
}

自定义功能

MyBatisPlus制作增强不做改变,要添加新的功能时,做法与MyBatis一致。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0YU0puXG-1666078578252)(E:\笔记\mybatis-plus\Mybatis-Plus入门案例.assets\image-20221014190705557.png)]

Mapper:

package com.atguigu.mybatisplus.mapper;

import com.atguigu.mybatisplus.pojo.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

import java.util.Map;

public interface UserMapperByMybatisPlus extends BaseMapper<User> {
    /**
     * 根据id查询用户信息为map集合
     * @param id
     * @return
     */
    Map<String,Object> selectMapById(Long id);
}

Mapper.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.atguigu.mybatisplus.mapper.UserMapperByMybatisPlus">
    <!--Map<String,Object> selectMapById(Long id);-->
    <select id="selectMapById" resultType="Map">
        select * from user where id = #{id}
    </select>
</mapper>

通用Service

  1. 创建接口UserService继承IService接口,泛型为实体类
package com.atguigu.mybatisplus.service;

import com.atguigu.mybatisplus.pojo.User;
import com.baomidou.mybatisplus.extension.service.IService;

public interface UserService extends IService<User> {

}
  1. 接口实现类UserServiceImpl继承MybatisPlus已经写好的ServiceImpl,实现UserService
package com.atguigu.mybatisplus.service;

import com.atguigu.mybatisplus.mapper.UserMapperByMybatisPlus;
import com.atguigu.mybatisplus.pojo.User;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapperByMybatisPlus, User> implements UserService {
}

  1. 测试
package com.atguigu.mybatisplus.service;

import com.atguigu.mybatisplus.pojo.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestUserService {
    @Autowired
    private UserService userService;

    @Test
    public void test(){
        User user = userService.getById(5L);
        System.out.println(user);
    }
}

批量添加

@Test
public void testBatch() {
    // SQL长度有限制,海量数据插入单条SQL无法实行,
    // 因此MP将批量插入放在了通用Service中实现,而不是通用Mapper
    ArrayList<User> users = new ArrayList<>();
    for (int i = 0; i < 5; i++) {
        User user = new User();
        user.setName("ybc" + i);
        user.setAge(20 + i);
        users.add(user);
    }
    //SQL:INSERT INTO t_user ( username, age ) VALUES ( ?, ? )
    userService.saveBatch(users);
}

常用注解

@TableName

经过以上的测试,在使用MyBatis-Plus实现基本的CRUD时,我们并没有指定要操作的表,只是在
Mapper接口继承BaseMapper时,设置了泛型User,而操作的表为user表,由此得出结论,MyBatis-Plus在确定操作的表时,由BaseMapper的泛型决定,即实体类型决定,且默认操作的表名和实体类型的类名一致

类名与要操作的表名不一致的问题

若实体类类型的类名和要操作的表的表名不一致,会出现什么问题?

我们将表user更名为t_user,测试查询功能
程序抛出异常,Table ‘mybatis_plus.user’ doesn’t exist,因为现在的表名为t_user,而默认操作的表名和实体类型的类名一致,即user表。

通过@TableName解决

在实体类类型上添加@TableName("t_user"),标识实体类对应的表,即可成功执行SQL语句。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-15xnqKEI-1666078578253)(E:\笔记\mybatis-plus\Mybatis-Plus入门案例.assets\image-20221014194506659.png)]

通过GlobalConfig解决

在开发的过程中,我们经常遇到以上的问题,即实体类所对应的表都有固定的前缀,例如t_或tbl_。

此时,可以使用MyBatis-Plus提供的全局配置,为实体类所对应的表名设置默认的前缀,那么就不需要在每个实体类上通过@TableName标识实体类对应的表。

在spring配置文件中加入GlobalConfig配置,在MybatisSqlSessionFactoryBean中引入:

<!-- 此处使用的是MybatisSqlSessionFactoryBean -->
    <bean class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
        <!-- 设置MyBatis配置文件的路径(可以不设置) -->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <!-- 设置数据源 -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- 设置类型别名所对应的包 -->
        <property name="typeAliasesPackage"
                  value="com.atguigu.mp.pojo"></property>
        <!--设置映射文件的路径 若映射文件所在路径和mapper接口所在路径一致,则不需要设置 -->
        <!--<property name="mapperLocations" value="classpath:mapper/*.xml"> </property> -->
        <!--引入GlobalConfig配置-->
        <property name="globalConfig" ref="globalConfig"></property>
    </bean>

    <!--GlobalConfig配置-->
    <bean id="globalConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig">
        <property name="dbConfig">
            <bean class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig">
                <!-- 设置实体类所对应的表的前缀 -->
                <property name="tablePrefix" value="t_"></property>
            </bean>
        </property>
    </bean>

@TableId

经过以上的测试,MyBatis-Plus在实现CRUD时,会默认将id作为主键列,并在插入数据时,默认 基于雪花算法的策略生成id。

主键不是id,而是uid的问题

若实体类和表中表示主键的不是id,而是其他字段,例如uid,MyBatis-Plus会自动识别uid为主 键列吗?

我们实体类中的属性id改为uid,将表中的字段id也改为uid,测试添加功能程序抛出异常,Field ‘uid’ doesn’t have a default value,说明MyBatis-Plus没有将uid作为主键赋值。

通过@TableId解决

在实体类中uid属性上通过@TableId将其标识为主键,即可成功执行SQL语句。

在这里插入图片描述

TableId的value属性

若实体类中主键对应的属性为id,而表中表示主键的字段为uid,此时若只在属性id上添加注解@TableId,则抛出异常Unknown column ‘id’ in ‘field list’,即MyBatis-Plus仍然会将id作为表的主键操作,而表中表示主键的是字段uid
此时需要通过@TableId注解的value属性,指定表中的主键字段,@TableId(“uid”)或@TableId(value=“uid”)。

TableId的type属性

type属性用来定义主键策略

在这里插入图片描述

在这里插入图片描述

配置全局主键策略

在GlobalConfig中配置idType属性:

<!--GlobalConfig配置-->
<bean id="globalConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig">
    <property name="dbConfig">
        <bean class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig">
            <!-- 设置实体类所对应的表的前缀 -->
            <property name="tablePrefix" value="t_"></property>
            <!-- 设置全局主键策略 -->
            <property name="idType" value="AUTO"></property>
        </bean>
    </property>
</bean>

@TableField

经过以上的测试,我们可以发现,MyBatis-Plus在执行SQL语句时,要保证实体类中的属性名和表中的字段名一致
如果实体类中的属性名和字段名不一致的情况,会出现什么问题呢?

若实体类中的属性使用的是驼峰命名风格,而表中的字段使用的是下划线命名风格 例如实体类属性userName,表中字段user_name。

此时MyBatis-Plus会自动将下划线命名风格转化为驼峰命名风格相当于在MyBatis中配置。

若实体类中的属性和表中的字段不满足上述情况,例如实体类属性name,表中字段username。

此时需要在实体类属性上使@TableField("username")设置属性所对应的字段名

在这里插入图片描述

@TableLogin

逻辑删除

  • 物理删除:真实删除,将对应数据从数据库中删除,之后查询不到此条被删除的数据

  • 逻辑删除:假删除,将对应数据中代表是否被删除字段的状态修改为“被删除状态”,之后在数据库中仍旧能看到此条数据记录-

  • 使用场景:可以进行数据恢复

实现逻辑删除

数据库中创建逻辑删除状态列,设置默认值为0

在这里插入图片描述

实体类中添加逻辑删除属性

在这里插入图片描述

测试功能,真正执行的是修改,将加上了@TableLogin注解的字段状态变成了1,被逻辑删除的数据默认不会被查到。

在这里插入图片描述

雪花算法

背景

需要选择合适的方案去应对数据规模的增长,以应对逐渐增长的访问压力和数据量。 数据库的扩展方式主要包括:业务分库、主从复制,数据库分表。

数据库分表

将不同业务数据分散存储到不同的数据库服务器,能够支撑百万甚至千万用户规模的业务,但如果业务继续发展,同一业务的单表数据也会达到单台数据库服务器的处理瓶颈。例如,淘宝的几亿用户数据, 如果全部存放在一台数据库服务器的一张表中,肯定是无法满足性能要求的,此时就需要对单表数据进行拆分。

单表数据拆分有两种方式:垂直分表和水平分表。示意图如下:

在这里插入图片描述

垂直分表

垂直分表适合将表中某些不常用且占了大量空间的列拆分出去。

例如,前面示意图中的 nickname 和 description 字段,假设我们是一个婚恋网站,用户在筛选其他用户的时候,主要是用 age 和 sex 两个字段进行查询,而 nickname 和 description 两个字段主要用于展示,一般不会在业务查询中用到。description 本身又比较长,因此我们可以将这两个字段独立到另外一张表中,这样在查询 age 和 sex 时,就能带来一定的性能提升。

水平拆分

水平分表适合表行数特别大的表,有的公司要求单表行数超过 5000 万就必须进行分表,这个数字可以作为参考,但并不是绝对标准,关键还是要看表的访问性能。对于一些比较复杂的表,可能超过 1000万就要分表了;而对于一些简单的表,即使存储数据超过 1 亿行,也可以不分表。

但不管怎样,当看到表的数据量达到千万级别时,作为架构师就要警觉起来,因为这很可能是架构的性 能瓶颈或者隐患。

水平分表相比垂直分表,会引入更多的复杂性,例如要求全局唯一的数据id该如何处理。

  • 主键自增
  1. 以最常见的用户 ID 为例,可以按照 1000000 的范围大小进行分段,1 ~ 999999 放到表 1中, 1000000 ~ 1999999 放到表2中,以此类推。

  2. 复杂点:分段大小的选取。分段太小会导致切分后子表数量过多,增加维护复杂度;分段太大可能会 导致单表依然存在性能问题,一般建议分段大小在 100 万至 2000 万之间,具体需要根据业务选取合适的分段大小。

  3. 优点:可以随着数据的增加平滑地扩充新的表。例如,现在的用户是 100 万,如果增加到 1000 万, 只需要增加新的表就可以了,原有的数据不需要动。

  4. 缺点:分布不均匀。假如按照 1000 万来进行分表,有可能某个分段实际存储的数据量只有 1 条,而另外一个分段实际存储的数据量有 1000 万条。

  • 取模
  1. 同样以用户 ID 为例,假如我们一开始就规划了 10 个数据库表,可以简单地用 user_id % 10 的值来表示数据所属的数据库表编号,ID 为 985 的用户放到编号为 5 的子表中,ID 为 10086 的用户放到编号为 6 的子表中。

  2. 复杂点:初始表数量的确定。表数量太多维护比较麻烦,表数量太少又可能导致单表性能存在问题。

  3. 优点:表分布比较均匀。

  4. 缺点:扩充新的表很麻烦,所有数据都要重分布。

  • 雪花算法

雪花算法是由Twitter公布的分布式主键生成算法,它能够保证不同表的主键的不重复性,以及相同表的主键的有序性

  1. 核心思想:

长度共64bit(一个long型)。

首先是一个符号位,1bit标识,由于long基本类型在Java中是带符号的,最高位是符号位,正数是0,负 数是1,所以id一般是正数,最高位是0。

41bit时间截(毫秒级),存储的是时间截的差值(当前时间截 - 开始时间截),结果约等于69.73年。

10bit作为机器的ID(5个bit是数据中心,5个bit的机器ID,可以部署在1024个节点)。

12bit作为毫秒内的流水号(意味着每个节点在每毫秒可以产生 4096 个 ID)。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-djV4XPwz-1666078578257)(E:\笔记\mybatis-plus\Mybatis-Plus入门案例.assets\image-20221015110117795.png)]

  1. 优点:整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞,并且效率较高。

条件构造器和常用接口

wapper介绍

在这里插入图片描述

  • Wrapper : 条件构造抽象类,最顶端父类
    • AbstractWrapper : 用于查询条件封装,生成 sql 的 where 条件
      • QueryWrapper : 查询条件封装
      • UpdateWrapper:Update 条件封装
      • AbstractLambdaWrapper : 使用Lambda 语法
        • LambdaQueryWrapper :用于Lambda语法使用的查询Wrapper
        • LambdaUpdateWrapper : Lambda 更新封装Wrapper

QueryWrapper

  • 例一:组装查询条件
@Test
    public void test3() {
        //查询用户名包含a,年龄在20到30之间,并且邮箱不为null的用户信息
        //SELECT id AS uid,username AS name,age,email,is_delete FROM t_user WHERE is_delete=0 AND (username LIKE ? AND age BETWEEN ? AND ? AND email IS NOT NULL)
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like("username", "a")
                .between("age", 20, 30)
                .isNotNull("email");
        List<User> list = userService.list(wrapper);
        list.forEach(System.out::println);
    }
  • 例二:组装排序条件
@Test
    public void test02(){
        //查询用户信息,按照年龄的降薪排序,若年龄相同,则按照id升序排序
        //SELECT id AS uid,username AS name,age,email,is_delete FROM t_user WHERE is_delete=0 ORDER BY age DESC,uid ASC
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("age").orderByAsc("uid");
        List<User> list = userService.list(wrapper);
        list.forEach(System.out::println);
    }
  • 例三:组装删除条件
@Test
    public void test4() {
        //删除邮箱为null的数据
        //UPDATE t_user SET is_delete=1 WHERE is_delete=0 AND (email IS NULL)
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.isNull("email");
        userService.remove(wrapper);
    }
  • 例4:条件的优先级(lambda表达式中的条件优先执行)
  @Test
    public void test4() {
        //查询用户名包含a,并且(年龄大于20或邮箱为null)的用户信息修改
        //SELECT id AS uid,username AS name,age,email,is_delete
        // FROM t_user
        // WHERE is_delete=0
        // AND (username LIKE %a% AND (age > 20 OR email IS NULL))
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like("username", "a")
                //lambda表达式中的条件优先执行
                .and(i -> i.gt("age", 20).
                        or().
                        isNull("email"));
        List<User> list = userService.list(wrapper);
        list.forEach(System.out::println);
    }
  • 例5:实现修改
@Test
    public void testUpdate() {
        //将年龄大于20且用户名中包含a 或 邮箱为null的用户信息修改
        //UPDATE t_user SET email=? WHERE is_delete=0 AND (age > ? AND username LIKE ? OR email IS NULL)
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.gt("age", 20)
                .like("username", "a")
                .or()
                .isNull("email");
        User user = new User();
        user.setEmail("test@qq.com");
        userService.update(user,queryWrapper);
    
  • 例6:查询指定字段
@Test
    public void testAppointColumn() {
        //只查询用户名、年龄、邮箱
        //SELECT username,age,email FROM t_user WHERE is_delete=0
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.select("username","age","email");
        List<Map<String, Object>> list = userService.listMaps(userQueryWrapper);
        list.forEach(System.out::println);
    }
  • 例6:实现子查询
@Test
    public void test7() {
        //查询id小于等于3的用户信息
        //SELECT id AS uid,username AS name,age,email,is_delete FROM t_user WHERE is_delete=0 AND (id IN (select id from t_user where id <= 3))
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.inSql("id","select id from t_user where id <= 3");
        List<User> list = userService.list(queryWrapper);
        list.forEach(System.out::println);
    }

UpdateWrapper

@Test
    public void test8() {
        //将用户名中包含a并且(年龄大于20或邮箱为null)的用户信息修改
        //UPDATE t_user SET username=?,email=? WHERE is_delete=0 AND (username LIKE ? AND (age > ? OR email IS NULL))
        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
        userUpdateWrapper.like("username", "a")
                .and(i -> i.gt("age", 20)
                        .or()
                        .isNull("email"));
        userUpdateWrapper.set("username", "update_test").set("email", "update@qq.com");
        userService.update(userUpdateWrapper);
    }

condition组装条件

在真正开发的过程中,组装条件是常见的功能,而这些条件数据来源于用户输入,是可选的,因此我们在组装这些条件时,必须先判断用户是否选择了这些条件,若选择则需要组装该条件,若没有选择则一定不能组装,以免影响SQL执行的结果。

@Test
public void test9(){
    //SELECT id AS uid,username AS name,age,email,is_delete FROM t_user WHERE is_delete=0 AND (age >= ? AND age <= ?)
    String username = "";
    Integer ageBegin = 20;
    Integer ageEnd = 30;

    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    if(StringUtils.isNotBlank(username)){
        //isNotBlank判断某个字符串是否不为空字符串,不为null,不为空白符
        queryWrapper.like("username",username);
    }
    if(ageBegin != null){
        queryWrapper.ge("age",ageBegin);//ge是大于等于
    }
    if(ageEnd != null){
        queryWrapper.le("age",ageEnd);//le是小于等于
    }

    List<User> list = userService.list(queryWrapper);
    list.forEach(System.out::println);
}

上面的实现方案没有问题,但是代码比较复杂,我们可以使用带condition参数的重载方法构建查询条件,简化代码的编写。

@Test
    public void test10() {
        String username = "";
        Integer ageBegin = 20;
        Integer ageEnd = 30;

        //SELECT id AS uid,username AS name,age,email,is_delete FROM t_user WHERE is_delete=0 AND (age >= ? AND age <= ?)
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        queryWrapper.like(StringUtils.isNotBlank(username),"username", username)
                .ge(ageBegin != null, "age", ageBegin)
                .le(ageEnd != null, "age", ageEnd);

        List<User> list = userService.list(queryWrapper);
        list.forEach(System.out::println);
    }

LambdaQueryWrapper

继上述案例,使用lambda函数式接口可以防止列名写错。

@Test
public void test11(){
    //SELECT id AS uid,username AS name,age,email,is_delete FROM t_user WHERE is_delete=0 AND (age >= ? AND age <= ?)
    String username = "";
    Integer ageBegin = 20;
    Integer ageEnd = 30;

    LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>();
    queryWrapper.like(StringUtils.isNotBlank(username),User::getName,username)
            .ge(ageBegin!=null,User::getAge,ageBegin)
            .le(ageEnd != null,User::getAge,ageEnd);

    List<User> list = userService.list(queryWrapper);
    list.forEach(System.out::println);
}

LambdaUpdateWrapper

使用LambdaUpdateWrapper可以避免列名写错。

@Test
    public void test12() {
        //将用户名中包含有a并且(年龄大于20或邮箱为null)的用户修改
        //UPDATE t_user SET email=? WHERE is_delete=0 AND (username LIKE ? AND (age > ? OR email IS NULL))
        LambdaUpdateWrapper<User> userLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        userLambdaUpdateWrapper.like(User::getName, "a")
                .and(i -> i.gt(User::getAge, 20)
                        .or()
                        .isNull(User::getEmail));
        userLambdaUpdateWrapper.set(User::getEmail,"2456@qq.com");
        userService.update(userLambdaUpdateWrapper);
    }

插件

分页插件

MyBatisPlus自带分页插件,只要简单配置即可实现分页功能。

  • 添加配置
<bean class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis-config.xml">
</property>
<property name="dataSource" ref="dataSource"></property>
<property name="typeAliasesPackage" value="com.atguigu.mp.pojo"></property>
<property name="globalConfig" ref="globalConfig"></property>
<!--配置插件-->
<property name="plugins">
<array>
<ref bean="mybatisPlusInterceptor"></ref>
</array>
</property>
</bean>

<!--配置MyBatis-Plus插件-->
<bean id="mybatisPlusInterceptor" class="com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor">
<property name="interceptors">
<list>
<ref bean="paginationInnerInterceptor"></ref>
</list>
</property>
</bean>

<!--配置MyBatis-Plus分页插件的bean-->
<bean id="paginationInnerInterceptor" class="com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerIntercept or">
<!--设置数据库类型-->
<property name="dbType" value="MYSQL"></property>

实现分页功能

@Test
    public void test(){
        Page<User> userPage = new Page<>(1,3);//当前第一页,每页3条数据
        userMapper.selectPage(userPage,null);//null表示查询所有信息
        System.out.println("数据:"+userPage.getRecords());
        System.out.println("当前页:"+userPage.getCurrent());
        System.out.println("总页数:"+userPage.getPages());
        System.out.println("数据总条数:"+userPage.getTotal());
        System.out.println("当前页数据条数"+userPage.getSize());
    }

自定义分页功能

UserMapper中定义接口方法:

/**
 * 通过年龄查询用户信息并分页
 * @param page MyBatisPlus提供的分页对象,必须位于第一个参数的位置
 * @param age
 * @return
 */
Page<User> selectPageVo(@Param("page") Page<User> page,@Param("age") Integer age);

UserMapper.xml中编写sql:

<?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.atguigu.mybatisplus.mapper.UserMapperByMybatisPlus">
    <sql id="BaseColumns">id,username,age,email</sql>

    <!--type:设置映射关系中的实体类类型-->
    <resultMap id="userResultMap" type="User">
        <!--property:属性名,必须是type实体类中的属性名
            column:字段名,必须是sql语句查询出来的字段名
        -->
        <!--id用户设置主键,唯一标识,不能重复-->
        <id property="uid" column="id"/>
        <!--result用于设置普通字段-->
        <result property="name" column="username"/>
        <result property="age" column="age"/>
        <result property="email" column="email"/>
    </resultMap>

    <!--Page<User> selectPageVo(@Param("page") Page<User> page,@Param("age") Integer age);-->
    <select id="selectPageVo" resultMap="userResultMap">
        select <include refid="BaseColumns"></include> from t_user where age > #{age}
    </select>
</mapper> 

测试:

@Test
    public void testDefined(){
        //设置分页
        Page<User> userPage = new Page<>(1, 5);
        Page<User> page = userMapperByMybatisPlus.selectPageVo(userPage, 20);
        //获取分页数据
        System.out.println("总记录数:"+page.getTotal());
        System.out.println("当前页:"+page.getCurrent());
        System.out.println("总页数:"+page.getPages());
        List<User> list = page.getRecords();
        System.out.println("数据:");
        list.forEach(System.out::println);
    }

乐观锁和悲观锁

一件商品,成本价是80元,售价是100元。老板先是通知小李,说你去把商品价格增加50元。小李正在玩游戏,耽搁了一个小时。正好一个小时后,老板觉得商品价格增加到150元,价格太高,可能会影响销量。又通知小王,你把商品价格降低30元。

此时,小李和小王同时操作商品后台系统。小李操作的时候,系统先取出商品价格100元;小王也在操作,取出的商品价格也是100元。小李将价格加了50元,并将100+50=150元存入了数据库;小王将商品减了30元,并将100-30=70元存入了数据库。

是的,如果没有锁,小李的操作就完全被小王的覆盖了。现在商品价格是70元,比成本价低10元。几分钟后,这个商品很快出售了1千多件商品,老板亏1万多。

上面的故事,如果是乐观锁,小王保存价格前,会检查下价格是否被人修改过了。如果被修改过了,则重新取出的被修改后的价格,150元,这样他会将120元存入数据库。

如果是悲观锁,小李取出数据后,小王只能等小李操作完之后,才能对价格进行操作,也会保证最终的价格是120元。

模拟冲突

数据库中添加商品表:

CREATE TABLE t_product (
	id BIGINT ( 20 ) NOT NULL COMMENT '主键ID',
	NAME VARCHAR ( 30 ) NULL DEFAULT NULL COMMENT '商品名称',
	price INT ( 11 ) DEFAULT 0 COMMENT '价格',
	VERSION INT ( 11 ) DEFAULT 0 COMMENT '乐观锁版本号',
PRIMARY KEY ( id ) 
);

添加数据:

INSERT INTO t_product (id, NAME, price) VALUES (1, '外星人笔记本', 100);

添加实体:

package com.atguigu.mybatisplus.pojo;

public class Product {
    private Long id;
    private String name;
    private Integer price;
    private Integer version;

    public Product() {
    }

    public Product(Long id, String name, Integer price, Integer version) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.version = version;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }

    public Integer getVersion() {
        return version;
    }

    public void setVersion(Integer version) {
        this.version = version;
    }

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", version=" + version +
                '}';
    }
}

添加Mapper:

package com.atguigu.mybatisplus.mapper;

import com.atguigu.mybatisplus.pojo.Product;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

public interface ProductMapper extends BaseMapper<Product> {
}

测试:

@Test
    public void test() {
        //1、小李
        Product p1 = productMapper.selectById(1L);
        System.out.println("小李取出的价格:" + p1.getPrice());
        //2、小王
        Product p2 = productMapper.selectById(1L);
        System.out.println("小王取出的价格:" + p2.getPrice());
        //3、小李将价格加了50元,存入了数据库
        p1.setPrice(p1.getPrice() + 50);
        int result1 = productMapper.updateById(p1);
        System.out.println("小李修改结果:" + result1);
        //4、小王将商品减了30元,存入了数据库
        p2.setPrice(p2.getPrice() - 30);
        int result2 = productMapper.updateById(p2);
        System.out.println("小王修改结果:" + result2);
        //最后的结果
        Product p3 = productMapper.selectById(1L);
        //价格覆盖,最后的结果:70
        System.out.println("最后的结果:" + p3.getPrice());
    }

乐观锁实现流程

数据库中添加version字段

取出记录时,获取当亲的vesion

select id,name,price,version from t_product

更新时,version+1,若果where语句中版本不对,则更新失败。

UPDATE product SET price=price+50, version=version + 1 WHERE id=1 AND version=1

Mybatis-Plus实现乐观锁

pojo中添加version字段
在这里插入图片描述

添加乐观锁插件配置:

<!--配置MyBatis-Plus插件-->
<bean id="mybatisPlusInterceptor"
class="com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor">
<property name="interceptors">
<list>
<ref bean="paginationInnerInterceptor"></ref>
<ref bean="optimisticLockerInnerInterceptor"></ref>
</list>
</property>
</bean>
<!--配置乐观锁插件-->
<bean id="optimisticLockerInnerInterceptor"
class="com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInt
erceptor"></bean>

测试修改冲突:

小李查询商品信息:

SELECT id,name,price,version FROM t_product WHERE id=?

小王查询商品信息:

SELECT id,name,price,version FROM t_product WHERE id=?

小李修改商品价格,自动将version+1

UPDATE t_product SET name=?, price=?, version=? WHERE id=? AND version=?

Parameters: 外星人笔记本(String), 150(Integer), 1(Integer), 1(Long), 0(Integer)

小王修改商品价格,此时version已更新,条件不成立,修改失败

UPDATE t_product SET name=?, price=?, version=? WHERE id=? AND version=?

Parameters: 外星人笔记本(String), 70(Integer), 1(Integer), 1(Long), 0(Integer)

最终,小王修改失败,查询价格:150

SELECT id,name,price,version FROM t_product WHERE id=?

优化流程:

@Test
    public void testConcurrentVersionUpdate() {
        //小李取数据
        Product p1 = productMapper.selectById(1L);
        //小王取数据
        Product p2 = productMapper.selectById(1L);
        //小李修改 + 50
        p1.setPrice(p1.getPrice() + 50);
        int result1 = productMapper.updateById(p1);
        System.out.println("小李修改的结果:" + result1);
        //小王修改 - 30
        p2.setPrice(p2.getPrice() - 30);
        int result2 = productMapper.updateById(p2);
        System.out.println("小王修改的结果:" + result2);
        if (result2 == 0) {
            //失败重试,重新获取version并更新
            p2 = productMapper.selectById(1L);
            p2.setPrice(p2.getPrice() - 30);
            result2 = productMapper.updateById(p2);
        }
        System.out.println("小王修改重试的结果:" + result2);
        //老板看价格
        Product p3 = productMapper.selectById(1L);
        System.out.println("老板看价格:" + p3.getPrice());
    }

通用枚举

表中的有些字段值是固定的,例如性别(男或女),此时我们可以使用MyBatis-Plus的通用枚举来实现。

数据库表添加自字段sex:

在这里插入图片描述

创建通用枚举类:

package com.atguigu.mybatisplus.enums;

import com.baomidou.mybatisplus.annotation.EnumValue;
import lombok.Getter;

@Getter
public enum SexEnum {
    MALE(1, "男"),
    FEMALE(2, "女");

    //需要存储数据库的属性上添加@EnumValue注解,需要配置扫描通用枚举的包
    @EnumValue
    private Integer sex;
    private String sexName;


    private SexEnum(Integer sex, String sexName) {
        this.sex = sex;
        this.sexName = sexName;
    }
}

扫描通用枚举:

<bean
class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis-config.xml">
</property>
<property name="dataSource" ref="dataSource"></property>
<property name="typeAliasesPackage" value="com.atguigu.mp.pojo"></property>
<!-- 设置MyBatis-Plus的全局配置 -->
<property name="globalConfig" ref="globalConfig"></property>
<!-- 配置扫描通用枚举 -->
<property name="typeEnumsPackage" value="com.atguigu.mp.enums"></property>
</bean>

测试:

@Test
public void test(){
    User user = new User();
    user.setAge(12);
    user.setEmail("123@qq.com");
    user.setSex(SexEnum.MALE);
    userMapper.insert(user);
}

代码生成器

引入依赖:

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.5.1</version>
</dependency>
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.31</version>
</dependency>

快速生成:

package com.atguigu.mybatisplus.config;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.Collections;

public class FastAutoGeneratorTest {
    public static void main(String[] args) {
        FastAutoGenerator.create("jdbc:mysql://127.0.0.1:3306/mybatis_plus",
                "root", "root")
                .globalConfig(builder -> {
                    builder.author("atguigu") // 设置作者
//.enableSwagger() // 开启 swagger 模式
                            .fileOverride() // 覆盖已生成文件
                            .outputDir("D://mybatis_plus"); // 指定输出目录
                })
                .packageConfig(builder -> {
                    builder.parent("com.atguigu") // 设置父包名
                            .moduleName("mybatisplus") // 设置父包模块名
                            .pathInfo(Collections.singletonMap(OutputFile.mapperXml, "D://mybatis_plus"));
// 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder.addInclude("t_user") // 设置需要生成的表名
                            .addTablePrefix("t_", "c_"); // 设置过滤表前缀
                })
                .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker 引擎模板,默认的是Velocity引擎模板
                .execute();
    }
}

MyBatisX插件

MyBatis-Plus为我们提供了强大的mapper和service模板,能够大大的提高开发效率

但是在真正开发过程中,MyBatis-Plus并不能为我们解决所有问题,例如一些复杂的SQL,多表联查,我们就需要自己去编写代码和SQL语句,我们该如何快速的解决这个问题呢,这个时候可以使用MyBatisX插件

MyBatisX一款基于 IDEA 的快速开发插件,为效率而生。

MyBatisX插件用法

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值