mybatis-plus 入门案例

195 阅读26分钟

一、Mybatis-Plus

1、介绍

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

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

image.png

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、支持数据库

任何能使用 mybatis 进行 CRUD, 并且支持标准 SQL 的数据库,具体支持情况如下,如果不在下列表查看分页部分教程 PR 您的支持。

  • mysql,oracle,db2,h2,hsql,sqlite,postgresql,sqlserver,Phoenix,Gauss ,clickhouse,Sybase,OceanBase,Firebird,cubrid,goldilocks,csiidb
  • 达梦数据库,虚谷数据库,人大金仓数据库,南大通用(华库)数据库,南大通用数据库,神通数据库,瀚高数据库

4、 框架结构

image.png

先扫描实体,通过反射抽取实体中的属性,再分析要操作的表是谁(表中的字段),然后把他注入到mybatis的容器中,mybatis-plus所操作的表以及表中的字段由实体类以及实体类中的属性决定

二、入门案例

1、创建springboot项目

2、加入依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>

    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.5.1</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
        <version> 8.0.22</version>
    </dependency>
</dependencies>

3、配置application.yml(这里用户和密码改成自己的)

spring:
  datasource:
    type: com.zaxxer.hikari.HikariDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
    username: root
    password: 123456

补充 mybatis-plus日志配置

可以输出SQL语句

#配置日志  打印sql语句
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

输出

JDBC Connection [HikariProxyConnection@1407713529 wrapping com.mysql.cj.jdbc.ConnectionImpl@337bbfdf] will not be managed by Spring
==>  Preparing: SELECT id,name,age,email FROM 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

4、编写实体和mapper

  • User.java
@Data
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}
  • UseMapper (这个是mapper接口)
public interface UserMapper extends BaseMapper<User> {
}

5、启动类的再编写(主要是加入依赖)

@SpringBootApplication
@MapperScan("com.bin.mybatisplus.mapper")
public class MybatisplusApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisplusApplication.class, args);
    }

}

6、编写测试类BatisTest.java

@SpringBootTest
public class BatisTest {
    @Autowired
    private UserMapper userMapper;

    @Test
    public void testSelect() {
        userMapper.selectList(null).forEach(System.out::println);
    }
}

7、测试结果

image.png

补充(数据库)

  • a、创建表
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;

image.png

  • b 加入数据
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');

image.png

三、CRUD

1、Mapper CRUD接口

在BaseMapper接口中已经封装实现

  • 增加Insert
// 插入一条记录
int insert(T entity);
  • 删除delete
// 根据 entity 条件,删除记录
int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);
// 删除(根据ID 批量删除)
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
// 根据 ID 删除
int deleteById(Serializable id);
// 根据 columnMap 条件,删除记录
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
  • 修改Update
// 根据 whereWrapper 条件,更新记录
int update(@Param(Constants.ENTITY) T updateEntity, @Param(Constants.WRAPPER) Wrapper<T> whereWrapper);
// 根据 ID 修改
int updateById(@Param(Constants.ENTITY) T entity);
  • 查询select
// 根据 ID 查询
T selectById(Serializable id);
// 根据 entity 条件,查询一条记录
T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

// 查询(根据ID 批量查询)
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
// 根据 entity 条件,查询全部记录
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 查询(根据 columnMap 条件)
List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
// 根据 Wrapper 条件,查询全部记录
List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询全部记录。注意: 只返回第一个字段的值
List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

// 根据 entity 条件,查询全部记录(并翻页)
IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询全部记录(并翻页)
IPage<Map<String, Object>> selectMapsPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询总记录数
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
  • 官方完整版BaseMapper

