1.MyBatis-Plus入门开发及配置

1.1.MyBatis-Plus简介

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

MyBatis-Plus易于学习,官网提供了基于SpringBoot的中文文档,社区活跃,版本迭代快速。

MyBatis-Plus官方文档:https://baomidou.com/guide/,可作为日常开发文档及特性学习。

1.2.基于SpringBoot项目集成MyBatis-Plus

可以基于IDEA的Spring Initializr进行SpringBoot项目的创建,或者移步至Boot官网构建一个简单的web starter项目:https://start.spring.io/

①导入MyBatis-Plus相关的依赖包、数据库驱动、lombok插件包:

pom.xml文件配置

mysql

mysql-connector-java

org.projectlombok

lombok

com.baomidou

mybatis-plus-boot-starter

3.0.5

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-test

test

junit

junit

test

②配置数据库驱动、日志级别

application.properties配置

# mysql5 驱动不同,默认驱动:com.mysql.jdbc.Driver

spring.datasource.username=root

spring.datasource.password=admin

spring.datasource.url=jdbc:mysql://localhost:3306/mybatisplus_0312?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8

#mysql8 驱动不同:com.mysql.cj.jdbc.Driver、需要增加时区的配置:serverTimezone=GMT%2B8,mysql8的驱动向下兼容mysql5

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

#配置日志

mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

1.3.入门Hello World进行数据库操作

基于官网示例来构建数据库表单及POJO数据类:https://baomidou.com/guide/quick-start.html#初始化工程

MybatisPlusApplication启动类:

@SpringBootApplication//配置Mapper接口类扫描

@MapperScan("com.fengye.mapper")//配置Spring Bean注解扫描

@ComponentScan(basePackages = "com.fengye.mapper")public classMybatisPlusApplication {public static voidmain(String[] args) {

SpringApplication.run(MybatisPlusApplication.class, args);

}

}

UserMapper类:

@Repository //持久层注解,表示该类交给Springboot管理

public interface UserMapper extends BaseMapper{

}

User类:

@Datapublic classUser {privateLong id;privateString name;privateInteger age;privateString email;

}

基础CRUD操作:

@SpringBootTestclassMybatisPlusApplicationTests {

@Autowired//需要配置SpringBoot包扫描,否则此处使用@Autowired会报警告//@Resource

privateUserMapper userMapper;

@TestvoidtestSelect() {

System.out.println(("----- selectAll method test ------"));

List userList = userMapper.selectList(null);

Assert.assertEquals(5, userList.size());

userList.forEach(System.out::println);

}

@TestvoidtestInsert(){

System.out.println("----- insert method test ------");

User user= newUser();

user.setName("枫夜爱学习");

user.setAge(20);

user.setEmail("241337663@qq.com");int insertId =userMapper.insert(user);

System.out.println(insertId);

}

@TestvoidtestUpdate(){

System.out.println("----- update method test ------");

User user= newUser();

user.setId(1370382950972436481L);

user.setName("苞米豆最爱");

user.setAge(4);

user.setEmail("baomidou@github.com");int updateId =userMapper.updateById(user);

System.out.println(updateId);

System.out.println(user);

}

@TestvoidtestDelete(){

System.out.println("----- delete method test ------");int deleteId = userMapper.deleteById(1370386235364118529L);

System.out.println(deleteId);

}

}

1.3.主键生成策略配置

主键生成策略:

使用@TableId(type = IdType.AUTO,value = "id") ,value属性值当实体类字段名和数据库一致时可以不写,这里的value指的是数据库字段名称,type的类型有以下几种:

public enumIdType {

AUTO(0), //Id自增操作

NONE(1), //未设置主键

INPUT(2), //手动输入,需要自己setID值

ID_WORKER(3), //默认的全局唯一id

UUID(4), //全局唯一id uuid

ID_WORKER_STR(5); //ID_WORKER的字符串表示法

...

}

目前MyBatis-Plus官方文档建议的id主键设置为:@TableId(type = IdType.INPUT)

1.4.自动填充

自动填充功能可以实现针对某个POJO类中的一些时间字段值进行自定义填充策略(非基于数据库表设置timestamp默认根据时间戳更新),实现自动插入和更新操作:

