学尚硅谷版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
  • 达梦数据库,虚谷数据库,人大金仓数据库,南大通用(华库)数据库,南大通用数据库,神通数据库,瀚高数据库

官方地址

官方地址: http://mp.baomidou.com
代码发布地址:
Github: https://github.com/baomidou/mybatis-plus
Gitee: https://gitee.com/baomidou/mybatis-plus
文档发布地址: https://baomidou.com/pages/24112f

mybatis Plus入门

环境搭建

本机开发环境

IDE:idea 2020.3
JDK:JDK8+
构建工具:maven 3.5.4
MySQL版本:MySQL 8+
Spring Boot:2.6.3
MyBatis-Plus:3.4.1
1.创建数据库及表
CREATE DATABASE `mybatis_plus`;
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;

2.数据添加

INSERT INTO user (id, name, age, email) VALUES(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),(5, 'Billie', 24, 'test5@baomidou.com');

3.创建springboot工程

4. 完成后添加依赖

        <dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.4.1</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency>
5.idea中安装lombok插件

编写代码和配置

编写配置文件yml

spring:#配置数据源datasource:#加载驱动driver-class-name: com.mysql.cj.jdbc.Driver#配置连接数据库url: jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&serverTimezone=GMT%2B8username: rootpassword: root#配置数据源type: com.zaxxer.hikari.HikariDataSourcemybatis-plus:configuration:
#添加日志log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

在Spring Boot启动类中添加@MapperScan注解,扫描mapper包


@SpringBootApplication
@MapperScan("com.heshujia.mybatis_plus.mapper")
public class MybatisPlusApplication {public static void main(String[] args) {SpringApplication.run(MybatisPlusApplication.class, args);}}

实体类

lomok注解有

@NoArgsConstructor  无参构造

@AllArgsConstructor  有参构造

@Getter get方法

@Setter set方法

@Data  包含了get set 方法 和tostring 和hashCode等

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {private Long id;private String name;private Integer age;private String email;
}

mapper 

BaseMapper是MyBatis-Plus提供的模板mapper,其中包含了基本的CRUD方法,泛型为操作的 实体类型
@Repository
public interface UserMapper extends BaseMapper<User> {}

测试

@SpringBootTest
class MybatisPlusApplicationTests {@AutowiredUserMapper userMapper;@Testvoid getUserList() {
//        测试查询  selectList 查出所有数据// SELECT id,name,age,email FROM userList<User> users = userMapper.selectList(null);users.forEach(System.out::println);}}

BaseMapper中的基本crud

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


@SpringBootTest
class MybatisPlusApplicationTests {@AutowiredUserMapper userMapper;@Testvoid contextLoads() {}@Testvoid getUserList() {
//        测试查询  selectList 查出所有数据// SELECT id,name,age,email FROM userList<User> users = userMapper.selectList(null);users.forEach(System.out::println);}@Testvoid getUserByMap() {//    根据Map集合设置条件查询// SELECT id,name,age,email FROM user WHERE name = ? AND age = ?Map<String, Object> HashMap = new HashMap<>();HashMap.put("name","Tom");HashMap.put("age","28");List<User> users = userMapper.selectByMap(HashMap);users.forEach(System.out::println);}@Testvoid getUserBatch() {//    根据id批量查询// SELECT id,name,age,email FROM user WHERE name = ? AND age = ?List<Long> longs = Arrays.asList(1L, 2l, 3L);List<User> users = userMapper.selectBatchIds(longs);users.forEach(System.out::println);}@Testvoid UserInsert() {//        插入数据   insert// SELECT id,name,age,email FROM user WHERE id IN ( ? , ? , ? )int i = userMapper.insert(new User(null, "老贺", 21, "1870562227@qq.com"));System.out.println(i);}@Testvoid UserDelete() {//删除数据  deleteById 传Long类型数据// DELETE FROM user WHERE id=?int i = userMapper.deleteById(5L);System.out.println(i);}@Testvoid UserDeleteMap() {//  根据Map集合设置的条件删除  把key,value做为条件//DELETE FROM user WHERE name = ? AND age = ?Map<String, Object> HashMap = new HashMap<>();HashMap.put("name","jack");HashMap.put("age","20");userMapper.deleteByMap(HashMap);}@Testvoid UserBatchDelete() {//根据id批量删除数据//DELETE FROM user WHERE id IN ( ? , ? , ? )List<Long> longs = Arrays.asList(1L, 3L,4L);int i = userMapper.deleteBatchIds(longs);System.out.println(i);}@Testvoid UserUpdeteId() {//根据id修改数据//UPDATE user SET name=?, age=? WHERE id=?User user = new User();user.setId(1L);user.setName("王不起");user.setAge(35);int i = userMapper.updateById(user);System.out.println(i);}}

自定义方法

mybatisplus在 MyBatis 的基础上只做增强不做改变,为 简化开发、提高效率而生。

yml添加

mybatis-plus:
#默认是 classpath*:/mapper/**/*.xml 这里演示自定义mapper文件路径mapper-locations: classpath*:/mapperFile/*.xml

mapper

@Repository
public interface UserMapper extends BaseMapper<User> {@MapKey("id") //将id作为KeyMap<String,Object>  getUserMap(Long id);
}

mapper配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.heshujia.mybatis_plus.mapper.UserMapper"><select id="getUserMap" resultType="map">select  * from  user  where id=#{id}</select>
</mapper>

测试