/*
 * Copyright (c) 2011-2022, 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 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;
import org.apache.ibatis.annotations.Param;

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

/*

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

 _ _     /_ _ _/_. ____  /    _
/ / //_//_//_|/ /_\  /_///_/_\      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<?> 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 实体对象封装操作类
     * @return
     */
    default boolean exists(Wrapper<T> queryWrapper) {
        Long count = this.selectCount(queryWrapper);
        return null != count && count > 0;
    }

    /**
     * 根据 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);

}
  • CRUD操作
@Data
@TableName("t_user")
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

-  crud操作

```java

@SpringBootTest
public class BatisTest {
    @Autowired


    private UserMapper userMapper;

    @Test
    public void testSelect() {
        //通过条件构造器查询一个list集合 若没有条件 则可以设置null为参数
        userMapper.selectList(null).forEach(System.out::println);
        //List<User> list=userMapper.selectList(null);
        userMapper.selectList(null).forEach(System.out::println);
    }

    //插入
    @Test
    public void testInsert(){
//        User user = new User(22,"zhangsan",23,"test6@qq.com");
//        int result = userMapper.insert(user);
//        System.out.println("是影响行数"+result);
//        System.out.println("id自动获取"+user.getId());


        //Preparing: INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
        User user = new User();
        user.setName("成斌");
        user.setAge(22);
        user.setEmail("qq.com");
         int result= userMapper.insert(user);
        System.out.println("result:"+result);
        System.out.println("id="+user.getId());
    }

    //删除
    @Test
    public void delete(){
        //这里id要加双引号,不然报错是数字过大
//      int result= userMapper.deleteById("1535968773411028993");
//        System.out.println("受影响行数"+result);



        // Preparing: DELETE FROM user WHERE name = ? AND age = ?
//        Map<String,Object> map = new HashMap<>();
//                map.put("name","lizhi");
//                map.put("age",22);
//                int res= userMapper.deleteByMap(map);
//        System.out.println(res);


        //多个id批量删除
        List<Long> longs = Arrays.asList(1L, 2L, 3L);
         int res= userMapper.deleteBatchIds(longs);
        System.out.println(res);
    }

    //修改
    @Test
    public void upDate(){
   //UPDATE user SET name=?, age=?, email=? WHERE id=?
        User user = new User();
        user.setId(4L);
        user.setName("lizhi");
        user.setAge(22);
        user.setEmail("lizhizhuangbi.com");
        int res = userMapper.updateById(user);
        System.out.println("res"+res);
    }


    //查询
    @Test
    public  void select(){

        //通过id查询信息
        //SELECT id,name,age,email FROM user WHERE id=?
//        User user= userMapper.selectById(3L);
//        System.out.println(user);


        //测试自定义接口selectMapById

        Map<String,Object> map = userMapper.selectMapById(3L);
        System.out.println(map);

    }
}

image.png

image.png

2、Service CRUD接口

  • UserServiceImpl
//标识为组件
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {
}
  • UserServiceUserService
public interface UserService extends IService<User> {

}
  • 结构

image.png

  • 测试
@SpringBootTest
public class MybatisPlusServiceTest {
    @Autowired
    private UserService userService;


    @Test
    public  void testGetCount(){
      /*Preparing: SELECT COUNT( * ) FROM user*/
        long count = userService.count();
        System.out.println("总记录数"+count);
    }
//批量添加
    @Test
    public void testInsertMore(){
/*Preparing: INSERT INTO user ( id, name, age ) VALUES ( ?, ?, ? )*/
        List<User> list= new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            User user = new User();
            user.setName("lizhi"+i);
            user.setAge(20+i);
            //把创建的user对象加到list集合中
            list.add(user);
        }
        boolean b = userService.saveBatch(list);
        System.out.println(b);
    }
}

四、常用注解

1、@TabName

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

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

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

image.png

问题解决:通过@TableName解决问题

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

通过全局配置解决问题

在开发的过程中,我们经常遇到以上的问题,即实体类所对应的表都有固定的前缀,例如t_或tbl_ 此时,可以使用MyBatis-Plus提供的全局配置,为实体类所对应的表名设置默认的前缀,那么就 不需要在每个实体类上通过@TableName标识实体类对应的表

image.png

2、@TabeleId注解

将属性对应的字段指定为主键,

1、value属性用于指定主键的字段,用于实体与数据库字段不匹配时

2、type属性,type属性设置主键的生成策略,@TableId(value = "uid",type = IdType.AUTO),(这里要求数据库设置的自动递增)

2、1 全局配置策略

mybatis-plus:
  configuration: 
