MyBatis-Plus之详细使用总结

  • 一、MyBatis-Plus
    • MyBatis-Plus简介
    • MyBatis-Plus框架结构
    • MyBatis-Plus特性
  • 二、MyBatis-Plus快速入门
    • 1.建库建表
    • 2.添加依赖
    • 3.配置
    • 4.编码
    • 5.修改启动类
    • 6.测试
  • 三、通用CRUD
  • 四、常用注解
  • 五、自动填充
    • 添加自动填充注解
    • 实现元对象处理器接口
  • 六、对乐观锁的支持
    • 悲观锁与乐观锁
    • 配置乐观锁拦截器
    • 添加version字段
    • 测试
  • 七、逻辑删除
    • 添加deleted字段
    • 使用@TableLogic注解
    • 进行配置
    • 测试
  • 八、条件构造器
    • 比较操作
    • 模糊查询
    • 排序
    • 逻辑查询
    • 分页插件
      • selectPage分页
      • selectMapsPage分页
  • 九、Mybatis-Plus的Service封装
    • 创建业务层接口
    • 创建业务层实现类
    • 方法预览
    • 测试
  • 十、代码生成器
    • 引入依赖
    • 示例代码
    • 示例效果
  • 十一、MybatisX快速开发插件
    • XML跳转
    • 生成代码
    • 重置模板
    • JPA提示
  • 十二、使用示例大全

一、MyBatis-Plus

MyBatis-Plus简介

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

官网

https://mp.baomidou.comhttps://mybatis.plus

MyBatis-Plus框架结构

MyBatis-Plus特性

无侵入:

 只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑

损耗小:

启动即会自动注入基本 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 操作智能分析阻断,也可自定义拦截规则,预防误操作

二、MyBatis-Plus快速入门

1.建库建表

 DROP TABLE IF EXISTS user;CREATE TABLE user(id BIGINT(20) NOT NULL COMMENT '主键ID',name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',age INT(11) NULL DEFAULT NULL COMMENT '年龄',email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',PRIMARY KEY (id));DELETE FROM user;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');

2.添加依赖

<dependencies><!--SpringBoot启动器--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><!--SpringBoot Test启动器--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!--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.3.2</version></dependency><!--Mysql数据库驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency>
</dependencies>

3.配置

spring.datasource.url = jdbc:mysql://192.168.254.110:3306/zd_supplier?useUnicode=true&characterEncoding=UTF-8&useSSL=false
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username = root
spring.datasource.password = 12345678# mybaits
# 设置Mapper接口所对应的XML文件位置,如果在Mapper接口中有自定义方法,需要进行该配置
mybatis.mapper-locations = classpath:mapper/**/*Mapper.xml
# 设置别名包扫描路径,通过该属性可以给包中的类注册别名
mybatis.type-aliases-package = com.xxx.supplier.model
# mybatis详细日志输出
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

在 resources目录下新建一个文件夹mybatis,专门存放mapper配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xxx.supplier.mapper.UserMapper"></mapper>

4.编码

创建User.java

@Data
public class User implements Serializable {private static final long serialVersionUID = 5310646772555238163L;private Long id;private String name;private Integer age;private String email;}

创建UserMapper.java继承BaseMapper接口,数据库基本增删改差基本不需要写了