    @Testvoid getUserMap() {//测试自定义方法  mybatisPlus只做增强不做修改,所以之前mybatis编写mapper文件的方法也能用//select * from user where id=?Map<String, Object> userMap = userMapper.getUserMap(1L);System.out.println(userMap);}

通用Service

  • 通用 Service CRUD 封装IService接口,进一步封装 CRUD 采用 get 查询单行 remove 删
  • 除 list 查询集合 page 分页 前缀命名方式区分 Mapper 层避免混淆.
  • 泛型 T 为任意实体对象.
  • 建议如果存在自定义通用 Service 方法的可能,请创建自己的 IBaseService 继承 Mybatis-Plus 提供的基类.
  • 官网地址:https://baomidou.com/pages/49cc81/#service-crud-%E6%8E%A5%E5%8F%A

创建Service接口和实现类


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

测试其中方法

@SpringBootTest
class MybatisPlusApplicationTests {
@AutowireduserServiceimp userServiceimp;@Testvoid getcount() {//查询表数据数量//SELECT COUNT( * ) FROM t_userint count = userServiceimp.count();System.out.println(count);}@Testvoid getBaseMapper1() {//批量添加方法//INSERT INTO t_user ( t_id, t_name, age, email, isDeleted ) VALUES ( ?, ?, ?, ?, ? )List<User> strings = new ArrayList<>();for (int i=0;i<5;i++){strings.add(new User(null,"abc"+i,20+i,i+"@qq.com",0));}userServiceimp.saveBatch(strings);}
}

常用注解

示例

@AllArgsConstructor
@NoArgsConstructor
@Data
@TableName("t_user")
public class User {@TableId(value = "t_id")private Long id;@TableField("t_name")private String name;private Integer age;private String email;@TableLogic@TableField("isDeleted")private  Integer isDeleted;
}

1、@TableName

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

也可以通过全局配置解决问题,配置前缀
mybatis-plus:configuration:
#添加日志log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#  global-config:
#    db-config:
#     配置MyBatis-Plus操作表的默认前缀
#      table-prefix: t_

2@TableId

若实体类和表中表示主键的不是id,而是其他字段,例如uid,MyBatis-Plus不会自动识别uid为主键.
在实体类中uid属性上通过@TableId将其标识为主键,即可成功执行SQL语句

@TableIdvalue属性
可以通过@TableId注解的value属性,指定表中的主键字段,@TableId("uid")或 @TableId(value="uid")
@TableIdtype属性
type属性用来定义主键策略 .参数为一个枚举类型

public enum IdType {AUTO(0),NONE(1),INPUT(2),ASSIGN_ID(3),ASSIGN_UUID(4),/** @deprecated */@DeprecatedID_WORKER(3),/** @deprecated */@DeprecatedID_WORKER_STR(3),/** @deprecated */@DeprecatedUUID(4);private final int key;private IdType(int key) {this.key = key;}public int getKey() {return this.key;}
}
  • IdType.ASSIGN_ID(默 认 基于雪花算法的策略生成数据id,与数据库id是否设置自增无关
  • IdType.AUTO 使用数据库的自增策略,注意,该类型请确保数据库设置了id自增否则无效

配置全局主键策略:
mybatis-plus:configuration:
#添加日志log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#  global-config:
#    db-config:
# 配置全局主键策略
#      id-type: auto

3@TableField

如果实体类中的属性名和字段名不一致的情况
就需要在实体类属性上使用@TableField("username")设置属性所对应的字段名

4@TableLogic

逻辑删除
  • 物理删除:真实删除,将对应数据从数据库中删除,之后查询不到此条被删除的数据
  • 逻辑删除:假删除,将对应数据中代表是否被删除字段的状态修改为“被删除状态”,之后在数据库 中仍旧能看到此条数据记录  ,使用场景:可以进行数据恢复

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

实体类中添加逻辑删除属性,@TableLogic
@TableLogic@TableField("isDeleted")private  Integer isDeleted;

雪花算法

需要选择合适的方案去应对数据规模的增长,以应对逐渐增长的访问压力和数据量。
数据库的扩展方式主要包括:业务分库、主从复制,数据库分表。
数据库分表
将不同业务数据分散存储到不同的数据库服务器,能够支撑百万甚至千万用户规模的业务,但如果业务 继续发展,同一业务的单表数据也会达到单台数据库服务器的处理瓶颈。例如,淘宝的几亿用户数据, 如果全部存放在一台数据库服务器的一张表中,肯定是无法满足性能要求的,此时就需要对单表数据进 行拆分。
单表数据拆分有两种方式:垂直分表和水平分表。示意图如下:
垂直分表
垂直分表适合将表中某些不常用且占了大量空间的列拆分出去。
例如,前面示意图中的 nickname 和 description 字段,假设我们是一个婚恋网站,用户在筛选其他用 户的时候,主要是用 age 和 sex 两个字段进行查询,而 nickname 和 description 两个字段主要用于展 示,一般不会在业务查询中用到。description 本身又比较长,因此我们可以将这两个字段独立到另外 一张表中,这样在查询 age 和 sex 时,就能带来一定的性能提升。

水平分表

水平分表适合表行数特别大的表,有的公司要求单表行数超过 5000 万就必须进行分表,这个数字可以 作为参考,但并不是绝对标准,关键还是要看表的访问性能。对于一些比较复杂的表,可能超过 1000 万就要分表了;而对于一些简单的表,即使存储数据超过 1 亿行,也可以不分表。
但不管怎样,当看到表的数据量达到千万级别时,作为架构师就要警觉起来,因为这很可能是架构的性 能瓶颈或者隐患。
水平分表相比垂直分表,会引入更多的复杂性,例如要求全局唯一的数据id该如何处理
主键自增
①以最常见的用户 ID 为例,可以按照 1000000 的范围大小进行分段,1 ~ 999999 放到表 1中,
1000000 ~ 1999999 放到表2中,以此类推。
②复杂点:分段大小的选取。分段太小会导致切分后子表数量过多,增加维护复杂度;分段太大可能会 导致单表依然存在性能问题,一般建议分段大小在 100 万至 2000 万之间,具体需要根据业务选取合适 的分段大小。
③优点:可以随着数据的增加平滑地扩充新的表。例如,现在的用户是 100 万,如果增加到 1000 万, 只需要增加新的表就可以了,原有的数据不需要动。
④缺点:分布不均匀。假如按照 1000 万来进行分表,有可能某个分段实际存储的数据量只有 1 条,而 另外一个分段实际存储的数据量有 1000 万条。
取模
①同样以用户 ID 为例,假如我们一开始就规划了 10 个数据库表,可以简单地用 user_id % 10 的值来 表示数据所属的数据库表编号,ID 为 985 的用户放到编号为 5 的子表中,ID 为 10086 的用户放到编号 为 6 的子表中。
②复杂点:初始表数量的确定。表数量太多维护比较麻烦,表数量太少又可能导致单表性能存在问题。
③优点:表分布比较均匀。
④缺点:扩充新的表很麻烦,所有数据都要重分布。
雪花算法
雪花算法是由Twitter公布的分布式主键生成算法,它能够保证不同表的主键的不重复性,以及相同表的 主键的有序性。
①核心思想:
长度共64bit(一个long型)。
首先是一个符号位,1bit标识,由于long基本类型在Java中是带符号的,最高位是符号位,正数是0,负 数是1,所以id一般是正数,最高位是0。
41bit时间截(毫秒级),存储的是时间截的差值(当前时间截 - 开始时间截),结果约等于69.73年。
10bit作为机器的ID(5个bit是数据中心,5个bit的机器ID,可以部署在1024个节点)。
12bit作为毫秒内的流水号(意味着每个节点在每毫秒可以产生 4096 个 ID)。
②优点:整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞,并且效率较高

条件构造器和常用接口

1wapper介绍

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

2QueryWrapper

2.1 组装查询条件
@Testpublic  void test1(){//测试条件构造器查询//  SELECT t_id AS id,t_name AS name,age,email,isDeleted FROM t_user//  WHERE isDeleted=0 AND (t_name LIKE ? AND age BETWEEN ?QueryWrapper<User> QueryWrapper = new QueryWrapper<>();QueryWrapper.like("t_name","a").between("age",20,21).isNotNull("email");userMapper.selectList(QueryWrapper);}
2.2组装排序条件
@Testpublic  void test2(){//条件构造器排序//按年龄降序查询用户,如果年龄相同则按id升序排列//SELECT t_id AS id,t_name AS name,age,email,isDeleted FROM t_user WHERE isDeleted=0 ORDER BY age DESC,t_id ASCQueryWrapper<User> QueryWrapper = new QueryWrapper<>();QueryWrapper.orderByDesc("age").orderByAsc("t_id");userMapper.selectList(QueryWrapper);}
2.3组装删除条件
  @Testpublic  void test3(){//条件构造器 删除//email为空的进行逻辑删除//UPDATE t_user SET isDeleted=1 WHERE isDeleted=0 AND (email IS NULL)QueryWrapper<User> QueryWrapper = new QueryWrapper<>();QueryWrapper.isNull("email");userMapper.delete(QueryWrapper);}
2.4条件的优先级
  @Testpublic  void test4(){//UPDATE t_user SET age=?, email=? WHERE isDeleted=0 AND (t_name LIKE ? AND age > ? OR email IS NULL)QueryWrapper<User> QueryWrapper = new QueryWrapper<>();QueryWrapper.like("t_name","a").gt("age",20).or().isNull("email");userMapper.update(new User(null,null,18,"user@qq.com",null),QueryWrapper);
}
 @Testpublic  void test5(){//UPDATE t_user SET age=?, email=? WHERE isDeleted=0 AND (t_name LIKE ? AND (age > ? OR email IS NULL))//将用户名中包含有a并且(年龄大于20或邮箱为null)的用户信息修改QueryWrapper<User> QueryWrapper = new QueryWrapper<>();QueryWrapper.like("t_name","a").and(i-> i.gt("age",20).or().isNull("email"));userMapper.update(new User(null,null,20,"user@qq.com",null),QueryWrapper);}

2.5组装select子句
select()
 @Testpublic  void test6(){//组装select子句//    SELECT t_name,age FROM t_user WHERE isDeleted=0// 查询用户信息的username和age字段
selectMaps()返回Map集合列表,通常配合select()使用,避免User对象中没有被查询到的列值 为null//selectMaps()返回Map集合列表,通常配合select()使用,避免User对象中没有被查询到的列值 为nullQueryWrapper<User> QueryWrapper = new QueryWrapper<>();QueryWrapper.select("t_name","age");List<Map<String, Object>> maps = userMapper.selectMaps(QueryWrapper);maps.forEach(System.out::println);}

2.6.实现子查询

insql()

 @Testpublic  void test7(){//查询id小于等于3的用户信息//实现子查询//SELECT t_id AS id,t_name AS name,age,email,isDeleted FROM t_user// WHERE isDeleted=0 AND (t_id IN (SELECT t_id FROM t_user WHERE t_idQueryWrapper<User> objectQueryWrapper = new QueryWrapper<>();objectQueryWrapper.inSql("t_id","SELECT t_id FROM t_user WHERE t_id <=4");List<User> users = userMapper.selectList(objectQueryWrapper);users.forEach(System.out::println);}

3.UpdateWrapper

    @Testpublic  void test8(){
//UpdateWrapper//将(年龄大于20或邮箱为null)并且用户名中包含有a的用户信息修改// 组装set子句以及修改条件//lambda表达式内的逻辑优先运算//UPDATE t_user SET t_name=?,age=? WHERE isDeleted=0 AND (t_name LIKE ? AND (age > ? OR email IS NULL))UpdateWrapper<User> objectUpdateWrapper = new UpdateWrapper<>();objectUpdateWrapper.like("t_name","a").and(i-> i.gt("age",20).or().isNull("email")).set("t_name","刘德华").set("age",18);userMapper.update(null,objectUpdateWrapper);}

4.condition

@Test
public  void test9(){
//StringUtils.isNotBlank()判断某字符串是否不为空且长度不为0且不由空白符(whitespace) 构成
定义查询条件,有可能为null(用户未输入或未选择)QueryWrapper<User> QueryWrapper = new QueryWrapper<>();User user = new User();user.setAge(18);user.setName("刘德华");QueryWrapper. like(StringUtils.isNotBlank(user.getName()),"t_name",user.getName()).and(i-> i.gt(user.getAge()!=null,"age",user.getAge()).or().isNull("email"));userMapper.selectList(QueryWrapper);}

5LambdaQueryWrapper

避免使用字符串表示字段,防止运行时错误

@Testpublic  void test10(){
//LambdaQueryWrapper//SELECT t_id AS id,t_name AS name,age,email,isDeleted FROM t_user WHERE isDeleted=0 AND (t_name LIKE ? AND age > ?)LambdaQueryWrapper<User> QueryWrapper = new LambdaQueryWrapper<>();String name="刘德华";Integer age=18;QueryWrapper. like(StringUtils.isNotBlank(name),User::getName,name).gt(age!=null,User::getAge,age);userMapper.selectList(QueryWrapper);}

6LambdaUpdateWrapper

表达式内的逻辑优先运算

    @Testpublic  void test11(){//LambdaUpdateWrapper//UPDATE t_user SET age=?,t_name=? WHERE isDeleted=0 AND (t_name LIKE ? AND age > ?)LambdaUpdateWrapper<User> objectLambdaUpdateWrapper = new LambdaUpdateWrapper<>();String name="张学友";Integer age=18;objectLambdaUpdateWrapper.set(age!=null,User::getAge,age).set(StringUtils.isNotBlank(name),User::getName,name).like(StringUtils.isNotBlank(name),User::getName,name).gt(age!=null,User::getAge,age);int update = userMapper.update(null, objectLambdaUpdateWrapper);}

插件

分页插件

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

添加配置类

@Configuration
public class mybatisPlusConfig {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor(){MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();//添加分页插件mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return mybatisPlusInterceptor;}
}
测试
@SpringBootTest
public class mybaitsPlusPageTest {
@AutowiredUserMapper userMapper;@Testpublic  void test01(){//第一个参数为页码,第二个参数为每页记录数Page<User> Page = new Page<>(1,2);Page<User> userPage = userMapper.selectPage(Page, null);List<User> records = Page.getRecords();records.forEach(System.out::println);System.out.println("当前页:"+Page.getCurrent());System.out.println("每页显示的记录数:"+Page.getSize());System.out.println("总记录数:"+Page.getTotal());System.out.println("总页数:"+Page.getPages());System.out.println("是否有上一页:"+Page.hasPrevious());System.out.println("是否有下一页:"+Page.hasNext());}
}
xml自定义分页使用
@Repository
public interface UserMapper extends BaseMapper<User> {Page<User> selectPageVo(@Param("page") Page<User> page,@Param("age") Integer age);
}

编写userMapper.xml

<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.heshujia.mybatis_plus.mapper.UserMapper"><select id="selectPageVo" resultType="com.heshujia.mybatis_plus.pojo.User">select  * from  t_user  where age > #{age}</select>
</mapper>

测试

@Testpublic  void test02(){//第一个参数为页码,第二个参数为每页记录数Page<User> Page = new Page<>(1,3);Page<User> userPage = userMapper.selectPageVo(Page, 23);List<User> records = Page.getRecords();records.forEach(System.out::println);System.out.println("当前页:"+Page.getCurrent());System.out.println("每页显示的记录数:"+Page.getSize());System.out.println("总记录数:"+Page.getTotal());System.out.println("总页数:"+Page.getPages());System.out.println("是否有上一页:"+Page.hasPrevious());System.out.println("是否有下一页:"+Page.hasNext());}

乐观锁

模拟修改冲突

1.表创建与数据添加
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);

2.添加实体类

@TableName("t_product")
@Data
public class Product {private  Long id;private  String name;private  Integer price;private  Integer version;
}

3.添加Mapper


@Repository
public interface ProductMapper  extends BaseMapper<Product> {
}
测试
@SpringBootTest
public class productTest {@AutowiredProductMapper productMapper;@Testpublic  void test01(){Product product_He = productMapper.selectById(1L);System.out.println("老贺取出的价格:"+product_He.getPrice());//100Product product_Liu = productMapper.selectById(1L);System.out.println("老刘取出的价格:"+product_Liu.getPrice()); //100//老贺将价格加了50快product_He.setPrice(product_He.getPrice()+50); //100+50int i = productMapper.updateById(product_He);System.out.println("老贺修改结果"+i);//老刘将价格减了30块product_Liu.setPrice(product_Liu.getPrice()-30);//100-30int r = productMapper.updateById(product_Liu);System.out.println("老刘修改结果"+r);//最后的结果Product productBoss = productMapper.selectById(1L);System.out.println("最终的价格为:"+productBoss.getPrice());//输出70,因为后面的修改操作把前面的覆盖了}}

乐观锁实现流程

修改实体类
version属性加上@Version注解
package com.heshujia.mybatis_plus.pojo;import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.Version;
import lombok.Data;
@TableName("t_product")
@Data
public class Product {private  Long id;private  String name;private  Integer price;@Versionprivate  Integer version;
}
添加乐观锁插件配置


@Configuration
public class mybatisPlusConfig {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor(){MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();//添加乐观锁插件mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());return mybatisPlusInterceptor;}
}

再次测试并优化

取出记录时,获取当前version
更新时,version + 1,如果where语句中的version版本不对,则更新失败
@SpringBootTest
public class productTest {@AutowiredProductMapper productMapper;@Testpublic  void test01(){Product product_He = productMapper.selectById(1L);System.out.println("老贺取出的价格:"+product_He.getPrice());//100Product product_Liu = productMapper.selectById(1L);System.out.println("老刘取出的价格:"+product_Liu.getPrice()); //100//老贺将价格加了50快product_He.setPrice(product_He.getPrice()+50); //100+50int i = productMapper.updateById(product_He);System.out.println("老贺修改结果"+i);//老刘将价格减了30块product_Liu.setPrice(product_Liu.getPrice()-30);//100-30int r = productMapper.updateById(product_Liu);System.out.println("老刘修改结果"+r);  //因为多了版本号判断,如果版本号不一致必然失败if (r==0){//失败重试Product product = productMapper.selectById(1L);product.setPrice(product.getPrice()-30);//150-30productMapper.updateById(product);}//最后的结果Product productBoss = productMapper.selectById(1L);System.out.println("最终的价格为:"+productBoss.getPrice());//输出120}}

通用枚举

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

实体类和数据库表添加字段sex
@AllArgsConstructor
@NoArgsConstructor
@Data
@TableName("t_user")
public class User {@TableId(value = "t_id")private Long id;@TableField("t_name")private String name;private Integer age;private String email;@TableLogic@TableField("isDeleted")private  Integer isDeleted;@TableField("sex")private sexEnum sexEnum;
}

创建通用枚举类型

@EnumValue


@Getter
public enum sexEnum {MALE(1,"男"),FEMALE(2,"女");@EnumValueprivate  Integer sex;private  String sexName;sexEnum(Integer sex,String sexName){this.sex=sex;this.sexName=sexName;}
}

配置扫描通用枚举

mybatis-plus:configuration:
#添加日志log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#默认是 classpath*:/mapper/**/*.xml 这里演示自定义mapper文件路径mapper-locations: classpath*:/mapperFile/*.xml# 配置扫描通用枚举type-enums-package: com.heshujia.mybatis_plus.pojo
#  global-config:
#    db-config:
#      id-type: auto
#     配置MyBatis-Plus操作表的默认前缀
#      table-prefix: t_

测试

@SpringBootTest
public class EnumTest {@AutowiredUserMapper  userMapper;@Testpublic  void testSextEnum(){//INSERT INTO t_user ( t_id, t_name, age, isDeleted, sex ) VALUES ( ?, ?, ?, ?, ? )//设置性别信息为枚举项,会将@EnumValue注解所标识的属性值存储到数据库userMapper.insert(new User(null,"Enum",20,null,0, sexEnum.FEMALE));}}

多数据源

适用于多种场景:纯粹多库、 读写分离、 一主多从、 混合模式等
目前我们就来模拟一个纯粹多库的一个场景,其他场景类似
场景说明:
我们创建两个库,分别为:mybatis_plus(以前的库不动)与mybatis_plus_1(新建),将
mybatis_plus库的product表移动到mybatis_plus_1库,这样每个库一张表,通过一个测试用例
分别获取用户数据与商品数据,如果获取到说明多库模拟成功
引入依赖
       <dependency><groupId>com.baomidou</groupId><artifactId>dynamic-datasource-spring-boot-starter</artifactId><version>3.5.0</version></dependency>
多数据源前置准备
创建2个数据库:mybatis_plus和mybaits_plus_1 
在mybatis_plus数据库中创建User表,在mybatis_plus_1数据库中创建product表.
实体类根据表自行编写
配置多数据源
spring:# 配置多数据源信息datasource:dynamic:# 设置默认的数据源或者数据源组,默认值即为masterprimary: master# 严格匹配数据源,默认false.true未匹配到指定数据源时抛异常,false使用默认数据源strict: falsedatasource:master:url: jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&serverTimezone=GMT%2B8driver-class-name: com.mysql.cj.jdbc.Driverusername: rootpassword: rootslave_1:url: jdbc:mysql://localhost:3306/mybatis_plus_1?useSSL=false&serverTimezone=GMT%2B8driver-class-name: com.mysql.cj.jdbc.Driverusername: rootpassword: rootmybatis-plus:configuration:#添加日志log-impl: org.apache.ibatis.logging.stdout.StdOutImpl# 配置扫描通用枚举type-enums-package: com.example.demo.pojo
创建userMapper和user service

@Repository
public interface UserMapper extends BaseMapper<User> {}
@DS("master")
@Service
public class userServiceimp extends ServiceImpl<UserMapper, User> implements userService {
}

创建productMapper和product service

@Repository
public interface ProductMapper  extends BaseMapper<Product> {
}
@DS("slave_1")
@Service
public class productServiceimp extends ServiceImpl<ProductMapper, Product> implements productService {
}
测试
@SpringBootTest
class DemoApplicationTests {@AutowiredproductService productService;@AutowireduserService userService;@Testpublic  void test01(){Product product = productService.getById(1L);User user = userService.getById(1L);System.out.println(product);System.out.println(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>

快速生成

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

MyBatisX插件

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

MyBatis-Plus笔记相关推荐

  1. mybatis学习笔记(13)-延迟加载

    2019独角兽企业重金招聘Python工程师标准>>> mybatis学习笔记(13)-延迟加载 标签: mybatis [TOC] resultMap可以实现高级映射(使用asso ...

  2. mybatis学习笔记(7)-输出映射

    2019独角兽企业重金招聘Python工程师标准>>> mybatis学习笔记(7)-输出映射 标签: mybatis [TOC] 本文主要讲解mybatis的输出映射. 输出映射有 ...

  3. mybatis学习笔记(3)-入门程序一

    2019独角兽企业重金招聘Python工程师标准>>> mybatis学习笔记(3)-入门程序一 标签: mybatis [TOC] 工程结构 在IDEA中新建了一个普通的java项 ...

  4. MyBatis多参数传递之Map方式示例——MyBatis学习笔记之十三

    前面的文章介绍了MyBatis多参数传递的注解.参数默认命名等方式,今天介绍Map的方式.仍然以前面的分页查询教师信息的方法findTeacherByPage为例(示例源代码下载地址:http://d ...

  5. ant的下载与安装——mybatis学习笔记之预备篇(一)

    看到这个标题是不是觉得有点奇怪呢--不是说mybatis学习笔记吗,怎么扯到ant了?先别急,请容我慢慢道来. mybatis是另外一个优秀的ORM框架.考虑到以后可能会用到它,遂决定提前学习,以备不 ...

  6. SpringBoot集成Mybatis用法笔记

    今天给大家整理SpringBoot集成Mybatis用法笔记.希望对大家能有所帮助! 搭建一个SpringBoot基础项目. 具体可以参考SpringBoot:搭建第一个Web程序 引入相关依赖 &l ...

  7. mybatis学习笔记--常见的错误

    原文来自:<mybatis学习笔记--常见的错误> 昨天刚学了下mybatis,用的是3.2.2的版本,在使用过程中遇到了些小问题,现总结如下,会不断更新. 1.没有在configurat ...

  8. mybatis学习笔记(1)-对原生jdbc程序中的问题总结

    2019独角兽企业重金招聘Python工程师标准>>> mybatis学习笔记(1)-对原生jdbc程序中的问题总结 标签:mybatis [TOC] 本文总结jdbc编程的一般步骤 ...

  9. MyBatis:学习笔记(4)——动态SQL

    MyBatis:学习笔记(4)--动态SQL 转载于:https://www.cnblogs.com/MrSaver/p/7453949.html

  10. Mybatis学习笔记(二) 之实现数据库的增删改查

    开发环境搭建 mybatis 的开发环境搭建,选择: eclipse j2ee 版本,mysql 5.1 ,jdk 1.7,mybatis3.2.0.jar包.这些软件工具均可以到各自的官方网站上下载 ...

最新文章

  1. Day3:数据类型(布尔值、集合)
  2. LiveVideoStack主编观察04 /
  3. rocketmq 同步刷盘和异步刷盘以及主从复制之同步复制和异步复制你理解了吗
  4. html加入购物车的动画,vue实现加入购物车动画
  5. PYTHON-anaconda-安装
  6. redis数据库及与python交互
  7. c语言大作业走迷宫,基于C语言实现简单的走迷宫游戏
  8. linux 按列提取文件名,Linux展示按文件名降序文件
  9. 大数据分析平台的作用有什么
  10. Android 10.0修改语言设置简体中文(中国)为简体中文(中国大陆)
  11. MS-DOS虚拟机安装
  12. 同个网络找不到计算机打印机共享,局域网共享打印机搜索不到怎么办 局域网共享打印机搜索不到解决方法...
  13. 端到端和非端到端的Embedding,以及embedding质量评估
  14. 微信小程序服务端调用--小程序码 wxacode.getUnlimited 接口调用,实现微信扫码直接跳转小程序页面
  15. software_reporter_tool 进程关闭的优雅法子
  16. Oracle配置本地网络服务名
  17. 北大教授:学术会议,已沦为表演
  18. Unity 解决 An asset is marked with HideFlags.DontSave but is included in the build 问题
  19. VoIP通话-基于SIP协议的Asterisk(一)-实现流程
  20. linux fcitx改mac输入法,Linux安装fcitx输入法

热门文章

  1. 利用python画各类世界、中国、区县地图(转)
  2. oracle更改分区表结构,Oracle分区修改的语句
  3. 机器学习--SVM(支持向量机)核函数原理以及高斯核函数
  4. 伙伴算法和slab_20多种免费的Slab Serif字体用于徽标和标题
  5. 【 华为OD机试 2023】 查找充电设备组合/最接近最大输出功率的设备 (C++ Java JavaScript Python 100%)
  6. 蒙特卡洛数值模拟-计算定积分的两种方法
  7. 手机电子邮件如何绑定公司企业邮箱
  8. 【ES实战】索引mapping的动态设置
  9. 关于GP2Y1010AU0F SHARP传感器使用
  10. 目标检测算法——收藏|小目标检测解决方案(三)