# 配置MyBatis日志 
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl 
  global-config: 
    db-config: 
    # 配置MyBatis-Plus操作表的默认前缀
     table-prefix: t_ 
     # 配置MyBatis-Plus的主键策略
     id-type: auto

image.png

3、雪花算法

  • 背景
    需要选择合适的方案去应对数据规模的增长,以应对逐渐增长的访问压力和数据量。 数据库的扩展方式主要包括:业务分库、主从复制,数据库分表。
  • 数据库分表 将不同业务数据分散存储到不同的数据库服务器,能够支撑百万甚至千万用户规模的业务,但如果业务 继续发展,同一业务的单表数据也会达到单台数据库服务器的处理瓶颈。例如,淘宝的几亿用户数据, 如果全部存放在一台数据库服务器的一张表中,肯定是无法满足性能要求的,此时就需要对单表数据进 行拆分。 单表数据拆分有两种方式:垂直分表和水平分表。示意图如下:

image.png

  • 垂直分表 垂直分表适合将表中某些不常用且占了大量空间的列拆分出去。 例如,前面示意图中的 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)。
  2. 优点:
    整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞,并且效率较高。

五、条件构造器

1、wrapper 简介

image.png

  • Wrapper : 条件构造抽象类,最顶端父类

    • AbstractWrapper : 用于查询条件封装,生成 sql 的 where 条件

    • QueryWrapper : 查询条件封装

    • UpdateWrapper: Update 条件封装

    • AbstractLambdaWrapper : 使用Lambda 语法

    • LambdaQueryWrapper :用于Lambda语法使用的查询Wrapper

    • LambdaUpdateWrapper : Lambda 更新封装Wrapper

2、QueryMapper

  • 组装查询条件

@Test
public void test01() {
/*SELECT uid AS id,user_name AS Name,age,email FROM t_user WHERE (user_name LIKE ? AND age BETWEEN ? AND ? AND email IS NOT NULL)*/
 //查询用户年龄20到30之间 email不为null的用户信息
 QueryWrapper<User> queryWrapper = new QueryWrapper<>();
 queryWrapper.like("user_name","z")
         .between("age",20,30)
         .isNotNull("email");
 List<User> list = userMapper.selectList(queryWrapper);
 list.forEach(System.out::println);
}
  • 组装排序条件

@Test
public  void test02(){

    //查询用户信息 按照年龄的降序排序 年龄相同 按照id升序排序
    //SELECT uid AS id,user_name AS Name,age,email FROM t_user ORDER BY age DESC,uid ASC
    QueryWrapper<User> queryWrapper= new QueryWrapper<>();
    queryWrapper.orderByDesc("age")
            .orderByAsc("uid");
    List<User> list = userMapper.selectList(queryWrapper);
    list.forEach(System.out::println);
}
  • 组装删除条件

这里实则是修改,因为之前设置的逻辑删除

image.png

@Test
public  void test03(){

    //删除email为nul 的用户
    //  Preparing: UPDATE t_user SET is_deleted=1 WHERE is_deleted=0 AND (email IS NULL)
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.isNull("email");
    int res = userMapper.delete(queryWrapper);
    System.out.println("res:"+res);
}

3、UpdateWrapper

@Test
public void test044() {
    //将(年龄大于20并且用户名中包含有a)或邮箱为null的用户信息修改
    UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
    updateWrapper.gt("age", 20).like("user_name", "a")
            .or()
            .isNull("email");
    User user = new User();
    user.setName("小米");
    user.setEmail("test@oz6.com");

    int result = userMapper.update(user, updateWrapper);
    System.out.println(result > 0 ? "修改成功!" : "修改失败!");
    System.out.println("受影响的行数为:" + result);
}

4、condition

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

  • 思路一

执行sql :SELECT uid AS id,user_name AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0 AND (user_name LIKE ? AND age <= ?)

 public void test09(){
     String username = "a";
     Integer ageBegin = null;
     Integer ageEnd = 30;
     QueryWrapper<User> queryWrapper = new QueryWrapper<>();
     if(StringUtils.isNotBlank(username)){
         //isNotBlank判断某个字符创是否不为空字符串、不为null、不为空白符
         queryWrapper.like("user_name", username);
     }
     if(ageBegin != null){
         queryWrapper.ge("age", ageBegin);
     }
     if(ageEnd != null){
         queryWrapper.le("age", ageEnd);
     }
     List<User> list = userMapper.selectList(queryWrapper);
     list.forEach(System.out::println);
 }
  • 思路二

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

