菜鸟的mybatis plus学习总结

  • 说明
  • 一、项目配置
    • (1)sql文件
    • (2)pom
    • (3)配置文件
  • 二、简单入门
  • 三、主键生成策略
  • 四、字段填充
  • 五、乐观锁
  • 六、分页查询
  • 七、逻辑删除
  • 八、条件构造器
  • 九、代码生成器
  • 十、注解集合
    • @TableName
    • @TableId
    • @TableField
    • @Version
    • @EnumValue
    • @TableLogic
    • @SqlParser
    • @KeySequence
  • 十一、补充
    • (1)将字段更新为null

说明

更新时间:2020/11/3 17:51,更新了注解集合
更新时间:2020/8/31 15:47,更新了代码生成器
更新时间:2020/8/22 16:34,更新了mybatis plus基本内容

本文主要对mybatis plus学习总结,本文会持续更新,不断地扩充

本文仅为记录学习轨迹,如有侵权,联系删除

一、项目配置

(1)sql文件

/*Navicat Premium Data TransferSource Server         : test1Source Server Type    : MySQLSource Server Version : 80015Source Host           : localhost:3306Source Schema         : test1Target Server Type    : MySQLTarget Server Version : 80015File Encoding         : 65001Date: 22/08/2020 16:35:37
*/SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',`name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '姓名',`age` int(11) NULL DEFAULT NULL COMMENT '年龄',`email` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '邮箱',`version` int(10) NULL DEFAULT NULL COMMENT '乐观锁',`update_time` datetime(0) NULL DEFAULT NULL COMMENT '更新时间',`create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',`deleted` int(1) NULL DEFAULT NULL COMMENT '逻辑删除',`password` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '密码',`phone` varchar(11) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '电话号码',PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1297022245490749443 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = 'user' ROW_FORMAT = Dynamic;-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, '灰太狼', 12, 'test1@baomidou.com', 3, '2020-07-03 12:51:25', '2020-07-03 12:51:25', 0, '123', '15698547896');
INSERT INTO `user` VALUES (2, '喜羊羊', 20, 'test2@baomidou.com', 1, '2020-07-03 11:47:47', '2020-07-03 11:47:47', 0, '123', '15698547896');
INSERT INTO `user` VALUES (3, 'Tonny', 28, 'test3@baomidou.com', 1, '2020-07-03 11:47:49', '2020-07-03 11:47:49', 0, '123', '15698547896');
INSERT INTO `user` VALUES (4, 'Sandy', 21, 'test4@baomidou.com', 1, '2020-07-03 11:47:51', '2020-07-03 11:47:51', 0, '123', '15698547896');
INSERT INTO `user` VALUES (5, 'Tonny', 24, 'test5@baomidou.com', 1, '2020-07-03 11:47:53', '2020-07-03 11:47:53', 0, '123', '15698547896');
INSERT INTO `user` VALUES (6, 'Tonny', 2, '123456@qq.com', 1, '2020-07-03 11:59:01', '2020-07-03 11:59:01', 0, '123', '15698547896');
INSERT INTO `user` VALUES (7, '李四2', 2, '123456@qq.com', 10, '2020-08-16 11:46:14', '2020-08-15 17:49:33', 0, '123', '15698547896');
INSERT INTO `user` VALUES (8, '张三', 19, '123@qq.com', NULL, '2020-08-22 15:38:04', '2020-08-22 15:38:04', 0, NULL, NULL);
INSERT INTO `user` VALUES (9, '张三', 19, '123@qq.com', NULL, '2020-08-22 15:41:44', '2020-08-22 15:41:44', 0, NULL, NULL);
INSERT INTO `user` VALUES (10, '张三', 19, '123@qq.com', NULL, '2020-08-22 15:42:48', '2020-08-22 15:42:48', 0, NULL, NULL);
INSERT INTO `user` VALUES (11, '张三', 19, '123@qq.com', 1, '2020-08-22 15:43:23', '2020-08-22 15:43:23', 1, NULL, NULL);SET FOREIGN_KEY_CHECKS = 1;

(2)pom

下面用到的pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.6.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.zsc</groupId><artifactId>mybatis_plus</artifactId><version>0.0.1-SNAPSHOT</version><name>mybatis_plus</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency><!--mybatis-plus依赖--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.3.1</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!--hutool--><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.3.10</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

(3)配置文件

#激活开发环境
spring.profiles.active=dev#mysql数据库连接信息
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.url=jdbc:mysql://localhost:3306/test1?userSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver#配置日志
#mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl#配置逻辑删除
#没有逻辑删除为0,已经逻辑删为1
mybatis-plus.global-config.db-config.logic-delete-field=deleted
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0

二、简单入门

pom.xml,这里采用3.0.5,目前最新的有3.3.2版本,该版本与最新版有一些区别,为了方便,这里依然采用3.0.5

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