①首先需要在POJO类上需要自动填充的字段上增加@TableField(fill = FieldFill.INSERT)、@TableField(fill = FieldFill.INSERT_UPDATE)注解:

@Datapublic classUser {//设置主键为需要自己填入设置

@TableId(type =IdType.AUTO)privateLong id;privateString name;privateInteger age;privateString email;//当创建数据库该字段时,自动执行创建该字段的默认值

@TableField(fill = FieldFill.INSERT, value = "create_time")privateDate createTime;//当数据库该字段发生创建与更新操作时,自动去填充数据值

@TableField(fill = FieldFill.INSERT_UPDATE, value = "update_time")privateDate updateTime;

}

②自定义实现类MyMetaObjectHandler实现MetaObjectHandler接口,覆写insertFill与updateFill方法:

@Slf4j

@Componentpublic class MyMetaObjectHandler implementsMetaObjectHandler {//插入时的填充策略

@Overridepublic voidinsertFill(MetaObject metaObject) {

log.info("start insert fill ....");this.strictInsertFill(metaObject,"createTime", LocalDateTime.class,LocalDateTime.now());this.strictUpdateFill(metaObject,"updateTime",LocalDateTime.class,LocalDateTime.now());

}//更新时的填充策略

@Overridepublic voidupdateFill(MetaObject metaObject) {

log.info("start update fill ....");this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); //起始版本 3.3.0(推荐)

}

}

2.核心功能

2.1.批量查询

//测试批量查询

@Testpublic voidtestSelectByBatchId(){

List users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));

users.forEach(System.out::println);

}

2.2.分页查询

①需要在配置类中注册分页插件注解:

//注册分页插件

@BeanpublicPaginationInterceptor paginationInterceptor() {

PaginationInterceptor paginationInterceptor= newPaginationInterceptor();//设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false

paginationInterceptor.setOverflow(false);returnpaginationInterceptor;

}

②测试分页插件效果:

@Testpublic voidtestPageHelper(){//参数:当前页;页面大小

Page page = new Page<>(1, 2);

userMapper.selectPage(page,null);

List records =page.getRecords();

records.forEach(System.out::println);

System.out.println("当前页是:" +page.getCurrent());

System.out.println("每页显示多少条数:" +page.getSize());

System.out.println("总页数是:" +page.getTotal());

}

2.3.逻辑删除

所谓逻辑删除,在数据库中并不是真正的删除数据的记录,而是通过一个变量来设置数据为失效状态(deleted = 0 => deleted = 1)。使用场景:管理员登录系统查看回收站被“删除数据”。

在MybatisPlus中,给我们提供logicSqlInjector

逻辑删除主要实现步骤:

①在数据库中增加逻辑删除字段deleted:

②实体类User中增加属性字段,并添加@TableLogic注解:

@TableLogic //逻辑删除

private Integer deleted;

③注册逻辑删除组件:

//注册逻辑删除插件

@BeanpublicISqlInjector sqlInjector(){return newLogicSqlInjector();

}

④在application.properties中配置逻辑删除:

#配置逻辑删除

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

执行测试Sql分析可以看到,实际逻辑删除并没有删除,而是通过修改deleted状态为1,数据仍可以保存在数据库中:

2.4.条件构造器Wapper

条件构造器就是Wrapper,就是一个封装查询条件对象,让开发者自由的定义查询条件,主要用于sql的拼接,排序或者实体参数等;

在实际使用中需要注意:

使用的参数是数据库字段名称,不是Java类属性名

条件构造器的查询方法有很多,可以封装出比较复杂的查询语句块,这里罗列一些重要常用的查询方法,更多详细请查询官网地址:

https://mp.baomidou.com/guide/wrapper.html#abstractwrapper

Wrapper分类:

测试如下:

//isNotNull:非空查询//ge:>= 判断查询

@Testpublic voidtestQueryWrapper(){//查询name不为空、并且邮箱不为空、并且年龄大于等于12

QueryWrapper queryWrapper = new QueryWrapper<>();

queryWrapper

.isNotNull("name")

.isNotNull("email")

.ge("age", 21);

List users =userMapper.selectList(queryWrapper);

users.forEach(System.out::println);

}//eq:用于单个查询where name = 'xxx'