//使用condition组装条件
@Test
public void test10(){
    //SELECT uid AS id,user_name AS Name,age,email FROM t_user WHERE (user_name LIKE ? AND age <= ?)
    String usermame = "a";
    Integer ageBegin = null;
    Integer ageEnd = 30;
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.like(StringUtils.isNotBlank(usermame),"user_name",usermame)
            .ge(ageBegin != null,"age",ageBegin)
            .le(ageEnd != null,"age",ageEnd);
    List<User> list = userMapper.selectList(queryWrapper);
    list.forEach(System.out::println);
}

5、LambdaQueryWappper

功能等同于QueryWrapper,提供了Lambda表达式的语法可以避免填错列名。

//LambdaQueryWappper
@Test
public void test11(){
    //这里和test10一样
    //SELECT uid AS id,user_name AS Name,age,email FROM t_user WHERE (user_name LIKE ? AND age <= ?)
    String usermame = "a";
    Integer ageBegin = null;
    Integer ageEnd = 30;
    LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.like(StringUtils.isNotBlank(usermame),User::getName,usermame)
            .ge(ageBegin != null,User::getAge,ageBegin)
            .le(ageEnd != null,User::getAge,ageEnd);
    List<User> list = userMapper.selectList(queryWrapper);
    list.forEach(System.out::println);
}

6、LambdaUpdateWapper

功能等同于UpdateWrapper,提供了Lambda表达式的语法可以避免填错列名。

//LambdaUpdateWapper
@Test
public void test12(){
    //将用户名中有a (年龄大于20或者邮箱为null)的用户信息修改
    //Preparing: UPDATE t_user SET user_name=?,email=? WHERE (user_name LIKE ? AND (age > ? OR email IS NULL))
    LambdaUpdateWrapper<User> updateWrapper = new  LambdaUpdateWrapper<>();
    updateWrapper.like(User::getName, "a")
            .and(i -> i.gt(User::getAge, "20").or().isNull(User::getEmail));
    updateWrapper.set(User::getName, "李志").set(User::getEmail, "lizhi.com");
    int res = userMapper.update(null, updateWrapper);
    System.out.println("res:" + res);
}

六、 常用插件

1、分页插件

MyBatis Plus自带分页插件,只要简单的配置即可实现分页功能

  • 添加配置类MyBatisPlusConfig
@Configuration
@MapperScan("com.bin.mybatisplus.mapper")
public class MyBatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //添加分页插件
        //ctrl+p
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}
  • 编写测试方法
@Test
public void testPage(){
    //访问第一页 每页显示三条数据
    Page<User> page = new Page<>(1,3);
    userMapper.selectPage(page,null);
    System.out.println(page);
}

2、自定义分页

上面调用的是MyBatis-Plus提供的带有分页的方法,那么我们自己定义的方法如何实现分页呢?

  • 在UserMapper接口中定义一个方法
 /**
  * 通过年龄查询用户信息
  * @param page MyBatis-plus 提供的分页对象 必须位于第一个参数的位置
  * @param age
  * @return
  */
Page<User> selectPageVo(@Param("page") Page<User> page,@Param("age") Integer age);
  • 在Usermapper.xml中编写SQL实现该接口
<!--Page<User> selectPageVo(@Param("page") Page<User> page,@Param("age") Integer age);-->
<select id="selectPageVo" resultType="User">
 select uid,user_name,age,email from t_user where age > #{age}
</select>
  • 编写测试方法
@Test
public void testPageVo(){

    //select uid,user_name,age,email from t_user where age > ? LIMIT ?
    Page<User> page = new Page<>(1,3);

    userMapper.selectPageVo(page,20);
    System.out.println(page.getRecords());
    System.out.println(page.getPages());
    System.out.println(page.getTotal());
    System.out.println(page.hasNext());
    System.out.println(page.hasPrevious());
}

3、乐观锁