创建实体

@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("user")
public class User {private Long id;private String name;private Integer age;private String email;private Integer deleted;private String password;private String phone;private LocalDateTime createTime;private LocalDateTime updateTime;private Integer version;
}

在主启动类中添加要扫描的包(mapper)路径

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;//扫描mapper文件夹
@MapperScan("com.zsc.mapper")
@SpringBootApplication
public class MybatisPlusApplication {public static void main(String[] args) {SpringApplication.run(MybatisPlusApplication.class, args);}}

创建持久层接口UserMapper

package com.zsc.mapper;import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zsc.pojo.User;
import org.springframework.stereotype.Repository;import java.util.List;/*** 在对应的mapper接口上继承BaseMapper类,即可完成所有的crud操作*/
@Repository
public interface UserMapper extends BaseMapper<User> {//至此所有的crud操作都已经完成}

BaseMapper之后,到此为止,所有的crud操作都已经完成,下面开始测试

测试

    /*** 测试插入*/@Testpublic void testInsert(){User user = new User();user.setName("红太狼");user.setAge(10);user.setEmail("123456@qq.com");int result = userMapper.insert(user);//自动帮我们生成idSystem.out.println(result);//受影响的行数System.out.println(user);//发现id会自动回填}/*** 测试更新*/@Testpublic void testUpdate(){User user = new User();//动态拼接sqluser.setId(1252260852669706244L);user.setAge(2);//参数是一个userint i = userMapper.updateById(user);System.out.println(i);}//其余的就不测试了

三、主键生成策略

首先数据库的主键先设置为自增

修改实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("user")
public class User {/**(1)主键策略* 关于mybatis-plus,简称MP* MP开启了驼峰转下划线,操作的sql语句,会依据属性名转换为下划线的列名称,如,会将userId转换为user_id  会将userIdS转换为user_id_s*** @TableId(type = IdType.AUTO)* 关于IdType重点* public enum IdType {*     AUTO(0),//数据库自增 依赖数据库*     NONE(1),// 表示该类型未设置主键类型 (如果没有主键策略)默认根据雪花算法生成*     INPUT(2),//用户输入ID(该类型可以通过自己注册填充插件进行填充)*   //下面这三种类型,只有当插入对象id为空时 才会自动填充。*     ID_WORKER(3),//全局唯一(idWorker)数值类型*     UUID(4),//全局唯一(UUID)*     ID_WORKER_STR(5);//全局唯一(idWorker的字符串表示)* }** 例如:* 在实体类中 ID属性加注解* @TableId(type = IdType.AUTO) 主键自增 数据库中需要设置主键自增* private Long id;* @TableId(type = IdType.NONE) 默认 跟随全局策略走* private Long id;* @TableId(type = IdType.UUID) UUID类型主键* private Long id;* @TableId(type = IdType.ID_WORKER) 数值类型  数据库中也必须是数值类型 否则会报错* private Long id;* @TableId(type = IdType.ID_WORKER_STR) 字符串类型   数据库也要保证一样字符类型* private Long id;* @TableId(type = IdType.INPUT) 用户自定义了  数据类型和数据库保持一致就行* private Long id;***///如果数据库对应id是自增长的,这里对应id也要设值为自增长,注意,同时得保证数据库对应的id也是自增长的,不然会报错@TableId(type = IdType.AUTO)private Long id;private String name;private Integer age;private String email;private Integer deleted;private String password;private String phone;private LocalDateTimecreateTime;private LocalDateTimeupdateTime;private Integer version;
}

其余不变,进行插入操作时,id会跟随主键策略变化

四、字段填充

像有些字段例如创建时间,版本号(用于乐观锁)、修改时间!这些个操作一遍都是自动化完成的,我们不希望手动更新,这个时候就需要进行字段的自动填充

创建公共元处理器MyMetaObjectHandler

package com.zsc.handler;import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;import java.time.LocalDateTime;
import java.util.Date;/*** @ClassName : MyMetaObjectHandler* @Description : 公共元数据处理器,用于mybatis* @Author : CJH* @Date: 2020-08-15 16:06*/@Slf4j
@Component//一定不要忘记把处理器加入IOC容器中
public class MyMetaObjectHandler implements MetaObjectHandler {//插入时的填充策略@Overridepublic void insertFill(MetaObject metaObject) {log.info("数据库表创建,开始填充系统字段...");this.setFieldValByName("createTime",LocalDateTime.now(),metaObject);//        过期方法
//        this.setFieldValByName("updateTime",LocalDateTime.now(),metaObject);
//        this.setFieldValByName("version",1L,metaObject);
//        this.setFieldValByName("deleted",0,metaObject);this.strictInsertFill(metaObject,"createTime", LocalDateTime.class,LocalDateTime.now());this.strictInsertFill(metaObject,"updateTime",LocalDateTime.class,LocalDateTime.now());this.strictInsertFill(metaObject,"version",Integer.class,1);this.strictInsertFill(metaObject,"deleted",Integer.class,0);}//更新时的填充策略@Overridepublic void updateFill(MetaObject metaObject) {log.info("数据库表更新,开始更新系统字段...");this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());}
}

更新实体类

package com.zsc.pojo;import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import java.time.LocalDateTime;
import java.util.Date;@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("user")
public class User {/*** (1)主键策略* 关于mybatis-plus,简称MP* MP开启了驼峰转下划线,操作的sql语句,会依据属性名转换为下划线的列名称,如,会将userId转换为user_id  会将userIdS转换为user_id_s** @TableId(type = IdType.AUTO)* 关于IdType重点* public enum IdType {* AUTO(0),//数据库自增 依赖数据库* NONE(1),// 表示该类型未设置主键类型 (如果没有主键策略)默认根据雪花算法生成* INPUT(2),//用户输入ID(该类型可以通过自己注册填充插件进行填充)*   //下面这三种类型,只有当插入对象id为空时 才会自动填充。* ID_WORKER(3),//全局唯一(idWorker)数值类型* UUID(4),//全局唯一(UUID)* ID_WORKER_STR(5);//全局唯一(idWorker的字符串表示)* }* <p>* 例如:* 在实体类中 ID属性加注解* @TableId(type = IdType.AUTO) 主键自增 数据库中需要设置主键自增* private Long id;* @TableId(type = IdType.NONE) 默认 跟随全局策略走* private Long id;* @TableId(type = IdType.UUID) UUID类型主键* private Long id;* @TableId(type = IdType.ID_WORKER) 数值类型  数据库中也必须是数值类型 否则会报错* private Long id;* @TableId(type = IdType.ID_WORKER_STR) 字符串类型   数据库也要保证一样字符类型* private Long id;* @TableId(type = IdType.INPUT) 用户自定义了  数据类型和数据库保持一致就行* private Long id;*///如果数据库对应id是自增长的,这里对应id也要设值为自增长,注意,同时得保证数据库对应的id也是自增长的,不然会报错@TableId(type = IdType.AUTO)private Long id;//@TableField(value = "name")//字段名与数据库字段名不一致时采用该形式进行映射private String name;private Integer age;private String email;private String password;private String phone;@TableField(fill = FieldFill.INSERT)//插入数据时自动更新时间private LocalDateTime createTime;@TableField(fill = FieldFill.INSERT_UPDATE)//插入和更新操作时自动更新时间private LocalDateTime updateTime;@TableField(fill = FieldFill.INSERT)//插入数据时自动更新时间private Integer version;@TableField(fill = FieldFill.INSERT)//插入数据时自动更新时间private Integer deleted;
}

测试

    @Testvoid find(){User user = new User();user.setName("张三");user.setAge(19);user.setEmail("123@qq.com");int insert = userMapper.insert(user);log.info("insert={}",insert);}

五、乐观锁

当要更新一条记录的时候,希望这条记录没有被别人更新,主要用于高并发的情况,乐观锁实现方式:

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

创建mybatis plus配置类MyBatisPlusConfig

@MapperScan("com.zsc.mapper")//可以将主启动类的扫描mapper放到这里
@EnableTransactionManagement//管理事务
@Configuration//表明这是一个配置类
public class MyBatisPlusConfig {//注册乐观锁插件@Beanpublic OptimisticLockerInterceptor optimisticLockerInterceptor(){return new OptimisticLockerInterceptor();}
}

更新实体类

package com.zsc.pojo;import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import java.time.LocalDateTime;
import java.util.Date;@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("user")
public class User {/*** (1)主键策略* 关于mybatis-plus,简称MP* MP开启了驼峰转下划线,操作的sql语句,会依据属性名转换为下划线的列名称,如,会将userId转换为user_id  会将userIdS转换为user_id_s** @TableId(type = IdType.AUTO)* 关于IdType重点* public enum IdType {* AUTO(0),//数据库自增 依赖数据库* NONE(1),// 表示该类型未设置主键类型 (如果没有主键策略)默认根据雪花算法生成* INPUT(2),//用户输入ID(该类型可以通过自己注册填充插件进行填充)*   //下面这三种类型,只有当插入对象id为空时 才会自动填充。* ID_WORKER(3),//全局唯一(idWorker)数值类型* UUID(4),//全局唯一(UUID)* ID_WORKER_STR(5);//全局唯一(idWorker的字符串表示)* }* <p>* 例如:* 在实体类中 ID属性加注解* @TableId(type = IdType.AUTO) 主键自增 数据库中需要设置主键自增* private Long id;* @TableId(type = IdType.NONE) 默认 跟随全局策略走* private Long id;* @TableId(type = IdType.UUID) UUID类型主键* private Long id;* @TableId(type = IdType.ID_WORKER) 数值类型  数据库中也必须是数值类型 否则会报错* private Long id;* @TableId(type = IdType.ID_WORKER_STR) 字符串类型   数据库也要保证一样字符类型* private Long id;* @TableId(type = IdType.INPUT) 用户自定义了  数据类型和数据库保持一致就行* private Long id;*///如果数据库对应id是自增长的,这里对应id也要设值为自增长,注意,同时得保证数据库对应的id也是自增长的,不然会报错@TableId(type = IdType.AUTO)private Long id;//@TableField(value = "name")//字段名与数据库字段名不一致时采用该形式进行映射private String name;private Integer age;private String email;private String password;private String phone;@TableField(fill = FieldFill.INSERT)//插入数据时自动更新时间private LocalDateTime createTime;@TableField(fill = FieldFill.INSERT_UPDATE)//插入和更新操作时自动更新时间private LocalDateTime updateTime;@Version//乐观锁注解@TableField(fill = FieldFill.INSERT)//插入数据时自动更新时间private Integer version;@TableField(fill = FieldFill.INSERT)//插入数据时自动更新时间private Integer deleted;
}

测试1

    /*** 测试乐观锁成功案例* 由于是单线程的情况,所以更新操作肯定成功*/@Testpublic void optimisticLockerInterceptor1Test(){//1、查询用户User user = userMapper.selectById(1L);//2、修改用户信息user.setAge(10);//3、执行更新操作userMapper.updateById(user);}

测试2

    /*** 测试乐观锁失败案例* 多线程操作*/@Testpublic void optimisticLockerInterceptor2Test(){//线程1User user1 = userMapper.selectById(1L);user1.setAge(11);//线程2:模拟另外一个线程执行了插队操作User user2 = userMapper.selectById(1L);user2.setAge(12);userMapper.updateById(user2);//自旋锁多次尝试提交,提交失败userMapper.updateById(user1);//如果没有乐观锁就会覆盖插队线程的值}

六、分页查询

分页查询需要在配置类中添加分页查询相关配置


@MapperScan("com.zsc.mapper")//可以将主启动类的扫描mapper放到这里
@EnableTransactionManagement//管理事务
@Configuration//表明这是一个配置类
public class MyBatisPlusConfig {//注册乐观锁插件@Beanpublic OptimisticLockerInterceptor optimisticLockerInterceptor(){return new OptimisticLockerInterceptor();}//分页查询插件配置@Beanpublic PaginationInterceptor paginationInterceptor() {PaginationInterceptor paginationInterceptor = new PaginationInterceptor();// 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求  默认false// paginationInterceptor.setOverflow(false);// 设置最大单页限制数量,默认 500 条,-1 不受限制// paginationInterceptor.setLimit(500);// 开启 count 的 join 优化,只针对部分 left joinreturn paginationInterceptor;}
}

测试

        /*** 构造参数:查询第一页,每页条数为5条*/Page page = new Page(1,5);//查询的条件用实体类接收,user什么都没设置则默认查询所有User queryUser = new User();queryUser.setName("灰太狼");//TODO 如果属性不一致,需要做特殊处理QueryWrapper queryWrapper = new QueryWrapper(queryUser);//查询IPage<User> userDOIPage = userMapper.selectPage(page, queryWrapper);//转成json输出,需要引入hutool工具类依赖String jsonString = JSONUtil.parse(userDOIPage).toJSONString(1);log.info("查询的结果 = {}",jsonString);}

七、逻辑删除

所谓逻辑删除就必须要说到物理删除和逻辑删除两者的区别:
物理删除:从数据库中直接删除
逻辑删除:在数据库中没有被移除,而是通过一个变量让其失效,不再被查询到,deleted = 0 => deleted = 1

配置application.properties配置文件

mybatis-plus:global-config:db-config:logic-delete-field: flag  # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2)logic-delete-value: 1 # 逻辑已删除值(默认为 1)logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)

实体类字段上加上@TableLogic注解

package com.zsc.pojo;import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Date;@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("user")
public class User implements Serializable {/*** (1)主键策略* 关于mybatis-plus,简称MP* MP开启了驼峰转下划线,操作的sql语句,会依据属性名转换为下划线的列名称,如,会将userId转换为user_id  会将userIdS转换为user_id_s** @TableId(type = IdType.AUTO)* 关于IdType重点* public enum IdType {* AUTO(0),//数据库自增 依赖数据库* NONE(1),// 表示该类型未设置主键类型 (如果没有主键策略)默认根据雪花算法生成* INPUT(2),//用户输入ID(该类型可以通过自己注册填充插件进行填充)*   //下面这三种类型,只有当插入对象id为空时 才会自动填充。* ID_WORKER(3),//全局唯一(idWorker)数值类型* UUID(4),//全局唯一(UUID)* ID_WORKER_STR(5);//全局唯一(idWorker的字符串表示)* }* <p>* 例如:* 在实体类中 ID属性加注解* @TableId(type = IdType.AUTO) 主键自增 数据库中需要设置主键自增* private Long id;* @TableId(type = IdType.NONE) 默认 跟随全局策略走* private Long id;* @TableId(type = IdType.UUID) UUID类型主键* private Long id;* @TableId(type = IdType.ID_WORKER) 数值类型  数据库中也必须是数值类型 否则会报错* private Long id;* @TableId(type = IdType.ID_WORKER_STR) 字符串类型   数据库也要保证一样字符类型* private Long id;* @TableId(type = IdType.INPUT) 用户自定义了  数据类型和数据库保持一致就行* private Long id;*///如果数据库对应id是自增长的,这里对应id也要设值为自增长,注意,同时得保证数据库对应的id也是自增长的,不然会报错@TableId(type = IdType.AUTO)private Long id;//@TableField(value = "name")//字段名与数据库字段名不一致时采用该形式进行映射private String name;private Integer age;private String email;private String password;private String phone;@TableField(fill = FieldFill.INSERT)//插入数据时自动更新时间private LocalDateTime createTime;@TableField(fill = FieldFill.INSERT_UPDATE)//插入和更新操作时自动更新时间private LocalDateTime updateTime;@Version//乐观锁注解@TableField(fill = FieldFill.INSERT)//插入数据时自动更新时间private Integer version;@TableLogic//逻辑删除@TableField(fill = FieldFill.INSERT)//插入数据时自动更新时间private Integer deleted;
}

测试

    /*** 逻辑删除*/@Testvoid logicDeleteTest(){User user = new User();user.setId(11L);int delete = userMapper.deleteById(user);log.info("delete={}",delete);}

1代表删除,0代表未删除

八、条件构造器

条件构造器Wrapper可以用来代替一些复杂的sql语句

下面给出一些常用的案例,具体可以看mybatis plus官网介绍

/**条件构造器查询**///查询name不为空,并且密码不为空,年龄大于18的用户@Testpublic void wrapper1Test(){//查询name不为空,并且邮箱不为空,年龄大于18的用户QueryWrapper<User> wrapper = new QueryWrapper<>();wrapper.isNotNull("name").isNotNull("email").ge("age",20);//大于List<User> users = userMapper.selectList(wrapper);users.forEach(System.out::println);}//查找用户名为喜羊羊的用户,只查询一位@Testpublic void wrapper2Test(){QueryWrapper<User> wrapper = new QueryWrapper<>();wrapper.eq("name","喜羊羊");User user = userMapper.selectOne(wrapper);System.out.println(user);}//查找用户年龄在20-25的用户@Testpublic void wrapper3Test(){QueryWrapper<User> wrapper = new QueryWrapper<>();wrapper.between("age",20,30);//区间Integer count = userMapper.selectCount(wrapper);System.out.println(count);}//模糊查询@Testpublic void wrapper4Test(){QueryWrapper<User> wrapper1 = new QueryWrapper<>();wrapper1.notLike("name","狼");//name中不包含狼的模糊查询QueryWrapper<User> wrapper2 = new QueryWrapper<>();wrapper2.likeRight("name","羊");//模糊查询name,相当于羊%QueryWrapper<User> wrapper3 = new QueryWrapper<>();wrapper3.likeLeft("name","羊");//模糊查询name,相当于%羊List<User> users1 = userMapper.selectList(wrapper1);users1.forEach(System.out::println);List<User> users2 = userMapper.selectList(wrapper2);users2.forEach(System.out::println);List<User> users = userMapper.selectList(wrapper3);users.forEach(System.out::println);}//id在子查询中查出来@Testpublic void wrapper5Test(){QueryWrapper<User> wrapper = new QueryWrapper<>();wrapper.inSql("id","select id from user where id < 3");List<Object> users = userMapper.selectObjs(wrapper);users.forEach(System.out::println);}//通过id进行排序@Testpublic void wrapper6Test(){QueryWrapper<User> wrapper = new QueryWrapper<>();wrapper.orderByDesc("id");List<User> users = userMapper.selectList(wrapper);users.forEach(System.out::println);}

九、代码生成器

pom依赖

<!--lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><!--mybatis-plus--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.4.0</version></dependency><!--mybatis-plus代码生成器--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.4.0</version></dependency><!--mybatis-plus代码生成器默认模板--><dependency><groupId>org.apache.velocity</groupId><artifactId>velocity-engine-core</artifactId><version>2.2</version></dependency>

核心代码如下(根据实际进行修改)

package com.zsc;import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.springframework.boot.test.context.SpringBootTest;import java.util.ArrayList;@SpringBootTest
class MybatisPlusAutogeneratorApplicationTests {/*** 自动生成所有代码*/public static void main(String[] args) {// 需要构建一个 代码自动生成器 对象        AutoGenerator mpg = new AutoGenerator();// 配置策略// 1、全局配置  GlobalConfig gc = new GlobalConfig();String projectPath = System.getProperty("user.dir");//获取当前项目目录gc.setOutputDir(projectPath + "/src/main/java");//输出到该目录,所有的代码将会被生成到这里gc.setAuthor("最强菜鸟");//设置作者gc.setOpen(false);//生成后是否帮你打开生成的文件gc.setFileOverride(false);//是否覆盖当前项目的文件gc.setServiceName("%sService"); // 去Service的I前缀      gc.setIdType(IdType.AUTO);//实体类主键id的生成策略,关于生成策略请看“mybatis-plus教程”的主键生成策略gc.setDateType(DateType.ONLY_DATE);//日期类型gc.setSwagger2(false);//是否自动配置swagger文档mpg.setGlobalConfig(gc);//丢到全局配置,使其生效//2、设置数据源(数据库配置)DataSourceConfig dsc = new DataSourceConfig();dsc.setUrl("jdbc:mysql://localhost:3306/test1?serverTimezone=GMT%2B8");dsc.setDriverName("com.mysql.cj.jdbc.Driver");dsc.setUsername("root");dsc.setPassword("123");dsc.setDbType(DbType.MYSQL);mpg.setDataSource(dsc);//丢到全局配置,使其生效//jdbc:mysql://xxx.xxx.xxx.xxx/xd_love?useUnicode=true&amp;characterEncoding=utf-8//3、包的配置PackageConfig pc = new PackageConfig();
//        pc.setModuleName("jquery");//生成的模块名,之后所有的生成的包均在此模块下pc.setParent("com.zsc");//这样生成的代码均在com.zsc.jquery下pc.setEntity("entity");//实体类放置的包pc.setMapper("mapper");//mapper包(存放javaBean实体对象)pc.setService("service");//service包(业务层)pc.setController("controller");//controller包(表现层)mpg.setPackageInfo(pc);//4、策略配置        StrategyConfig strategy = new StrategyConfig();strategy.setInclude("user"); // 设置要映射的表名,根据数据库表映射生成实体类  strategy.setNaming(NamingStrategy.underline_to_camel);//类的命名规则,下划线转驼峰命名strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库下划线转驼峰命名strategy.setEntityLombokModel(true); // 自动lombok;需要引入lombok依赖strategy.setLogicDeleteFieldName("deleted");//逻辑删除// 自动填充配置        TableFill createTime = new TableFill("create_time", FieldFill.INSERT);//create_time数据表的字段表示时间自动填充TableFill updateTime = new TableFill("update_time", FieldFill.INSERT_UPDATE);//update_time数据表的字段表示时间自动填充ArrayList<TableFill> tableFills = new ArrayList<>();tableFills.add(createTime);tableFills.add(updateTime);strategy.setTableFillList(tableFills);// 乐观锁strategy.setVersionFieldName("version");strategy.setRestControllerStyle(true);strategy.setControllerMappingHyphenStyle(true); // localhost:8080/hello_id_2      mpg.setStrategy(strategy);System.out.println("success");mpg.execute(); //最终执行}}

运行结果

十、注解集合

@TableName

描述:表名注解

属性 类型 必须指定 默认值 描述
value String "" 表名
schema String "" schema
keepGlobalPrefix boolean false 是否保持使用全局的 tablePrefix 的值(如果设置了全局 tablePrefix 且自行设置了 value 的值)
resultMap String "" xml 中 resultMap 的 id
autoResultMap boolean false 是否自动构建 resultMap 并使用(如果设置 resultMap 则不会进行 resultMap 的自动构建并注入)

关于autoResultMap的说明:
mp会自动构建一个ResultMap并注入到mybatis里(一般用不上).下面讲两句: 因为mp底层是mybatis,所以一些mybatis的常识你要知道,mp只是帮你注入了常用crud到mybatis里 注入之前可以说是动态的(根据你entity的字段以及注解变化而变化),但是注入之后是静态的(等于你写在xml的东西) 而对于直接指定typeHandler,mybatis只支持你写在2个地方:
定义在resultMap里,只作用于select查询的返回结果封装
定义在insert和updatesql的#{property}里的property后面(例:#{property,typehandler=xxx.xxx.xxx}),只作用于设置值 而除了这两种直接指定typeHandler,mybatis有一个全局的扫描你自己的typeHandler包的配置,这是根据你的property的类型去找typeHandler并使用.

@TableId

描述:主键注解

属性 类型 必须指定 默认值 描述
value String "" 主键字段名
type Enum IdType.NONE 主键类型

#IdType

描述
AUTO 数据库ID自增
NONE 无状态,该类型为未设置主键类型(注解里等于跟随全局,全局里约等于 INPUT)
INPUT insert前自行set主键值
ASSIGN_ID 分配ID(主键类型为Number(Long和Integer)或String)(since 3.3.0),使用接口IdentifierGenerator的方法nextId(默认实现类为DefaultIdentifierGenerator雪花算法)
ASSIGN_UUID 分配UUID,主键类型为String(since 3.3.0),使用接口IdentifierGenerator的方法nextUUID(默认default方法)
ID_WORKER 分布式全局唯一ID 长整型类型(please use ASSIGN_ID)
UUID 32位UUID字符串(please use ASSIGN_UUID)
ID_WORKER_STR 分布式全局唯一ID 字符串类型(please use ASSIGN_ID)

@TableField

描述:字段注解(非主键)

属性 类型 必须指定 默认值 描述
value String "" 数据库字段名
el String "" 映射为原生 #{ ... } 逻辑,相当于写在 xml 里的 #{ ... } 部分
exist boolean true 是否为数据库表字段
condition String "" 字段 where 实体查询比较条件,有值设置则按设置的值为准,没有则为默认全局的 %s=#{%s},参考
update String "" 字段 update set 部分注入, 例如:update="%s+1":表示更新时会set version=version+1(该属性优先级高于 el 属性)
insertStrategy Enum N DEFAULT 举例:NOT_NULL: insert into table_a(<if test="columnProperty != null">column</if>) values (<if test="columnProperty != null">#{columnProperty}</if>)
updateStrategy Enum N DEFAULT 举例:IGNORED: update table_a set column=#{columnProperty}
whereStrategy Enum N DEFAULT 举例:NOT_EMPTY: where <if test="columnProperty != null and columnProperty!=''">column=#{columnProperty}</if>
fill Enum FieldFill.DEFAULT 字段自动填充策略
select boolean true 是否进行 select 查询
keepGlobalFormat boolean false 是否保持使用全局的 format 进行处理
jdbcType JdbcType JdbcType.UNDEFINED JDBC类型 (该默认值不代表会按照该值生效)
typeHandler Class<? extends TypeHandler> UnknownTypeHandler.class 类型处理器 (该默认值不代表会按照该值生效)
numericScale String "" 指定小数点后保留的位数

关于jdbcTypetypeHandler以及numericScale的说明:
numericScale只生效于 update 的sql. jdbcType和typeHandler如果不配合@TableName#autoResultMap = true一起使用,也只生效于 update 的sql. 对于typeHandler如果你的字段类型和set进去的类型为equals关系,则只需要让你的typeHandler让Mybatis加载到即可,不需要使用注解

#FieldStrategy

描述
IGNORED 忽略判断
NOT_NULL 非NULL判断
NOT_EMPTY 非空判断(只对字符串类型字段,其他类型字段依然为非NULL判断)
DEFAULT 追随全局配置

#FieldFill

描述
DEFAULT 默认不处理
INSERT 插入时填充字段
UPDATE 更新时填充字段
INSERT_UPDATE 插入和更新时填充字段

@Version

描述:乐观锁注解、标记 @Verison 在字段上

@EnumValue

描述:通枚举类注解(注解在枚举字段上)

@TableLogic

描述:表字段逻辑处理注解(逻辑删除)

属性 类型 必须指定 默认值 描述
value String "" 逻辑未删除值
delval String "" 逻辑删除值

@SqlParser

描述:租户注解,支持method上以及mapper接口上

属性 类型 必须指定 默认值 描述
filter boolean false true: 表示过滤SQL解析,即不会进入ISqlParser解析链,否则会进解析链并追加例如tenant_id等条件

@KeySequence

描述:序列主键策略 oracle
属性:value、resultMap

属性 类型 必须指定 默认值 描述
value String "" 序列名
clazz Class Long.class id的类型, 可以指定String.class,这样返回的Sequence值是字符串"1"
属性 类型 必须指定 默认值 描述
filter boolean false true: 表示过滤SQL解析,即不会进入ISqlParser解析链,否则会进解析链并追加例如tenant_id等条件

十一、补充

(1)将字段更新为null

例如将createTime更新为null

        User user = new User();user.setId(1);user.setUsername("zs");user.setPassword("123");user.setCreateTime(null);userMapper.updateById(user);

mybatis plus学习总结相关推荐

  1. Spring+SpringMVC+MyBatis深入学习及搭建(十)——MyBatis逆向工程

    转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/6973266.html 前面讲到:Spring+SpringMVC+MyBatis深入学习及搭建(九)--My ...

  2. java学mybatis还用学jdbc吗,mybatis系统学习(二)——使用基础mybatis代替原始jdbc

    mybatis系统学习(二)--使用基础mybatis代替原始jdbc 前言 这一篇笔记的内容应当是建立在上一篇的基础之上,不论是使用的数据表,还是对应的实体类,都在上一篇有过说明. 有兴趣的或者对相 ...

  3. Spring+SpringMVC+MyBatis深入学习及搭建(十一)——SpringMVC架构

    转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/6985816.html 前面讲到:Spring+SpringMVC+MyBatis深入学习及搭建(十)--My ...

  4. Spring+SpringMVC+MyBatis深入学习及搭建(十七)——SpringMVC拦截器

    转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/7098753.html 前面讲到:Spring+SpringMVC+MyBatis深入学习及搭建(十六)--S ...

  5. Spring+SpringMVC+MyBatis深入学习及搭建(十四)——SpringMVC和MyBatis整合

    转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/7010363.html 前面讲到:Spring+SpringMVC+MyBatis深入学习及搭建(十三)--S ...

  6. mybatis框架--学习笔记(下)

    上篇:mybatis框架--学习笔记(上):https://blog.csdn.net/a745233700/article/details/81034021 8.高级映射: (1)一对一查询: ①使 ...

  7. mybatis框架--学习笔记(上)

    使用JDBC操作数据库的问题总结: (1)数据库连接,使用时创建,不使用时立即释放,对数据库进行频繁连接开启和关闭,造成数据库资源浪费,影响数据库性能. 设想:使用数据库连接池管理数据库连接. (2) ...

  8. Spring+SpringMVC+MyBatis深入学习及搭建(二)——MyBatis原始Dao开发和mapper代理开发

    前面有写到Spring+SpringMVC+MyBatis深入学习及搭建(一)--MyBatis的基础知识.MybatisFirst中存在大量重复的代码.这次简化下代码: 使用MyBatis开发Dao ...

  9. mybatis自己学习的一些总结

    以前一直在使用spring的JDBCTEMPLATE和hibernate做项目:两个都还不错,spring的jdbctemplate用起来比较麻烦,虽然很简单.而hibernate呢,用起来很好用,很 ...

  10. [Spring+SpringMVC+Mybatis]框架学习笔记(四):Spring实现AOP

    上一章:[Spring+SpringMVC+Mybatis]框架学习笔记(三):Spring实现JDBC 下一章:[Spring+SpringMVC+Mybatis]框架学习笔记(五):SpringA ...

最新文章

  1. 为啥不能用uuid做MySQL的主键?
  2. python画板颜色_教你在python中用不同的方式画不同颜色的画布
  3. DOS下查看局域网的ip使用情况,以及ip对应的主机名
  4. Openlayers中点击地图获取坐标并输出
  5. PHP连接MSSQL
  6. UNIX环境高级编程——Linux终端设备详解
  7. 【完整可运行源码+GIF动画演示】十大经典排序算法系列——冒泡排序、选择排序、插入排序、希尔排序、归并排序、快速排序、堆排序、计数排序、桶排序、基数排序
  8. 针对“云计算”服务安全思路的改进-花瓶模型V4.0
  9. magento模板中XML与phtml关系
  10. 干点大事!“覆盖25万人的AI资源对接平台”发布,找人、找技术不再难!
  11. 浙大PAT乙级练习1001
  12. 计算机二级知识普及挑战赛答案,全国计算机二级试题库
  13. tfidf处理代码_tfidf代码简单实现
  14. 在简历中使用STAR法则
  15. Streaming Telemetry翻译学习
  16. XCode使用googletest(包括googlemock)
  17. Hazel游戏引擎(005)入口点
  18. 双硬盘(固态+机械)装双系统(win10+Ubuntu14.04)
  19. 【亲测有效】解决PPT里多个图片无法使用组合功能
  20. 体重计c语言程序,利用MSP430F149和HX711模块制作体重秤?

热门文章

  1. 机器人庄园作文_以创新为话题的作文6篇
  2. python 几何计算_计算几何python
  3. 打开ie看book!2007电子杂志(样本、目录、画册、商刊)行业国际标准!
  4. Restore 和 Recovery 的区别
  5. python123csv格式清洗与转换_干净的数据 数据清洗入门与实践
  6. 1053 习题4-9-1 判断正整数位数
  7. 那些被忽略的琐碎和点滴,才是浸透在生活中最明亮的勇气
  8. c语言conflicting types,gcc编译C程序出现”error conflicting types for function”编译错误的分析解决...
  9. 彻底关闭Windows10_21h1任务栏里的资讯和兴趣广告
  10. Windows环境使用CLion进行Android NDK开发配置