@Testpublic voidtestQueryOne(){//查询姓名为Sandy的用户

QueryWrapper queryWrapper = new QueryWrapper<>();

queryWrapper.eq("name", "Sandy");

User selectOne=userMapper.selectOne(queryWrapper);

System.out.println(selectOne);

}//between:介于...之间

@Testpublic voidtestQueryBetween(){//查询年龄在20 - 30岁之间的用户

QueryWrapper queryWrapper = new QueryWrapper<>();

queryWrapper.between("age", 25, 30);

List userList =userMapper.selectList(queryWrapper);

userList.forEach(System.out::println);

}//notLike、likeRight、likeLeft

@Testpublic voidtestQueryLike(){//查询姓名中不包含字母'e'并且邮箱以't'开头的

QueryWrapper queryWrapper = new QueryWrapper<>();

queryWrapper

.notLike("name", 'e')

.likeRight("email", 't');

List userList =userMapper.selectList(queryWrapper);

userList.forEach(System.out::println);

}//inSql:表示in 查询id IN ( select id from user where id < 3 )

@Testpublic voidtestInSql(){//查询姓名中不包含字母'e'并且邮箱以't'开头的

QueryWrapper queryWrapper = new QueryWrapper<>();

queryWrapper.inSql("id", "select id from user where id < 3");

List objects =userMapper.selectObjs(queryWrapper);

objects.forEach(System.out::println);

}

@Testpublic voidtestOrderBy(){//查询user按年龄排序

QueryWrapper queryWrapper = new QueryWrapper<>();

queryWrapper.orderByDesc("age");

List userList =userMapper.selectList(queryWrapper);

userList.forEach(System.out::println);

}

3.插件扩展

3.1.乐观锁插件

当我们在开发中,有时需要判断,当我们更新一条数据库记录时,希望这条记录没有被别人更新,这个时候就可以使用乐观锁插件。

乐观锁的实现方式:

取出记录时,获取当前的version;

更新时,带上这个version;

执行更新时,set version = new version where version = oldversion;

如果version不对,就更新失败

具体实现步骤如下:

①数据库新增乐观锁字段version,设置默认值为1:

②在实体类User中新增version字段:

@Version //乐观锁Version注解

private Integer version;

③注册乐观锁主键:

//开启事务

@EnableTransactionManagement

@Configuration//声明此类是配置类

public classMyBatisplusConfig {//注册乐观锁插件

@BeanpublicOptimisticLockerInterceptor optimisticLockerInterceptor() {return newOptimisticLockerInterceptor();

}

}

④测试单线程多线程情况乐观锁是否执行更新update成功:

//测试乐观锁单线程执行成功

@Testpublic voidtestOptimisticLocker(){//1、查询用户信息

User user = userMapper.selectById(1L);//2、修改用户信息

user.setName("fengye");

user.setEmail("241337663@qq.com");//3、执行更新操作

userMapper.updateById(user);

}//测试乐观锁失败!多线程下

@Testpublic voidtestOptimisticLocker2(){//线程 1

User user = userMapper.selectById(1L);

user.setName("fengye111");

user.setEmail("241337663@qq.com");//模拟另外一个线程执行了插队操作

User user2 = userMapper.selectById(1L);

user2.setName("fengye222");

user2.setEmail("241337663@qq.com");

userMapper.updateById(user2);

userMapper.updateById(user);//如果没有乐观锁就会覆盖插队线程的值!

}

3.2.性能分析插件

MyBatis-Plus提供的性能分析插件可以作为性能分析拦截器,用于输出每条SQL语句及其执行时间。可以在开发测试时定量分析慢查询的SQL语句,用于后期优化分析。

具体使用步骤:

①在MyBatis-PlusConfig类中配置SQL性能分析插件:

/*** SQL执行效率插件*/@Bean

@Profile({"dev","test"})//设置 dev test 环境开启,保证我们的效率

publicPerformanceInterceptor performanceInterceptor() {

PerformanceInterceptor performanceInterceptor= newPerformanceInterceptor();

performanceInterceptor.setMaxTime(100); //ms设置sql执行的最大时间为100ms,如果超过了则不执行

performanceInterceptor.setFormat(true); //是否格式化代码

returnperformanceInterceptor;

}

②配置插件运行环境为dev:

#设置开发环境为dev

spring.profiles.active=dev