作用:当要更新一条记录的时候,希望这条记录没有被别人更新 乐观锁的实现方式:

  • 取出记录时,获取当前 version
  • 更新时,带上这个 version
  • 执行更新时, set version = newVersion where version = oldVersion
  • 如果 version 不对,就更新失败

3.1场景


  • 一件商品,成本价是80元,售价是100元。老板先是通知小李,说你去把商品价格增加50元。小李正在玩游戏,耽搁了一个小时。正好一个小时后,老板觉得商品价格增加到150元,价格太高,可能会影响销量。又通知小王,你把商品价格降低30元。
  • 此时,小李和小王同时操作商品后台系统。小李操作的时候,系统先取出商品价格100元;小王也在操作,取出的商品价格也是100元。小李将价格加了50元,并将100+50=150元存入了数据库;小王将商品减了30元,并将100-30=70元存入了数据库。是的,如果没有锁,小李的操作就完全被小王的覆盖了。
  • 现在商品价格是70元,比成本价低10元。几分钟后,这个商品很快出售了1千多件商品,老板亏1万多

3.2 乐观锁与悲观锁


  • 上面的故事,如果是乐观锁,小王保存价格前,会检查下价格是否被人修改过了。如果被修改过了,则重新取出的被修改后的价格,150元,这样他会将120元存入数据库。
  • 如果是悲观锁,小李取出数据后,小王只能等小李操作完之后,才能对价格进行操作,也会保证最终的价格是120元。

3.3 模拟修改冲突

  • 数据库中增加商品表
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);
  • 添加一个实体类Product
@Data
public class Product {
    private  Long id;
    private String name;
    private Integer price;
    private Integer version;
}
  • 增加一个mapper接口ProductMapper
@Repository
public interface ProductMapper extends BaseMapper<Product> {
}

-测试方法

测试类前加上

//这里productMappe报错,可以在ProductMapper上加上@Repository持久化注解,将它标记成一个持久层组件
@Autowired
private ProductMapper productMapper;
@Test
public  void testProduct(){
    //小李查询商品价格
    Product productLi = productMapper.selectById(1);
    System.out.println("小李查询的商品价格"+productLi.getPrice());
    //小王查询商品价格
    Product productWang = productMapper.selectById(1);
    System.out.println("小王查询的商品价格"+productWang.getPrice());
    //小李将商品价格+50
    productLi.setPrice(productLi.getPrice()+50);
    productMapper.updateById(productLi);
    //小王将商品价格-30
    productWang.setPrice(productWang.getPrice()-30);
    productMapper.updateById(productWang);
    //老板查询商品价格
    Product productBoss = productMapper.selectById(1);
    System.out.println("老板查询的商品价格"+productBoss.getPrice());

}
  • 测试结果

image.png

3.4 乐观锁解决问题

3.4.1乐观锁实现流程

据库中添加version字段 ,取出记录时,获取当前version
SELECT id,name,price,version FROM product WHERE id=1
更新时,version + 1,如果where语句中的version版本不对,则更新失败
UPDATE product SET price=price+50, version=version + 1 WHERE id=1 AND version=1

3.4.2Mybatis-Plus实现乐观锁

  • 修改实体类
package com.bin.mybatisplus.model;

import com.baomidou.mybatisplus.annotation.Version;
import lombok.Data;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 小南瓜
 * @Date: 2022/06/18/13:22
 * @Description:
 */
@Data
public class Product {
    private  Long id;
    private String name;
    private Integer price;
    @Version
    private Integer version;
}
  • 添加乐观锁创建配置
package com.bin.mybatisplus.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 小南瓜
 * @Date: 2022/06/18/10:33
 * @Description:
 */