public interface UserMapper extends BaseMapper<User> {// 对mybatis无侵入,只做增强,不做改变,自定义定义查询方法@Select("select * from user")public List<User> selectAll();}

5.修改启动类

在 Spring Boot 启动类中添加 @MapperScan 注解,设置mapper接口的扫描包:

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

6.测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class SampleTest {@Autowiredprivate UserMapper userMapper;@Testpublic void testSelect() {System.out.println(("----- selectAll method test ------"));List<User> userList = userMapper.selectList(null);Assert.assertEquals(5, userList.size());userList.forEach(System.out::println);}}

三、通用CRUD

public interface BaseMapper<T> {/*** 插入一条记录** @param entity 实体对象*/int insert(T entity);/*** 根据 ID 删除** @param id 主键ID*/int deleteById(Serializable id);/*** 根据 columnMap 条件,删除记录** @param columnMap 表字段 map 对象*/int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);/*** 根据 entity 条件,删除记录** @param wrapper 实体对象封装操作类(可以为 null)*/int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);/*** 删除(根据ID 批量删除)** @param idList 主键ID列表(不能为 null 以及 empty)*/int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);/*** 根据 ID 修改** @param entity 实体对象*/int updateById(@Param(Constants.ENTITY) T entity);/*** 根据 whereEntity 条件,更新记录** @param entity        实体对象 (set 条件值,可以为 null)* @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)*/int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);/*** 根据 ID 查询** @param id 主键ID*/T selectById(Serializable id);/*** 查询(根据ID 批量查询)** @param idList 主键ID列表(不能为 null 以及 empty)*/List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);/*** 查询(根据 columnMap 条件)** @param columnMap 表字段 map 对象*/List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);/*** 根据 entity 条件,查询一条记录** @param queryWrapper 实体对象封装操作类(可以为 null)*/T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);/*** 根据 Wrapper 条件,查询总记录数** @param queryWrapper 实体对象封装操作类(可以为 null)*/Integer 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)*/IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);/*** 根据 Wrapper 条件,查询全部记录(并翻页)** @param page         分页查询条件* @param queryWrapper 实体对象封装操作类*/IPage<Map<String, Object>> selectMapsPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
}

四、常用注解

//指定数据库中表名
@TableName("tb_user")
public class User {}    //指定数据库中主键名
@TableId(type = IdType.AUTO)
private Long id;//指定数据库中字段名
//驼峰命名,则无需注解
@TableField("USER_NAME")
private String userName; //排除表字段,不与数据库表做映射
@TableField(exist = false)
private String phone;//使用static transient修饰字段也同样能忽略字段与数据库表之间的映射
private static field; //使用lombok需手动提供get/set方法
private transient field;  //不能参与序列化

主键生成策略

mybatis-plus主键生成策略 :默认使用全局唯一的数字类型

@Getter
public enum IdType {/*** 数据库ID自增*/AUTO(0),/*** 该类型为未设置主键类型(注解里等于跟随全局,全局里约等于 INPUT)*/NONE(1),/*** 用户输入ID* <p>该类型可以通过自己注册自动填充插件进行填充</p>*/INPUT(2),/* 以下3种类型、只有当插入对象ID 为空,才自动填充。 *//*** 分配ID (主键类型为number或string),* 默认实现类 {@link com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator}(雪花算法)** @since 3.3.0*/ASSIGN_ID(3),/*** 分配UUID (主键类型为 string)* 默认实现类 {@link com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator}(UUID.replace("-",""))*/ASSIGN_UUID(4),/*** 全局唯一ID (idWorker)* @deprecated 3.3.0 please use {@link #ASSIGN_ID}*/@DeprecatedID_WORKER(3),/*** 字符串全局唯一ID (idWorker 的字符串表示)* @deprecated 3.3.0 please use {@link #ASSIGN_ID}*/@DeprecatedID_WORKER_STR(3),/*** 全局唯一ID (UUID)* @deprecated 3.3.0 please use {@link #ASSIGN_UUID}*/@DeprecatedUUID(4);private final int key;IdType(int key) {this.key = key;}
}

设置全局主键生成策略

mybatis-plus:global-config:db-config:id-type: auto

五、自动填充

项目中经常会遇到一些数据,每次都使用相同的方式填充,例如记录的创建时间,更新时间等,恰好可以使用MyBatis Plus的自动填充功能,完成这些字段的赋值工作。

添加自动填充注解

实体上增加字段并添加自动填充注解

 @TableField(fill = FieldFill.INSERT)private Date createTime;@TableField(fill = FieldFill.INSERT_UPDATE)private Date updateTime;

实现元对象处理器接口

实现MetaObjectHandler接口

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {/*** 当MyBatis Plus执行insert操作时执行** @param metaObject*/@Overridepublic void insertFill(MetaObject metaObject) {this.setFieldValByName("createTime", new Date(), metaObject);this.setFieldValByName("updateTime", new Date(), metaObject);}/*** 当MyBatis Plus执行update操作时执行** @param metaObject*/@Overridepublic void updateFill(MetaObject metaObject) {this.setFieldValByName("updateTime", new Date(), metaObject);}
}

六、对乐观锁的支持

悲观锁与乐观锁

数据库自身解决并发两种策略