③执行测试,可以看到sql已经format及实际执行sql语句的消耗时间:

@Testpublic voidtestPerformance(){//查询全部用户

List users = userMapper.selectList(null);

users.forEach(System.out::println);

}

3.3.代码生成器

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

具体使用步骤如下:

①使用代码生成器(Mybatis-Plus3.1.1版本以下)需要添加velocity模板、Swagger配置:

org.apache.velocity

velocity-engine-core

2.3

com.spring4all

spring-boot-starter-swagger

1.5.1.RELEASE

provided

②编写自动生成器类:

public classAutoGeneratorUtil {public static voidmain(String[] args) {

AutoGenerator mpg= newAutoGenerator();//策略配置//1、全局配置

GlobalConfig gc = newGlobalConfig();

String projectPath= System.getProperty("user.dir");

gc.setActiveRecord(true); //是否开启AR模式

gc.setAuthor("fengye");

gc.setOutputDir(projectPath+"/src/main/java");

gc.setOpen(false);

gc.setFileOverride(false); //是否覆盖

gc.setServiceName("%sService"); //设置生成的services接口的名字的首字母是否为I//gc.setIdType(IdType.ID_WORKER);//gc.setDateType(DateType.ONLY_DATE);

gc.setSwagger2(true);

mpg.setGlobalConfig(gc);//2、设置数据源

DataSourceConfig dsc = newDataSourceConfig();

dsc.setDriverName("com.mysql.cj.jdbc.Driver");

dsc.setUrl("jdbc:mysql://localhost:3306/mybatisplus_0312?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");

dsc.setUsername("root");

dsc.setPassword("admin");

dsc.setDbType(DbType.MYSQL);

mpg.setDataSource(dsc);//3、包的配置

PackageConfig pc = newPackageConfig();

pc.setModuleName("test");

pc.setParent("com.fengye");

pc.setEntity("entity");

pc.setMapper("mapper");//设置xml文件与mapper目录同级

pc.setXml("mapper");

pc.setService("service");

pc.setController("controller");

mpg.setPackageInfo(pc);//4、策略配置

StrategyConfig strategy = newStrategyConfig();//设置要映射的表名,支持多张表以逗号隔开

strategy.setInclude("user", "t_dept", "t_employee");

strategy.setNaming(NamingStrategy.underline_to_camel);

strategy.setColumnNaming(NamingStrategy.underline_to_camel);

strategy.setEntityLombokModel(true); //使用lombok注解

strategy.setRestControllerStyle(true); //Restful风格

strategy.setLogicDeleteFieldName("deleted"); //逻辑删除名称//5、自动填充配置

TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);

TableFill gmtModified= new TableFill("gmt_modified", FieldFill.INSERT_UPDATE);

ArrayList tableFills = new ArrayList<>();

tableFills.add(gmtCreate);

tableFills.add(gmtModified);

strategy.setTableFillList(tableFills);//6、乐观锁

strategy.setVersionFieldName("version");strategy.setRestControllerStyle(true);

strategy.setControllerMappingHyphenStyle(true); //设置映射地址支持下划线 localhost:8080/hello_id_2

mpg.setStrategy(strategy);

mpg.execute();

}

}

本博客写作参考文档相关:

https://baomidou.com/guide/

http://luokangyuan.com/mybatisplusxue-xi-bi-ji/

https://www.bilibili.com/video/BV17E411N7KN?p=16&spm_id_from=pageDriver

示例代码已上传至Github地址:

https://github.com/devyf/JavaWorkSpace/tree/master/mybatis_plus/mybatis_plus_quickstart

本帖子中包含资源

您需要 登录 才可以下载,没有帐号?立即注册