@Configuration
@MapperScan("com.bin.mybatisplus.mapper")
public class MyBatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //添加分页插件
        //ctrl+p
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));

        //添加乐观锁插件
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
        
    }
}
  • 再次执行测试方法

    小李查询商品信息:

    ​ 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 testProduct(){
  //小李查询商品价格
  Product productLi = productMapper.selectById(1);
  System.out.println("小李查询的商品价格"+productLi.getPrice());
  //小王查询商品价格
  Product productWang = productMapper.selectById(1);
  System.out.println("小王查询的商品价格"+productWang.getPrice());
  //小李将商品价格+50
  productLi.setPrice(productLi.getPrice()+50);
  productMapper.updateById(productLi);
  //小王将商品价格-30
  productWang.setPrice(productWang.getPrice()-30);
   int result=productMapper.updateById(productWang);

  if (result == 0){
      //操作失败
      Product productNew = productMapper.selectById(1);
      productNew.setPrice(productNew.getPrice()-30);
      productMapper.updateById(productNew);
  }
  //老板查询商品价格
  Product productBoss = productMapper.selectById(1);
  System.out.println("老板查询的商品价格"+productBoss.getPrice());

}
  • 测试结果

image.png

七、通用枚举

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

  • 数据库增加sex字段

image.png

  • 创建通用枚举类型SexEnum
package com.bin.mybatisplus.enums;

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

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 小南瓜
 * @Date: 2022/06/18/18:06
 * @Description:
 */

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

    @EnumValue//将注解所标识的属性的值存储到数据库中
    private  Integer sex;
    private  String sexName;

    SexEnum(Integer sex, String sexName) {
        this.sex = sex;
        this.sexName = sexName;
    }
}
  • User实体类增加sex属性

@Data
// 设置实体类所对应的表名
//@TableName("t_user")
public class User {
    //将属性对应的字段指定为主键
    //@TableId
    //value属性用于指定主键的字段
    //type属性设置主键的生成策略
    @TableId(value = "uid")
    private Long id;//uid

    @TableField("user_name")
    private String Name;

    private Integer age;
    private String email;

    private SexEnum sex;

//    @TableLogic
//    private int isDeleted;//逻辑删除

}
  • 配置扫描通用枚举
spring:
  datasource:
    type: com.zaxxer.hikari.HikariDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
    username: root
    password: 123456
    #配置MyBatis
mybatis-plus:
  configuration:
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    # 配置MyBatis-Plus操作表的默认前缀
    db-config:
      table-prefix: t_
      # 设置统一的主键生成策略
      id-type: auto
      #设置类型别名所对应的包
  type-aliases-package: com.bin.mybatisplus.model
  #扫描通用枚举
  type-enums-package: com.bin.mybatisplus.enums
  • 测试方法
@Test
public void test(){
    User user = new User();
    user.setName("admin");
    user.setAge(22);
    user.setSex(SexEnum.MALE);
    int res= userMapper.insert(user);
    System.out.println("res:"+res);
}

八、代码生成器

MyBatis-Plus为我们提供了强大的mapper和service模板,能够大大的提高开发效率。 但是在真正开发过程中,MyBatis-Plus并不能为我们解决所有问题,例如一些复杂的SQL,多表联查,我们就需要自己去编写代码和SQL语句,我们该如何快速的解决这个问题呢,这个时候可以使用MyBatisX插件。 MyBatisX一款基于 IDEA 的快速开发插件,为效率而生。

  • 引入依赖

image.png

  • 快速生成
package com.bin.mybatisplus;

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

import java.util.Collections;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 小南瓜
 * @Date: 2022/06/18/18:41
 * @Description:
 */
public class FastAutoGeneratorTest {
    public static void main(String[] args) {
        FastAutoGenerator.create("url", "username", "password")
                .globalConfig(builder -> {
                    builder.author("baomidou") // 设置作者
                            .enableSwagger() // 开启 swagger 模式
                            .fileOverride() // 覆盖已生成文件
                            .outputDir("D://"); // 指定输出目录
                })
                .packageConfig(builder -> {
                    builder.parent("com.baomidou.mybatisplus.samples.generator") // 设置父包名
                            .moduleName("system") // 设置父包模块名
                            .pathInfo(Collections.singletonMap(OutputFile.mapperXml, "D://")); // 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder.addInclude("t_simple") // 设置需要生成的表名
                            .addTablePrefix("t_", "c_"); // 设置过滤表前缀
                })
                .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
                .execute();
    }
}
  • 执行结果

image.png

九、多数据源

