mybatis-plus和mysql
mybatis-plus and mysql
持续更新中 。。。。。。
文章目录
- mybatis-plus and mysql
- 1. 乐观锁和悲观锁的介绍
- 2. mybatis(乐观锁)
- 3. 分页插件
- 4. 代码生成器
- 5. 逻辑删除
- 6. 条件构造器
- 7. 自动填充
1. 乐观锁和悲观锁的介绍
悲观锁
串行: 对于一条数据,在我没有完成操作之前,其他线程不能对这条数据操作
乐观锁
当要更新一条记录时,希望这条记录没有被别人更新
乐观锁的实现方式:
- 取出记录时,获取当前
version
- 更新时,带上这个
version
- 执行更新时,
set version = newVersion where version = oldVersion
- 如果
version
不对,就更新失败
- 取出记录时,获取当前
2. mybatis(乐观锁)
注意:mybatis-plus的版本3.5.1
主要类: OptimisticLockerInnerInterceptor
配置插件:
spring.xml格式
<bean class="com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor" id="optimisticLockerInnerInterceptor"/><bean id="mybatisPlusInterceptor" class="com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor"><property name="interceptors"><list><ref bean="optimisticLockerInnerInterceptor"/></list></property> </bean>
springboot 注解方式
@Configuration
public class BeanConfig {@Beanpublic IKeyGenerator myKeyGenerator(){return new H2KeyGenerator();}//插件配置//乐观锁插件,分页插件@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();//添加插件interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());//乐观锁interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));//分页插件return interceptor;}
}
添加字段
@Version private Integer version;
3. 分页插件
主要类 PaginationInnerInterceptor
配置插件
@Configuration public class BeanConfig {@Beanpublic IKeyGenerator myKeyGenerator(){return new H2KeyGenerator();}//插件配置//乐观锁插件,分页插件@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();//添加插件interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());//乐观锁interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));//分页插件return interceptor;} }
- 测试分页插件效果
//测试分页插件@Testpublic void testPagination(){Page<User> page = new Page<>(1, 5);//当前页,每页5条数据userMapper.selectPage(page, null);// 将查到的所有数据存入在Page对象里面page.getRecords().forEach(System.out::println);System.out.println("====================");System.out.println(page.getCurrent());//当前页System.out.println(page.getPages());//总页数System.out.println(page.getSize());//每页显示条数System.out.println(page.getTotal());//总条数System.out.println(page.hasNext());//是否有下一页System.out.println(page.hasPrevious());//是否有上一页}
4. 代码生成器
添加依赖
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.5.2</version> </dependency>
创建一个方法,方法体如下 :
package com.biienu;import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;import java.util.Collections;/*** @Author: biienu* @Date: 2022/3/19 21:13*/
@SpringBootTest
public class AutoGenearteCode {FastAutoGenerator.create("jdbc:mysql://localhost:3306/club?characterEncoding=UTF-8&serverTimezone=GMT%2B8","root", "aoeyue").globalConfig(builder -> {builder.author("biienu") // 设置作者.enableSwagger() // 开启 swagger 模式.fileOverride() // 覆盖已生成文件
// .outputDir("E:\\ProcessDocuments\\项目测试\\online-education\\service\\service-edu\\src\\main\\java\\com\\biienu"); // 指定输出目录.outputDir("E:\\ProcessDocuments\\web-front\\gradual-design\\student-orgnization-end\\src\\main\\java");}).packageConfig(builder -> {builder.parent("com.biienu.studentorgnizationend") // 设置父包名.moduleName("") // 设置父包模块名
// .pathInfo(Collections.singletonMap(OutputFile.mapperXml, "E:\\ProcessDocuments\\项目测试\\online-education\\service\\service-edu\\src\\main\\resources\\mappers")); // 设置mapperXml生成路径.pathInfo(Collections.singletonMap(OutputFile.mapperXml,"E:\\ProcessDocuments\\web-front\\gradual-design\\student-orgnization-end\\src\\main\\resources\\mappers"));}).strategyConfig(builder -> {builder.addInclude("activity","apply_activity","apply_club","club","member","message","news","user").entityBuilder().serviceBuilder().formatServiceFileName("%sService"); // 将生成的 Service 类名称格式化为 %sService;
// .addTablePrefix("t_", "c_"); // 设置过滤表前缀}).templateEngine(new VelocityTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板.execute();}
}
5. 逻辑删除
使用说明
只对自动注入的 sql 起效:
插入: 不作限制
查找: 追加 where 条件过滤掉已删除数据,且使用 wrapper.entity 生成的 where 条件会忽略该字段
更新: 追加 where 条件防止更新到已删除数据,且使用 wrapper.entity 生成的 where 条件会忽略该字段
删除: 转变为 更新
例如:
- 删除:
update user set deleted=1 where id = 1 and deleted=0
- 查找:
select id,name,deleted from user where deleted=0
字段类型支持说明:
支持所有数据类型(推荐使用
Integer
,Boolean
,LocalDateTime
)如果数据库字段使用
datetime
,逻辑未删除值和已删除值支持配置为字符串null
,另一个值支持配置为函数来获取值如now()
附录:
- 逻辑删除是为了方便数据恢复和保护数据本身价值等等的一种方案,但实际就是删除。
- 如果你需要频繁查出来看就不应使用逻辑删除,而是以一个状态去表示。
使用步骤 :
yaml配置文件修改
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 private Integer deleted;
6. 条件构造器
主要通过QueryWrapper
类
如果想进行复杂条件查询,那么需要使用条件构造器 Wapper,涉及到如下方法
1、delete
2、selectOne
3、selectCount
4、selectList
5、selectMaps
6、selectObjs
7、update
7. 自动填充
实现步骤 :
创建一个类,实现
MetaObjectHandler
类, 重写两个方法,如下 :public class MyMetaObjectHandler implements MetaObjectHandler {@Overridepublic void insertFill(MetaObject metaObject) {this.setFieldValByName("gmtCreate",LocalDateTime.now(), metaObject);//gmtCreate为实体字段,不是表中字段 this.setFieldValByName("gmtModified",LocalDateTime.now(), metaObject);}@Overridepublic void updateFill(MetaObject metaObject) {this.setFieldValByName("gmtModified", LocalDateTime.now(), metaObject);} }
在实体类属性上添加这个注解
@TableField
, 实现如下 :@TableField(fill = FieldFill.INSERT)private LocalDateTime gmtCreate;@TableField(fill = FieldFill.INSERT_UPDATE)private LocalDateTime gmtModified;
mybatis-plus和mysql相关推荐
- 在mybatis用mysql的代码块_关于Mybatis 中使用Mysql存储过程的方法
1.存储过程的简介 我们常用的操作数据库语言SQL语句在执行的时候需要要先编译,然后执行,而存储过程(Stored Procedure)是一组为了完成特定功能的SQL语句集,经编译后存储在数据库中,用 ...
- 使用Mybatis如何对Mysql进行分页功能?
使用Mybatis如何对Mysql进行分页功能 1.Limit实现分页 接口 //分页List<User> getUserByLimit(HashMap<String, Intege ...
- Mybatis实现存取Mysql的Json字段映射Java对象
Mybatis实现存取Mysql的Json字段映射Java对象 一.需求 二.解决方案 一.需求 在业务比较复杂的项目模块,为了应对多样化的场景,我们通常会在mysql中采用json格式来存储相应的信 ...
- Springboot、Mybatis(Mybatis-plus) 、Mysql
一.Springboot SpringBoot基于Spring4.0设计,不仅继承了Spring框架原有的优秀特性,而且还通过简化配置来进一步简化了Spring应用的整个搭建和开发过程.另外Sprin ...
- maven mybatis mysql_Java Web学习系列——Maven Web项目中集成使用Spring、MyBatis实现对MySQL的数据访问...
标签: 本篇内容还是建立在上一篇Java Web学习系列--Maven Web项目中集成使用Spring基础之上,对之前的Maven Web项目进行升级改造,实现对MySQL的数据访问. 添加依赖Ja ...
- Mybatis拦截器 mysql load data local 内存流处理
Mybatis 拦截器不做解释了,用过的基本都知道,这里用load data local主要是应对大批量数据的处理,提高性能,也支持事务回滚,且不影响其他的DML操作,当然这个操作不要涉及到当前所lo ...
- 安装mysql8.0.11版本,并使用mybatis进行连接mysql遇到的问题
之前Centos远程服务器使用mysql的版本是5.1.32,今天重新安装了mysql的最先版本8.0.11,安装过程出现了一些问题. 1.第一个错误:1251异常. (1)安装完mysql8.0.1 ...
- spring mvc mysql 实例_Spring+Mybatis+SpringMVC+Maven+MySql搭建实例
一.准备工作 1. 首先创建一个表: CREATE TABLE `t_user` ( `USER_ID` int(11) NOT NULL AUTO_INCREMENT, `USER_NAME` ch ...
- springmvc与mysql实例_Spring+Mybatis+SpringMVC+Maven+MySql搭建实例
摘要:本文主要讲了如何使用Maven来搭建Spring+Mybatis+SpringMVC+MySql的搭建实例,文章写得很详细,有代码有图片,最后也带有运行的效果. 一.准备工作 1. 首先创建一个 ...
- mysql 插入毫秒数据_【转载】怎样在mybatis里向mysql中插入毫秒数的时间?
由于业务场景需求,需要记录精准的时间,但是呢,又不要想使用int类型来存储时间,因为这样的可读性比较差了. 怎样在mybatis中向数据库插入毫秒级别的时间呢? 首先,先来看看怎样向数据库中插入毫秒时 ...
最新文章
- Linux 设置 Swap 空间
- 161. Leetcode 55. 跳跃游戏 (贪心算法-贪心区间)
- 思科安全——企业安全棋局的“宇宙流”
- 大型单细胞数据分析解决方案
- 开源网站统计程序 oracle,利用百夫长统计程序源码免费搭建独立网站统计软件工具...
- 这4个免费办公神器有多良心?用后就离不开,可惜一般人都不知道
- 使用bs4+re正则来爬取网页上需要的数据
- 第一节-戴师兄数据分析学习笔记
- ros操作系统的介绍
- 苹果鼠标滚轮驱动_苹果鼠标magic mouse在戴尔电脑Windows10系统上使用滚轮的方法...
- video.js 自定义播放组件
- 面试官:说说你对双向绑定的理解?
- Tensorflow使用object_detetcion安装教程
- 什么是GMS、CDMA、GPRS、EDGE、WCDMA、TD-CDMA、HSPA+、LTE?
- revit学习-视图
- Win7 更新 80072EFE 错误
- 基于PHP+MySQL的游戏论坛管理系统
- Windows Server 2016 VOL 简体中文版 2017 年 1 月版
- MTK WIFImac地址
- 【天光学术】银行会计主管竞聘演讲稿
热门文章
- AI大事件 | Geoffrey Hinton决定抛弃反向传播,预期策略梯度算法
- 时序逻辑电路总结【一】触发器
- web安全防火墙介绍
- java数组可以包含对象吗_数组可以包含对象类型的元素吗_对象数组
- [Linux 驱动] -- 驱动调试技巧点滴分享
- 微信转发网站怎么可以看到icon图标?
- 四平方和定理(每个正整数均可表示为4个平方数的和)
- 拉格朗日四平方和定理c语言,拉格朗日四平方定理的证明
- android 高德地图显示标题,android学习之高德地图添加标记
- AntD Button 图标集成 iconfont