java mybatis的作用,【java框架】MyBatis-Plus(1)--MyBatis-Plus快速上手开发及核心功能体验-博客...相关推荐

  1. 【java框架】MyBatis-Plus(1)--MyBatis-Plus快速上手开发及核心功能体验

    可以基于IDEA的Spring Initializr进行SpringBoot项目的创建,或者移步至Boot官网构建一个简单的web starter项目:https://start.spring.io/ ...

  2. 基于hexo框架快速从0到1搭建个人博客----文章写作(四)

    基于hexo框架快速从0到1搭建个人博客----文章写作 一.Github图床(图片存储) 二.PicGo(图片上传) 三.jsDelivr(CDN加速) 四.Typora(写文传图) 五.总结 一. ...

  3. java中properties作用,Java中Properties的使用详解

    Java中有个比较重要的类Properties(Java.util.Properties),主要用于读取Java的配置文件,各种语言都有自己所支 持的配置文件,配置文件中很多变量是经常改变的,这样做也 ...

  4. 基于SpringBoot+Vue开发的前后端分离博客项目-Java后端接口开发

    文章目录 1. 前言 2. 新建Springboot项目 3. 整合mybatis plus 第一步:导依赖 第二步:写配置文件 第三步:mapper扫描+分页插件 第四步:代码生成配置 第五步:执行 ...

  5. 【Bootstrap4前端框架+MySQL数据库】前后端综合实训【10天课程 博客汇总表 详细笔记】【附:所有代码】

    目   录 日常要求.项目要求 用到的软件版本情况说明 上课时的所有代码.用到的软件安装包 实训第2周--前后端"新闻管理系统"工程所有文件(MySQL语句+eclipse项目) ...

  6. java model类作用_SPRING框架中ModelAndView、Model、ModelMap区别及详细分析

    注意:如果方法声明了注解@ResponseBody ,则会直接将返回值输出到页面. 首先介绍ModelMap[Model]和ModelAndView的作用 Model 是一个接口, 其实现类为Exte ...

  7. java set的作用,Java的自学之路-构造方法 的作用以及与set方法的区别

    在java中,我们创建一个类时需要对类中的成员变量进行私有化,private..这样可以提高代码的安全性,那么在new 一个对象时,我们就不能对类中的成员变量直接赋值,此时可以在类中写一个 方法,这个 ...

  8. java集成agent作用,Java Agent基本简介和使用

    javaagent简介 javaagent是一种能够在不影响正常编译的情况下,修改字节码.java作为一种强类型的语言,不通过编译就不能能够进行jar包的生成.而有了javaagent技术,就可以在字 ...

  9. java中properties作用,java中Properties类的使用

    java中Properties类的使用 在java.util 包下面有一个类 Properties,该类主要用于读取以项目的配置文件(以.properties结尾的文件和xml文件). Propert ...

最新文章

  1. NSURLCache
  2. 《Java程序设计》终极不改版【下】
  3. Singleton 和 Monostate 模式
  4. python默认编码方式_关于设置python默认编码方式的问题
  5. 2017-12-28 Linux学习笔记
  6. 武大高级软件工程2017评分汇总
  7. android开发ViewPager按比例显示图片(显示下一张图片的一部分)
  8. 工具推荐——Snipaste
  9. 表头冻结列冻结_如何在Excel中冻结和取消冻结行和列
  10. chrome打不开网页 转圈圈
  11. python搜索引擎的设计与实现_Python搜索引擎实现原理和方法
  12. 后台管理系统项目整体流程
  13. 山东农村商业银行计算机笔试,2021年山东农村商业银行笔试备考:计算机科目高分复习方法...
  14. 恶意软件Emotet卷土重来滥用.LNK文件进行攻击,你只需要一项技术就能有效保护组织
  15. 云栖独栋别墅_绿野云溪花海独栋别墅
  16. 云主机和电脑主机服务器有什么区别?
  17. harmonyos开源,华为杨海松:鸿蒙系统支持第三方手机 “开源开放毫无保留”
  18. C++详解:枚举类型 --- enum | Xunlan_blog
  19. C语言:实现一个函数itoa(int n,char s[]),将整数n这个数字转换为对应的字符串,保存到s中...
  20. 移动端」H5页面长按复制功能实现

热门文章

  1. Spring Boot的启动流程
  2. Android应用安全加固
  3. 建造智能食用菌大棚,用菌菇养殖管理系统管理温室
  4. (下篇)校园小程序前端部署教程-优雅草老八写
  5. TCP/IP 工作模型
  6. 安装php vcruntime140,win7安装apache或者php 5.7缺少vcruntime140.dll的问题
  7. Linux下安装gitea
  8. 论CTOR添加到11月BCH协议升级
  9. 使用 yarn 安装时,报错node_modules\node sass:Command failed.
  10. powermockito测试私有方法_03 增强测试: 静态、私有方法处理