用于多种场景:纯粹多库、 读写分离、 一主多从、 混合模式等 目前我们就来模拟一个纯粹多库的一个场景,其他场景类似 场景说明: 我们创建两个库,分别为:mybatis_plus(以前的库不动)与mybatis_plus_1(新建),将 mybatis_plus库的product表移动到mybatis_plus_1库,这样每个库一张表,通过一个测试用例 分别获取用户数据与商品数据,如果获取到说明多库模拟成功

1、创建数据库及表

  • 创建数据库mybatis_plus_1和表product
CREATE DATABASE `mybatis_plus_1` /*!40100 DEFAULT CHARACTER SET utf8mb4 */;
use `mybatis_plus_1`; 
CREATE TABLE 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 product (id, NAME, price) VALUES (1, '外星人笔记本', 100);
  • 删除mybatis_plus库中的product

2、新建springBoot项目

  • 加入依赖
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.1</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
    <version> 8.0.22</version>
</dependency>

<!--多数据源-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
    <version>3.5.0</version>
</dependency>
  • 创建User类
package com.bin.pojo;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 小南瓜
 * @Date: 2022/06/18/19:20
 * @Description:
 */
@Data
@TableName("t_user")
public class User {

    @TableId
    private Integer uid;

    private  String username;

    private  Integer age;

    private Integer sex;

    private String email;

    private Integer isDeleted;

}
  • 创建Product类
package com.bin.pojo;

import lombok.Data;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 小南瓜
 * @Date: 2022/06/18/19:26
 * @Description:
 */
@Data
public class Product {

    private  Integer id;

    private  String name;

    private Integer price;

    private  Integer version;
}
  • 编写UserMapper接口
package com.bin.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.bin.pojo.User;
import org.springframework.stereotype.Repository;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 小南瓜
 * @Date: 2022/06/18/19:19
 * @Description:
 */
@Repository
public interface UserMapper extends BaseMapper<User> {
}
  • 编写ProductMapper
package com.bin.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.bin.pojo.Product;
import org.springframework.stereotype.Repository;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 小南瓜
 * @Date: 2022/06/18/19:32
 * @Description:
 */
@Repository
public interface ProductMapper extends BaseMapper<Product> {
}

3、编写Service以及实现类

  • 编写ProductService
public interface ProductService extends IService<Product> {

}
  • 编写UserService
public interface UserService extends IService<User> {
}
  • 编写ProductServiceImpl
@Service
@DS("slave_1")
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {
}
  • 编写UserServiceImpl
@Service
@DS("master")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}

-启动类指定MapperScan

@SpringBootApplication
@MapperScan("com.bin.mapper")
public class MybatisPlusDatasourceApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisPlusDatasourceApplication.class, args);
    }

}

4、测试类

@Autowired
private UserService userService;

@Autowired
private ProductService productService;

@Test
public void test(){
    System.out.println(userService.getById(1));
    System.out.println(productService.getById(1));
}
  • 测试结果

image.png

结果: 1、都能顺利获取对象,则测试成功 2、如果我们实现读写分离,将写操作方法加上主库数据源,读操作方法加上从库数据源,自动切换,是不是就能实现读写分离?

十、MybatisX创建

如果搜不到,可以连接手机热点

yBatis-Plus为我们提供了强大的mapper和service模板,能够大大的提高开发效率 但是在真正开发过程中,MyBatis-Plus并不能为我们解决所有问题,例如一些复杂的SQL,多表 联查,我们就需要自己去编写代码和SQL语句,我们该如何快速的解决这个问题呢,这个时候可 以使用MyBatisX插件 MyBatisX一款基于 IDEA 的快速开发插件,为效率而生。 MyBatisX插件用法:baomidou.com/pages/ba5b2…

十一、主键生成策略

image.png

  1. AUTO:自动增长
  2. ID_WORKER:自带策略,数字类型使用,比如Long
  3. ID_WORKER_STR:mp自带策略,字符串使用
  4. INPUT:设置id值
  5. NONE:输入
  6. UUID:随机唯一值

十二、自动填充

1 在实体类中需要填充的属性上添加注解

@TableField(.. fill = FieldFill.INSERT)

image.png 2 创建实体类,实现接口MateObjectHandler实现接口里面的方法

image.png

//交给spring管理
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {

    }

    @Override
    public void updateFill(MetaObject metaObject) {

    }
}

image.png