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

  1. 配置插件:

    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;}
}
  1. 添加字段

    @Version
    private Integer version;
    

3. 分页插件

主要类 PaginationInnerInterceptor

  1. 配置插件

    @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;}
    }
    
    1. 测试分页插件效果
        //测试分页插件@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. 代码生成器

  1. 添加依赖

    <dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.5.2</version>
    </dependency>
    
  2. 创建一个方法,方法体如下 :

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()


附录:

  • 逻辑删除是为了方便数据恢复和保护数据本身价值等等的一种方案,但实际就是删除。
  • 如果你需要频繁查出来看就不应使用逻辑删除,而是以一个状态去表示。

使用步骤 :

  1. 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)
    
  2. 实体类字段上添加注解

    @TableLogic
    private Integer deleted;
    

6. 条件构造器

主要通过QueryWrapper

如果想进行复杂条件查询,那么需要使用条件构造器 Wapper,涉及到如下方法

1、delete

2、selectOne

3、selectCount

4、selectList

5、selectMaps

6、selectObjs

7、update


7. 自动填充

实现步骤 :

  1. 创建一个类,实现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);}
    }
    
  2. 在实体类属性上添加这个注解@TableField, 实现如下 :

        @TableField(fill = FieldFill.INSERT)private LocalDateTime gmtCreate;@TableField(fill = FieldFill.INSERT_UPDATE)private LocalDateTime gmtModified;
    

mybatis-plus和mysql相关推荐

  1. 在mybatis用mysql的代码块_关于Mybatis 中使用Mysql存储过程的方法

    1.存储过程的简介 我们常用的操作数据库语言SQL语句在执行的时候需要要先编译,然后执行,而存储过程(Stored Procedure)是一组为了完成特定功能的SQL语句集,经编译后存储在数据库中,用 ...

  2. 使用Mybatis如何对Mysql进行分页功能?

    使用Mybatis如何对Mysql进行分页功能 1.Limit实现分页 接口 //分页List<User> getUserByLimit(HashMap<String, Intege ...

  3. Mybatis实现存取Mysql的Json字段映射Java对象

    Mybatis实现存取Mysql的Json字段映射Java对象 一.需求 二.解决方案 一.需求 在业务比较复杂的项目模块,为了应对多样化的场景,我们通常会在mysql中采用json格式来存储相应的信 ...

  4. Springboot、Mybatis(Mybatis-plus) 、Mysql

    一.Springboot SpringBoot基于Spring4.0设计,不仅继承了Spring框架原有的优秀特性,而且还通过简化配置来进一步简化了Spring应用的整个搭建和开发过程.另外Sprin ...

  5. maven mybatis mysql_Java Web学习系列——Maven Web项目中集成使用Spring、MyBatis实现对MySQL的数据访问...

    标签: 本篇内容还是建立在上一篇Java Web学习系列--Maven Web项目中集成使用Spring基础之上,对之前的Maven Web项目进行升级改造,实现对MySQL的数据访问. 添加依赖Ja ...

  6. Mybatis拦截器 mysql load data local 内存流处理

    Mybatis 拦截器不做解释了,用过的基本都知道,这里用load data local主要是应对大批量数据的处理,提高性能,也支持事务回滚,且不影响其他的DML操作,当然这个操作不要涉及到当前所lo ...

  7. 安装mysql8.0.11版本,并使用mybatis进行连接mysql遇到的问题

    之前Centos远程服务器使用mysql的版本是5.1.32,今天重新安装了mysql的最先版本8.0.11,安装过程出现了一些问题. 1.第一个错误:1251异常. (1)安装完mysql8.0.1 ...

  8. spring mvc mysql 实例_Spring+Mybatis+SpringMVC+Maven+MySql搭建实例

    一.准备工作 1. 首先创建一个表: CREATE TABLE `t_user` ( `USER_ID` int(11) NOT NULL AUTO_INCREMENT, `USER_NAME` ch ...

  9. springmvc与mysql实例_Spring+Mybatis+SpringMVC+Maven+MySql搭建实例

    摘要:本文主要讲了如何使用Maven来搭建Spring+Mybatis+SpringMVC+MySql的搭建实例,文章写得很详细,有代码有图片,最后也带有运行的效果. 一.准备工作 1. 首先创建一个 ...

  10. mysql 插入毫秒数据_【转载】怎样在mybatis里向mysql中插入毫秒数的时间?

    由于业务场景需求,需要记录精准的时间,但是呢,又不要想使用int类型来存储时间,因为这样的可读性比较差了. 怎样在mybatis中向数据库插入毫秒级别的时间呢? 首先,先来看看怎样向数据库中插入毫秒时 ...

最新文章

  1. Linux 设置 Swap 空间
  2. 161. Leetcode 55. 跳跃游戏 (贪心算法-贪心区间)
  3. 思科安全——企业安全棋局的“宇宙流”
  4. 大型单细胞数据分析解决方案
  5. 开源网站统计程序 oracle,利用百夫长统计程序源码免费搭建独立网站统计软件工具...
  6. 这4个免费办公神器有多良心?用后就离不开,可惜一般人都不知道
  7. 使用bs4+re正则来爬取网页上需要的数据
  8. 第一节-戴师兄数据分析学习笔记
  9. ros操作系统的介绍
  10. 苹果鼠标滚轮驱动_苹果鼠标magic mouse在戴尔电脑Windows10系统上使用滚轮的方法...
  11. video.js 自定义播放组件
  12. 面试官:说说你对双向绑定的理解?
  13. Tensorflow使用object_detetcion安装教程
  14. 什么是GMS、CDMA、GPRS、EDGE、WCDMA、TD-CDMA、HSPA+、LTE?
  15. revit学习-视图
  16. Win7 更新 80072EFE 错误
  17. 基于PHP+MySQL的游戏论坛管理系统
  18. Windows Server 2016 VOL 简体中文版 2017 年 1 月版
  19. MTK WIFImac地址
  20. 【天光学术】银行会计主管竞聘演讲稿

热门文章

  1. AI大事件 | Geoffrey Hinton决定抛弃反向传播,预期策略梯度算法
  2. 时序逻辑电路总结【一】触发器
  3. web安全防火墙介绍
  4. java数组可以包含对象吗_数组可以包含对象类型的元素吗_对象数组
  5. [Linux 驱动] -- 驱动调试技巧点滴分享
  6. 微信转发网站怎么可以看到icon图标?
  7. 四平方和定理(每个正整数均可表示为4个平方数的和)
  8. 拉格朗日四平方和定理c语言,拉格朗日四平方定理的证明
  9. android 高德地图显示标题,android学习之高德地图添加标记
  10. AntD Button 图标集成 iconfont