悲观锁(Pessimistic Lock)

每次获取数据时候都认为别人会修改,所以每次在拿数据的时候都会上锁,这样别人想拿这个数据就会block直到它拿到锁。

传统关系型数据库里用到了很多这种锁机制,比如行锁,表锁等,读锁,写锁等,都是在做操作之前先上锁。

乐观锁(Optimistic Lock)

每次获取数据的时候都认为别人不会修改,所以不会上锁,但是在更新的时候会判断一下在此期间别人有没有更新这个数据,可以使用版本号等机制。

乐观锁适用于多读的应用类型,这样可以提高吞吐量,像数据库如果提供类似于write_condition机制的其实都是提供的乐观锁

配置乐观锁拦截器

配置OptimisticLockerInterceptor类型的Bean

 // 乐观锁的拦截器@Beanpublic OptimisticLockerInterceptor optimisticLockerInterceptor(){return new OptimisticLockerInterceptor();}

添加version字段

数据库表添加version字段,mp使用乐观锁,自动更新version值

//指定数据库中表名
@TableName("tb_user")
public class User {@Versionprivate Integer version;}

测试

@Autowiredprivate UserMapper userMapper;@Testpublic void test() {User user = new User();user.setName("name");user.setAge(20);user.setEmail("123@qq.com");userMapper.insert(user);User selectUser = userMapper.selectById(user.getId());System.out.println("保存User:" + selectUser);selectUser.setAge(30);userMapper.updateById(selectUser);User updateUser1 = userMapper.selectById(selectUser.getId());System.out.println("第一次修改User:" + updateUser1);selectUser.setAge(40);userMapper.updateById(selectUser);User updateUser2 = userMapper.selectById(selectUser.getId());System.out.println("第二次修改User:" + updateUser2);
}

七、逻辑删除

添加deleted字段

数据库表添加deleted字段

ALTERTABLE `user` ADD COLUMN `deleted` boolean DEFAULT false

使用@TableLogic注解

实体类添加deleted字段,并使用@TableLogic注解

@TableLogic
private Integer deleted;

进行配置

mybatis-plus:global-config:db-config:# 默认值logic-delete-value: 1logic-not-delete-value: 0

测试

