1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > 【精简版】MyBatis-Plus学习笔记

【精简版】MyBatis-Plus学习笔记

时间:2018-11-04 00:11:53

相关推荐

【精简版】MyBatis-Plus学习笔记

文章目录

1、前言2、什么是MyBatis-Plus3、MyBatis-Plus快速入门3.1 准备工作3.2 操作流程3.2.1 根据user表创建实体类3.2.2 创建Mapper接口3.2.3 进行测试4、MyBatis-Plus 常用注解4.1 @TableName4.2 @TableId4.3 @TableField4.4 @Version4.5 @EnumValue4.6 @TableLogic5、MyBatis-Plus 常用CRUD方法5.1 查询5.2 添加5.3 删除5.4 修改6、自定义SQL(多表关联查询)7、MyBatis-Plus代码生成器

1、前言

该技术博客中内容,是关于B站楠哥教程的笔记总结,希望能为大家带来帮助,参考链接如下:

楠哥MyBatis-Plus视频链接

MyBatis-Plus官方文档

2、什么是MyBatis-Plus

它是国产的开源框架,中国人设计的,基于Mybatis。可以理解为在Mybatis框架的基础上进行二次封装。使得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 操作智能分析阻断,也可自定义拦截规则,预防误操作

3、MyBatis-Plus快速入门

3.1 准备工作

本次的Mybatis-Plus快速入门,我们使用SpringBoot + Mybatis-Plus方式,所以第一步操作我们需要创建一个SpringBoot项目,选中的依赖如下:

然后我们需要手动导入MyBatis-Plus依赖:

<!--MyBatis-Plus--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.3.1.tmp</version></dependency>

修改application.yml文件:

spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8username: rootpassword: root# 打印日志信息mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

创建数据库mybatis,添加一张user表:

CREATE TABLE `user` (`id` bigint(100) NOT NULL AUTO_INCREMENT,`name` varchar(10) DEFAULT NULL,`age` int(10) DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8

3.2 操作流程

3.2.1 根据user表创建实体类

package com.xu.mybatisplus.entity;import lombok.Data;@Datapublic class User {private Long id;private String name;private Integer age;}

3.2.2 创建Mapper接口

package com.xu.mybatisplus.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;import com.xu.mybatisplus.entity.User;public interface UserMapper extends BaseMapper<User> {//BaseMapper接口中定义了许多操作数据(CRUD)的方法,我们可以直接调用//该接口的实现类是动态生成的。只要程序运行就会动态生成对应的实现类对象【反射机制】}

3.2.3 进行测试

package com.xu.mybatisplus.mapper;import com.xu.mybatisplus.entity.User;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import java.util.List;@SpringBootTest //启动Spring容器,可以获取到容器中的beanclass UserMapperTest {@Autowired//依赖注入之前需要在启动类上进行包扫描操作://@MapperScan("com.xu.mybatisplus.mapper"):将mapper接口的bean扫描到ioc容器中private UserMapper mapper;@Testpublic void test() {//查询user表中所有数据List<User> users = mapper.selectList(null);for (User user : users) {System.out.println(user);}}}

控制台结果:

User(id=1, name=张三, age=20)

User(id=2, name=李四, age=21)

User(id=3, name=王五, age=22)

4、MyBatis-Plus 常用注解

4.1 @TableName

作用:映射数据库中的表名

思考一个问题,我们使用Mybatis-Plus框架的过程中,程序如何知道我们想要查找哪张表的数据呢?其实是通过类名查找的,框架会自动查找实体类对应的表。

那么当我们的实体类名和表名不一致时,再次运行程序一定会报错。这时候我们就可以使用@TableName注解进行映射,代码如下:

package com.xu.mybatisplus.entity;import com.baomidou.mybatisplus.annotation.TableName;import lombok.Data;@Data@TableName("user") //参数为表名public class Account {private Long id;private String name;private Integer age;}

4.2 @TableId

作用:

value:映射主键字段type:设置主键类型(主键生成策略)

AUTO:主键自增,开发者无需赋值

NONE(默认):设置主键,通过雪花算法实现

INPUT:主键需要开发者手动赋值,如果没有手动赋值,则通过自增方式赋值

ASSIGN_ID:主键类型为Long、Integer、String,通过雪花算法自动赋值

ASSIGN_UUID:主键的数据类型为String,自动生成UUID进行赋值

package com.xu.mybatisplus.entity;import com.baomidou.mybatisplus.annotation.IdType;import com.baomidou.mybatisplus.annotation.TableField;import com.baomidou.mybatisplus.annotation.TableId;import lombok.Data;@Datapublic class User {//@TableId(type = IdType.ASSIGN_ID)//@TableId(type = IdType.AUTO)//@TableId(type = IdType.INPUT)//@TableId(type = IdType.ASSIGN_UUID)private Long id;private String name;private Integer age;}

4.3 @TableField

作用:

value:映射非主键字段exist:表示该字段是否为数据库字段。如果实体类中的成员变量在数据库中没有对应的字段,则可以使用exist设置为falseselect:表示是否查询该字段,设置为false就不会查询fill:表示是否自动填充,将对象存入数据库的时候,由MP自动给某些字段赋值,例如:create_time,update_time

给表添加两个字段:create_time,update_time

给实体类添加两个成员变量

package com.xu.mybatisplus.entity;import com.baomidou.mybatisplus.annotation.FieldFill;import com.baomidou.mybatisplus.annotation.TableField;import com.baomidou.mybatisplus.annotation.TableId;import lombok.Data;import java.util.Date;@Datapublic class User {@TableIdprivate Long id;@TableField(value = "name", select = false)private String title;private Integer age;@TableField(exist = false)private String gender;@TableField(fill = FieldFill.INSERT)private Date createTime;@TableField(fill = FieldFill.INSERT_UPDATE)private Date updateTime;}

创建自动填充处理器

package com.xu.mybatisplus.handler;import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;import org.apache.ibatis.reflection.MetaObject;import org.ponent;import java.util.Date;@Componentpublic class MyMetaObjectHandler implements MetaObjectHandler {@Overridepublic void insertFill(MetaObject metaObject) {this.setFieldValByName("createTime", new Date(), metaObject);this.setFieldValByName("updateTime", new Date(), metaObject);}@Overridepublic void updateFill(MetaObject metaObject) {this.setFieldValByName("updateTime", new Date(), metaObject);}}

4.4 @Version

作用:标记乐观锁,通过version字段来保证数据的安全性,当修改数据时,会把version作为条件,当条件成立时才会修改成功

首先给user表添加字段version,默认值为1给实体类添加成员变量version,并添加@Version

package com.xu.mybatisplus.entity;import com.baomidou.mybatisplus.annotation.FieldFill;import com.baomidou.mybatisplus.annotation.TableField;import com.baomidou.mybatisplus.annotation.TableId;import com.baomidou.mybatisplus.annotation.Version;import lombok.Data;import java.util.Date;@Datapublic class User {@TableIdprivate Long id;@TableField(value = "name", select = false)private String title;private Integer age;@TableField(exist = false)private String gender;@TableField(fill = FieldFill.INSERT)private Date createTime;@TableField(fill = FieldFill.INSERT_UPDATE)private Date updateTime;@Versionprivate Integer version;}

注册配置类

package com.xu.mybatisplus.config;import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class MyBatisPlusConfig {@Bean //这里有个坑:可能依赖版本号的问题,导致获取不到OptimisticLockerInterceptor public OptimisticLockerInterceptor optimisticLockerInnerInterceptor() {return new OptimisticLockerInterceptor();}}

4.5 @EnumValue

作用:通用枚举类注解,将数据库字段映射成实体类的枚举类型成员变量

给user表添加新的字段status,默认值为0或1

创建枚举类StatusEnum

package com.xu.mybatisplus.enums;import com.baomidou.mybatisplus.annotation.EnumValue;public enum StatusEnum {WORK(1, "上班"),REST(0, "休息");@EnumValue //将code与表中的值进行映射private Integer code;private String msg;StatusEnum(Integer code, String msg) {this.code = code;this.msg = msg;}}

给实体类添加属性

package com.xu.mybatisplus.entity;import com.baomidou.mybatisplus.annotation.FieldFill;import com.baomidou.mybatisplus.annotation.TableField;import com.baomidou.mybatisplus.annotation.TableId;import com.baomidou.mybatisplus.annotation.Version;import com.xu.mybatisplus.enums.StatusEnum;import lombok.Data;import java.util.Date;@Datapublic class User {@TableIdprivate Long id;@TableField(value = "name", select = false)private String title;private Integer age;@TableField(exist = false)private String gender;@TableField(fill = FieldFill.INSERT)private Date createTime;@TableField(fill = FieldFill.INSERT_UPDATE)private Date updateTime;@Versionprivate Integer version;private StatusEnum status;}

application.yml中添加配置

mybatis-plus:type-enums-package:com.xu.mybatisplus.enums

4.6 @TableLogic

作用:映射逻辑删除,并不会永久删除数据

user表中添加deleted字段,默认值为0

实体类添加注解

package com.xu.mybatisplus.entity;import com.baomidou.mybatisplus.annotation.*;import com.xu.mybatisplus.enums.StatusEnum;import lombok.Data;import java.util.Date;@Datapublic class User {@TableIdprivate Long id;@TableField(value = "name", select = false)private String title;private Integer age;@TableField(exist = false)private String gender;@TableField(fill = FieldFill.INSERT)private Date createTime;@TableField(fill = FieldFill.INSERT_UPDATE)private Date updateTime;@Versionprivate Integer version;private StatusEnum status;@TableLogic //可能因为依赖版本号的问题,导致该注解失效private Integer deleted;}

application.yml中添加配置

mybatis-plus:global-config:db-config:logic-not-delete-value: 0logic-delete-value: 1

5、MyBatis-Plus 常用CRUD方法

5.1 查询

@Testpublic void select() {//1.参数传null,不加任何条件全部查询mapper.selectList(null);//2.参数传QueryWrapper,调用eq():查询条件为name = 小红QueryWrapper wrapper = new QueryWrapper();wrapper.eq("name", "小红");mapper.selectList(wrapper);//3.参数传QueryWrapper,调用allEq():多条件查询为name = 小红 and age = 3QueryWrapper wrapper1 = new QueryWrapper();HashMap<String, Object> map = new HashMap<>();map.put("name", "小红");map.put("age", 3);wrapper1.allEq(map);mapper.selectList(wrapper1);//4.参数传QueryWrapper,调用lt():查询条件为age < 2QueryWrapper wrapper2 = new QueryWrapper();wrapper2.lt("age", 2);mapper.selectList(wrapper2);//5.参数传QueryWrapper,调用ne():查询条件为age != 小红QueryWrapper wrapper3 = new QueryWrapper();wrapper3.ne("name", "小红");mapper.selectList(wrapper3);//6.参数传QueryWrapper,调用ge():查询条件为age >= 2QueryWrapper wrapper4 = new QueryWrapper();wrapper4.ge("age", 2);mapper.selectList(wrapper4);//7.参数传QueryWrapper,调用like():模糊查询条件为name like %小%QueryWrapper wrapper5 = new QueryWrapper();wrapper5.like("name", "小");mapper.selectList(wrapper5);//8.参数传QueryWrapper,调用likeLeft():模糊查询条件为name like %小QueryWrapper wrapper6 = new QueryWrapper();wrapper6.likeLeft("name", "小");mapper.selectList(wrapper6);//9.参数传QueryWrapper,调用likeRight():模糊查询条件为name like 小%QueryWrapper wrapper7 = new QueryWrapper();wrapper7.likeRight("name", "小");mapper.selectList(wrapper7);//10.参数传QueryWrapper,调用inSql():查询条件为//id in (select id from user where id < 10)//and age in (select age from user where age > 3)QueryWrapper wrapper8 = new QueryWrapper();wrapper8.inSql("id", "select id from user where id < 10");wrapper8.inSql("age", "select age from user where age > 3");mapper.selectList(wrapper8);//11.参数传QueryWrapper,调用orderAsc():查询条件为order by age ascQueryWrapper wrapper9 = new QueryWrapper();wrapper9.orderByAsc("age");mapper.selectList(wrapper9);//12.参数传QueryWrapper,调用orderDesc():查询条件为order by age descQueryWrapper wrapper10 = new QueryWrapper();wrapper10.orderByDesc("age");mapper.selectList(wrapper10);//13.参数传QueryWrapper,调用orderAsc() + having()//查询条件为having id > 8 order by age ascQueryWrapper wrapper11 = new QueryWrapper();wrapper11.orderByAsc("age");wrapper11.having("id > 8");mapper.selectList(wrapper11);}

@Testpublic void select() {//1.selectById():查询id为7mapper.selectById(7);//2.selectBatchIds():查询id为7,8,9mapper.selectBatchIds(Arrays.asList(7, 8, 9));//3.selectByMap():查询id为7//Map只能做等值判断,逻辑判断需要使用WrapperHashMap<String, Object> map = new HashMap<>();map.put("id", 7);mapper.selectByMap(map);//4.selectCount():查询id > 1QueryWrapper wrapper = new QueryWrapper();wrapper.gt("id", 1);mapper.selectCount(wrapper);//5.selectMaps():将查询的结果集封装到Map中QueryWrapper wrapper1 = new QueryWrapper();wrapper1.gt("id", 1);mapper.selectMaps(wrapper1);//6.selectPage():分页查询,需要在MyBatisPlusConfig中添加如下代码:/*@Beanpublic PaginationInterceptor paginationInterceptor() {return new PaginationInterceptor();}*///第一个参数为页数,第二个参数为每页记录数Page<User> page = new Page<>(1, 2);//不传Wrapper说明没有条件mapper.selectPage(page, null);//7.selectMapsPage():分页查询,查询结果封装为Map集合Page<Map<String, Object>> page1 = new Page<>(1, 2);mapper.selectMapsPage(page1, null);//8.selectObjs():查询所有id值mapper.selectObjs(null);//9.selectOne():查询一条数据QueryWrapper wrapper2 = new QueryWrapper();wrapper2.eq("id", 7);mapper.selectOne(wrapper2);}

5.2 添加

@Testpublic void insert() {User user = new User();user.setTitle("徐志斌");user.setAge(22);mapper.insert(user);}

5.3 删除

@Testpublic void delete() {//1.deleteById():通过id删除mapper.deleteById(2);//2.deleteBatchIds():通过一组id删除mapper.deleteBatchIds(Arrays.asList(7, 8));//3.delete():根据条件删除QueryWrapper wrapper = new QueryWrapper();wrapper.eq("age", 14);mapper.delete(wrapper);//4.deleteByMap():将条件封装到Map中进行删除HashMap<String, Object> map = new HashMap<>();map.put("id", 10);mapper.deleteByMap(map);}

5.4 修改

@Testpublic void update() {//1.updateById():通过id修改数据User user = mapper.selectById(1);user.setTitle("一号");mapper.updateById(user);//2.update():根据条件修改数据User user1 = mapper.selectById(1);user1.setTitle("小红");QueryWrapper wrapper = new QueryWrapper();wrapper.eq("id", 1);mapper.update(user1, wrapper);}

6、自定义SQL(多表关联查询)

user表:

product表:

创建实体类

package com.xu.mybatisplus.entity;import lombok.Data;@Data//多表关联查询得到结果集映射到本类中public class ProductVO {private Integer category;private Integer count;private String description;private Integer userId;private String userName;}

编写UserMapper接口,自定义SQL语句:

package com.xu.mybatisplus.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;import com.xu.mybatisplus.entity.ProductVO;import com.xu.mybatisplus.entity.User;import org.apache.ibatis.annotations.Select;import java.util.List;public interface UserMapper extends BaseMapper<User> {@Select("select p.*,u.name as userName from product p,user u where p.user_id = u.id and u.id = #{id}")List<ProductVO> productList(Integer id);}

进行测试

@Testpublic void product() {List<ProductVO> lists = mapper.productList(7);for (ProductVO vo : lists) {System.out.println(vo);}}

7、MyBatis-Plus代码生成器

作用:根据数据库中的表自动生成实体类、mapper接口、service层代码、controller层代码,就是这么强大!

导入MyBatis-Plus-Generator依赖

<!--MyBatis-Plus-Generator--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.3.1.tmp</version></dependency><!--velocity--><dependency><groupId>org.apache.velocity</groupId><artifactId>velocity</artifactId><version>1.7</version></dependency>

启动类代码如下

package com.xu.mybatisplus;import com.baomidou.mybatisplus.annotation.DbType;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.rules.NamingStrategy;public class Main {public static void main(String[] args) {//创建generator对象AutoGenerator autoGenerator = new AutoGenerator();//创建数据源对象DataSourceConfig dataSourceConfig = new DataSourceConfig();dataSourceConfig.setDbType(DbType.MYSQL);dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8");dataSourceConfig.setUsername("root");dataSourceConfig.setPassword("root");dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");autoGenerator.setDataSource(dataSourceConfig);//全局配置GlobalConfig globalConfig = new GlobalConfig();globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java");globalConfig.setOpen(false);globalConfig.setAuthor("Coder Xu");globalConfig.setServiceName("%sService");autoGenerator.setGlobalConfig(globalConfig);//包信息PackageConfig packageConfig = new PackageConfig();packageConfig.setParent("com.xu.mybatisplus");packageConfig.setModuleName("generator");packageConfig.setController("controller");packageConfig.setService("service");packageConfig.setServiceImpl("service.impl");packageConfig.setMapper("mapper");packageConfig.setEntity("entity");autoGenerator.setPackageInfo(packageConfig);//配置策略StrategyConfig strategyConfig = new StrategyConfig();//生成器只针对user表,不作用其他表strategyConfig.setInclude("user"); strategyConfig.setEntityLombokModel(true);strategyConfig.setNaming(NamingStrategy.underline_to_camel);strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);autoGenerator.setStrategy(strategyConfig);//启动生成器autoGenerator.execute();}}

效果如下,非常的便利:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。