注意:被删除前,数据的deleted字段的值必须是0,才能被选取出来执行逻辑删除的操作
@Test
public void testLogicDelete() {int result = userMapper.deleteById(1L);system.out.println(result);// 查询操作也会自动添加逻辑删除字段的判断List<User> users = userMapper.selectList(null);users.forEach(System.out::println);}
测试后发现,数据并没有被删除,deleted字段的值由0变成了1

八、条件构造器

针对各种复杂条件的操作,MP专门针对sql条件进行了封装,提供了各种Wrapper接口及其实现类。

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

比较操作

eq :等于 =ne:不等于 <>gt:大于 >ge:大于等于 >=lt:小于 <le:小于等于 <=between:between 值1 AND 值2notBetween:not between 值1 AND 值2in:字段 in (value1, value2, ...)notIn :字段 not in (value1, value2, ...)
@Testpublic  void test() {QueryWrapper<User> queryWrapper=new QueryWrapper<>();//SELECT id,name,age,email FROM user WHERE age >= ? AND name IN (?,?,?)queryWrapper.ge("age",20).in("name", "Jone", "Jack");List<User> list=userMapper.selectList(queryWrapper);for (User user : list) {System.out.println(user);}}

模糊查询

like

like  '%值%'例 : like("name", " 王") ---> name like '%王%'

notLike

not like '%值%'例 : notLike("name", " 王") ---> name not like '%王%'

likeLeft

like  '%值'例 : likeLeft("name", " 王") ---> name like '%王'

likeRight

like '值%'例 : likeRight("name", " 王") ---> name like '王%'
    @Testpublic void test(){QueryWrapper<User> queryWrapper=new QueryWrapper<>();queryWrapper.like("name","王");List<User> list=userMapper.selectList(queryWrapper);for (User user : list) {System.out.println(user);}}

排序

orderBy

排序: ORDER BY 字段, ...例 : orderBy(true, true, "id", "name") ---> order by id ASC,name ASC

orderByAsc

排序: ORDER BY 字段, ... ASC例 : orderByAsc("id", "name") ---> order by id ASC,name ASC

orderByDesc

排序: ORDER BY 字段, ... DESC例 : orderByDesc("id", "name") ---> order by id DESC,name DESC
 @Test
public void test(){QueryWrapper<User> queryWrapper=new QueryWrapper<>();queryWrapper.orderByDesc("age");List<User> list=userMapper.selectList(queryWrapper);for (User user : list) {System.out.println(user);}}

逻辑查询

or

主动调用or 表示紧接着下一个方法不是用and连接,不调用or则默认为使用and连接gt("age", 20).or().eq("name", "jack")  ---> age >20 or name = "jack"

and

例 : and(item-> item.eq("email","123@qq.com").ne("id", 6))  ---> and (email = "123@qq.com" and id <> 6)
    @Testpublic void test() {QueryWrapper<User> queryWrapper = new QueryWrapper<>();//age >20 or name = "jack"queryWrapper.gt("age", 20).or().eq("name", "jack");//and (email = "123@qq.com" and id <> 6)queryWrapper.and(item-> item.eq("email","123@qq.com").ne("id", 6));List<User> list = userMapper.selectList(queryWrapper);for (User user : list) {System.out.println(user);}}

分页插件

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

配置分页插件

@MapperScan("com.xxx.supplier.mapper")
@SpringBootApplication
public class MyApplication {public static void main(String[] args) {SpringApplication.run(MyApplication.class, args);}/*** 分页插件** @return*/@Beanpublic PaginationInterceptor paginationInterceptor() {return new PaginationInterceptor();}
}

selectPage分页

    @Testpublic void test(){QueryWrapper<User>  queryWrapper=new QueryWrapper<>();queryWrapper.gt("age",20);Page<User>  page=new Page<>(1,2);IPage<User> iPage = userMapper.selectPage(page,queryWrapper);System.out.println("数据总条数:" + iPage.getTotal());System.out.println("总页数:" + iPage.getPages());List<User> users = iPage.getRecords();for (User user : users) {System.out.println("user = " + user);}}

selectMapsPage分页

当指定了特定的查询列时,希望分页结果列表只返回被查询的列,而不是很多null值时可以使用selectMapsPage分页

    @Testpublic void testSelectMapsPage() {Page<Map<String, Object>> page = new Page<>(1, 5);Page<Map<String, Object>> pageParam = seataTestMapperl.selectMapsPage(page, null);List<Map<String, Object>> records = pageParam.getRecords();records.forEach(System.out::println);System.out.println(pageParam.getCurrent());System.out.println(pageParam.getPages());System.out.println(pageParam.getSize());System.out.println(pageParam.getTotal());System.out.println(pageParam.hasNext());System.out.println(pageParam.hasPrevious());}

九、Mybatis-Plus的Service封装

在进行业务层开发时,使用Mybatis-Plus提供的Service封装,继承其接口和实现类,使得编码与开发更加便捷高效。

创建业务层接口

创建业务层接口,继承IService:

import com.baomidou.mybatisplus.extension.service.IService;
public interface UserService extends IService<User> {}

创建业务层实现类

创建业务层实现类,继承ServiceImpl

@Service
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {}

方法预览

IService接口与ServiceImpl实现类提供的方法:

测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestUserService {@Autowiredprivate UserService userService;@Testpublic void testInsert() {User user;//saveuser = new User();user.setEmail("1234@qq.com");user.setAge(12);user.setName("小白");userService.save(user);//selectuser = userService.getById(2);System.out.println(user);//updateuser = new User();//条件:根据id更新user.setId(1L);//更新字段user.setAge(20);userService.updateById(user);// delteuserService.removeById(2L);}
}

十、代码生成器

AutoGenerator是MyBatis-Plus的代码生成器,通过 AutoGenerator可以快速生成Entity类、Mapper接口、Mapper XML、Service、Controller 等各个模块的代码,极大的提升开发效率。

引入依赖

 <!--代码生成器--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.4.1</version></dependency><!--模板引擎--><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.31</version></dependency>

示例代码

public class CodeGenerator {/*** <p>* 读取控制台内容* </p>*/public static String scanner(String tip) {Scanner scanner = new Scanner(System.in);StringBuilder help = new StringBuilder();help.append("请输入" + tip + ":");System.out.println(help.toString());if (scanner.hasNext()) {String ipt = scanner.next();if (StringUtils.isNotBlank(ipt)) {return ipt;}}throw new MybatisPlusException("请输入正确的" + tip + "!");}public static void main(String[] args) {// 代码生成器AutoGenerator mpg = new AutoGenerator();// 全局配置GlobalConfig gc = new GlobalConfig();String projectPath = System.getProperty("user.dir");gc.setOutputDir(projectPath + "/src/main/java");gc.setAuthor("jobob");gc.setOpen(false);// gc.setSwagger2(true); 实体属性 Swagger2 注解mpg.setGlobalConfig(gc);// 数据源配置DataSourceConfig dsc = new DataSourceConfig();dsc.setUrl("jdbc:mysql://localhost:3306/demo?useUnicode=true&useSSL=false&characterEncoding=utf8");// dsc.setSchemaName("public");dsc.setDriverName("com.mysql.jdbc.Driver");dsc.setUsername("root");dsc.setPassword("123456");mpg.setDataSource(dsc);// 包配置PackageConfig pc = new PackageConfig();pc.setModuleName(scanner("模块名"));pc.setParent("com.baomidou.ant");mpg.setPackageInfo(pc);// 自定义配置InjectionConfig cfg = new InjectionConfig() {@Overridepublic void initMap() {// to do nothing}};// 如果模板引擎是 freemarkerString templatePath = "/templates/mapper.xml.ftl";// 如果模板引擎是 velocity//String templatePath = "/templates/mapper.xml.vm";// 自定义输出配置List<FileOutConfig> focList = new ArrayList<>();// 自定义配置会被优先输出focList.add(new FileOutConfig(templatePath) {@Overridepublic String outputFile(TableInfo tableInfo) {// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;}});/*cfg.setFileCreate(new IFileCreate() {@Overridepublic boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {// 判断自定义文件夹是否需要创建checkDir("调用默认方法创建的目录,自定义目录用");if (fileType == FileType.MAPPER) {// 已经生成 mapper 文件判断存在,不想重新生成返回 falsereturn !new File(filePath).exists();}// 允许生成模板文件return true;}});*/cfg.setFileOutConfigList(focList);mpg.setCfg(cfg);// 配置模板TemplateConfig templateConfig = new TemplateConfig();// 配置自定义输出模板//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别// templateConfig.setEntity("templates/entity2.java");// templateConfig.setService();// templateConfig.setController();templateConfig.setXml(null);mpg.setTemplate(templateConfig);// 策略配置StrategyConfig strategy = new StrategyConfig();strategy.setNaming(NamingStrategy.underline_to_camel);strategy.setColumnNaming(NamingStrategy.underline_to_camel);//strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");strategy.setEntityLombokModel(true);strategy.setRestControllerStyle(true);// 公共父类// strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");// 写于父类中的公共字段strategy.setSuperEntityColumns("id");strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));strategy.setControllerMappingHyphenStyle(true);strategy.setTablePrefix(pc.getModuleName() + "_");mpg.setStrategy(strategy);mpg.setTemplateEngine(new FreemarkerTemplateEngine());mpg.execute();}
}

示例效果

十一、MybatisX快速开发插件

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

安装方法:打开 IDEA,进入 File -> Settings -> Plugins -> Browse Repositories,输入 mybatisx 搜索并安装。

XML跳转

生成代码

重置模板

JPA提示

十二、使用示例大全

    @Autowiredprivate UserMapper userMapper;/*** 普通查询*/@Testpublic void selectById() {User User = userMapper.selectById(1);System.out.println(User);}/*** 批量查询*/@Testpublic void selectByIds() {List<Long> ids = Arrays.asList(1L, 2L, 3L);List<User> User = userMapper.selectBatchIds(ids);System.out.println(User);}/*** 名字包含Jack并且年龄小于20*/@Testpublic void selectByWrapper() {QueryWrapper<User> queryWrapper = new QueryWrapper<User>();queryWrapper.like("name", "Jack").lt("age", 20);List<User> UserList = userMapper.selectList(queryWrapper);UserList.forEach(System.out::println);}/*** 名字包含Jack并且年龄大于等于20且小于等于30并且email不为空*/@Testpublic void selectByWrapper2() {QueryWrapper<User> queryWrapper = new QueryWrapper<User>();queryWrapper.like("name", "Jack").between("age", 20, 30).isNotNull("email");List<User> UserList = userMapper.selectList(queryWrapper);UserList.forEach(System.out::println);}/*** 名字姓Tom或者年龄大于等于20,按照年龄降序排列,年龄相同按照id生序排列*/@Testpublic void selectByWrapper3() {QueryWrapper<User> queryWrapper = new QueryWrapper<User>();queryWrapper.likeRight("name", "Tom").or().ge("age", 20).orderByDesc("age").orderByAsc("id");List<User> UserList = userMapper.selectList(queryWrapper);UserList.forEach(System.out::println);}/*** 创建日期为2021年05月20日并且直属上级名字为陈姓*/@Testpublic void selectByWrapper4() {QueryWrapper<User> queryWrapper = new QueryWrapper<User>();queryWrapper.apply("date_format(create_time,'%Y-%m-%d')={0}", "2021-05-20").inSql("parent_id", "select id from user where name like '陈%'");List<User> UserList = userMapper.selectList(queryWrapper);UserList.forEach(System.out::println);}/*** 名字为陈姓并且(年龄小于30或邮箱不为空)*/@Testpublic void selectByWrapper5() {QueryWrapper<User> queryWrapper = new QueryWrapper<User>();queryWrapper.likeRight("name", "陈").and(wq -> wq.lt("age", 30)).or().isNotNull("email");List<User> UserList = userMapper.selectList(queryWrapper);UserList.forEach(System.out::println);}/*** 名字为陈姓并且(年龄小于30并且大于20或邮箱不为空)*/@Testpublic void selectByWrapper6() {QueryWrapper<User> queryWrapper = new QueryWrapper<User>();queryWrapper.likeRight("name", "陈").and(wq -> wq.lt("age", 30).gt("age", 20).or().isNotNull("email"));List<User> UserList = userMapper.selectList(queryWrapper);UserList.forEach(System.out::println);}/*** (年龄小于30并且大与20或邮箱不为空)名字为陈姓*/@Testpublic void selectByWrapper7() {QueryWrapper<User> queryWrapper = new QueryWrapper<User>();queryWrapper.nested(wq -> wq.lt("age", 30).gt("age", 20).or().isNotNull("email")).likeRight("name", "陈");List<User> UserList = userMapper.selectList(queryWrapper);UserList.forEach(System.out::println);}/*** 年龄20,30,40*/@Testpublic void selectByWrapper8() {QueryWrapper<User> queryWrapper = new QueryWrapper<User>();queryWrapper.in("age", Arrays.asList(20, 30, 40));List<User> UserList = userMapper.selectList(queryWrapper);UserList.forEach(System.out::println);}/*** 只返回满足条件的其中一条语句即可*/@Testpublic void selectByWrapper9() {QueryWrapper<User> queryWrapper = new QueryWrapper<User>();queryWrapper.in("age", Arrays.asList(20, 30, 40)).last("limit 1");List<User> UserList = userMapper.selectList(queryWrapper);UserList.forEach(System.out::println);}/*** 名字中包含Billie并且年龄小于30(只取id,name)*/@Testpublic void selectByWrapper10() {QueryWrapper<User> queryWrapper = new QueryWrapper<User>();queryWrapper.select("id", "name").like("name", "Billie").lt("age", 30);List<User> UserList = userMapper.selectList(queryWrapper);UserList.forEach(System.out::println);}/*** 名字中包含Billie并且年龄小于30(不取create_time,parent_id两个字段,即不列出全部字段)*/@Testpublic void selectByWrapper11() {QueryWrapper<User> queryWrapper = new QueryWrapper<User>();queryWrapper.like("name", "Billie").lt("age", 30).select(User.class, info -> !info.getColumn().equals("create_time") &&!info.getColumn().equals("parent_id"));List<User> UserList = userMapper.selectList(queryWrapper);UserList.forEach(System.out::println);}/*** 姓名和邮箱不为空*/public void testCondition() {String name = "陈";String email = "";condition(name, email);}private void condition(String name, String email) {QueryWrapper<User> queryWrapper = new QueryWrapper<User>();queryWrapper.like(StringUtils.isNullOrEmpty(name), "name", name).like(StringUtils.isNullOrEmpty(email), "email", email);List<User> UserList = userMapper.selectList(queryWrapper);UserList.forEach(System.out::println);}/*** 实体作为条件构造器方法的参数*/@Testpublic void selectByWrapperEntity() {User whereUser = new User();whereUser.setUserName("Billie");whereUser.setAge(22);QueryWrapper<User> queryWrapper = new QueryWrapper<User>(whereUser);List<User> UserList = userMapper.selectList(queryWrapper);UserList.forEach(System.out::println);}/*** AllEq用法*/@Testpublic void selectByWrapperAllEq() {QueryWrapper<User> queryWrapper = new QueryWrapper<User>();Map<String, Object> params = new HashMap<String, Object>();params.put("name", "Billie");params.put("age", null);queryWrapper.allEq(params);List<User> UserList = userMapper.selectList(queryWrapper);UserList.forEach(System.out::println);}/*** AllEq用法(排除不是条件的字段)*/@Testpublic void selectByWrapperAllEq2() {QueryWrapper<User> queryWrapper = new QueryWrapper<User>();Map<String, Object> params = new HashMap<String, Object>();params.put("name", "Billie");params.put("age", null);queryWrapper.allEq((k, v) -> !k.equals("name"), params);List<User> UserList = userMapper.selectList(queryWrapper);UserList.forEach(System.out::println);}/*** selectMaps*/@Testpublic void selectByWrapperMaps() {QueryWrapper<User> queryWrapper = new QueryWrapper<User>();queryWrapper.like("name", "Tom").lt("age", 30);List<Map<String, Object>> UserList = userMapper.selectMaps(queryWrapper);UserList.forEach(System.out::println);}/*** 按照部门分组,查询每组的平均年龄,最大年龄,最小年龄。并且只取年龄总和小于500的组*/@Testpublic void selectByWrapperMaps2() {QueryWrapper<User> queryWrapper = new QueryWrapper<User>();queryWrapper.select("avg(age) avg_age", "min(min) min_age", "max(age) max_age").groupBy("dept_id").having("sum(age)<{0}", 100);List<Map<String, Object>> UserList = userMapper.selectMaps(queryWrapper);UserList.forEach(System.out::println);}/*** selectObjs*/@Testpublic void selectByWrapperObjs() {QueryWrapper<User> queryWrapper = new QueryWrapper<User>();queryWrapper.select("id", "name").like("name", "Tom").lt("age", 30);List<Object> UserList = userMapper.selectObjs(queryWrapper);UserList.forEach(System.out::println);}/*** selectCount*/@Testpublic void selectByWrapperCount() {QueryWrapper<User> queryWrapper = new QueryWrapper<User>();queryWrapper.like("name", "Tom").lt("age", 30);Integer count = userMapper.selectCount(queryWrapper);System.out.println(count);}/*** selectOne*/@Testpublic void selectByWrapperSelectOne() {QueryWrapper<User> queryWrapper = new QueryWrapper<User>();queryWrapper.like("name", "Tom").lt("age", 30);User user = userMapper.selectOne(queryWrapper);System.out.println(user);}/*** 使用Lambda*/@Testpublic void selectLambda() {// LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();LambdaQueryWrapper<User> lambda = new LambdaQueryWrapper<User>();lambda.like(User::getName, "Jack").lt(User::getAge, 30);List<User> UserList = userMapper.selectList(lambda);UserList.forEach(System.out::println);}/*** 使用Lambda,名字为陈姓(年龄小于30或邮箱不为空)*/@Testpublic void selectLambd2() {LambdaQueryWrapper<User> lambda = new LambdaQueryWrapper<User>();lambda.like(User::getName, "Jack").and(lqw -> lqw.lt(User::getAge, 30).or().isNotNull(User::getEmail));List<User> UserList = userMapper.selectList(lambda);UserList.forEach(System.out::println);}/*** 使用Lambda链式*/@Testpublic void selectLambd3() {List<User> UserList = new LambdaQueryChainWrapper<User>(userMapper).like(User::getName, "Jack").ge(User::getAge, 20).list();UserList.forEach(System.out::println);}

MyBatis-Plus之详细使用总结相关推荐

  1. 手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版)

    手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版) SSM(Spring+SpringMVC+Mybatis),目前较为主流的企业级架构方案.标准的MVC设计模式, ...

  2. Spring Boot整合Mybatis【超详细】

    pring Boot整合Mybatis 配置文件形式 pom.xml 配置数据源 UserMapper.xml UserMapper 配置springboot整合mybatis 在运行类上添加@Map ...

  3. MyBatis框架的详细讲解(优点与缺点)

    文章目录 前言 一.Mybatis是什么? 核心思想 二.ORM Mybatis的基本要素 二.resultMap和resultType的区别: resultMap自动映射区别: 使用@param注解 ...

  4. SpringBoot结合MyBatis 【超详细】

    1.SpringBoot+老杜MyBatis 一.简单回顾一下MyBatis 二.快速入门 ​三.简易插入删除更改 四.查询 ①.按其中一个字段查询 ②.按所有字段进行查询 ​五.详解MyBatis核 ...

  5. 【MyBatis】MyBatis是什么?能干什么?一篇学习MyBatis,知识点详细解释,实例演示

    文章目录 MyBatis 1.简介 1.1 什么是MyBatis? 1.2 如何获得MyBatis? 1.3 持久化? 1.4 持久层? 1.5 为什么需要Mybatis? 2.第一个MyBatis程 ...

  6. SpringMVC+Spring+mybatis项目搭建详细过程

    创建maven-web项目,为了方便的管理jar包.首先在maven中导入所需的包.在pom.xml中加入以下代码:<dependency> <groupId>org.spri ...

  7. mybatis逆向工程generatorConfiguration详细配置

    <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE generatorConfiguratio ...

  8. mybatis 使用in 查询时报错_不会Mybatis?一文教你手写实现Mybatis(超详细),吊打面试官!...

    一.MyBatis核心组件 在开始实现我们的mybatis框架之前我觉得有必要先学习一下[MyBatis核心组件],如下示意图(出自前文),在图中可以了解到更多的细节. 二.MyBatis手写实现 1 ...

  9. 详解手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版)

    转载(https://www.jb51.net/article/130560.htm) SSM(Spring+SpringMVC+Mybatis),目前较为主流的企业级架构方案.标准的MVC设计模式, ...

  10. MyBatis学习总结(18)——MyBatis与Hibernate详细比较

    前言 Hibernate 是非常流行的O/R mapping框架,它出身于sf.net,现在已经成为Jboss的一部分. Mybatis 是另外一种优秀的O/R mapping框架.目前属于apach ...

最新文章

  1. 【EMC】电磁兼容性相关名词解释、基础知识
  2. 波士顿动力机器人齐秀舞姿,这是要成团出道?
  3. PowerDesigner如何将物理模型转为对象模型,将对象模型转生成Java类
  4. Android Kotlin Coroutines ktx扩展
  5. linux由众多微内核组成,什么是linux
  6. Android -- 网络请求
  7. 关于RICHEDIT的两个问题
  8. pjk static tp.php,在测试服上偶然出现 Error: Loading chunk 5 failed.
  9. Spring.profile实现开发、测试和生产环境的配置和切换
  10. Robot framework之元素定位实战
  11. 单点登录(java)
  12. Windows 10快捷键入门(会更新)
  13. 谷歌浏览器旧版本下载地址
  14. Linux监控平台搭建Zabbix(资源)
  15. 2022.9.19 自学计算机
  16. luogu P4233 射命丸文的笔记
  17. windows下安装PGSQL14
  18. 使用Shell脚本对Oracle元数据进行动态版本控制
  19. Cris 的Python日记(四):Python 数据结构之序列和列表
  20. [译] 用于 iOS 的 ML Kit 教程:识别图像中的文字

热门文章

  1. 我的世界观(Albert Einstein)
  2. 天猫魔盒1S:电视购物新体验
  3. replaceAll 替换
  4. 在Ubuntu下如何压缩与解压一个文件夹
  5. 保证分布式数据一致性的6种方案
  6. Flask关于request的一些方法与属性
  7. sony xz1c android 10,小屏旗舰再现江湖,索尼XZ1c曝光
  8. (附源码)springboot的房产中介系统 毕业设计312341
  9. 笔试编程---快手实习题目
  10. html画一个倒三角,css 三角形画法