mybatis-plus和mysql

mybatis-plus and mysql

持续更新中 。。。。。。

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 {

    @Bean
    public IKeyGenerator myKeyGenerator(){
        return new H2KeyGenerator();
    }
    //插件配置
    //乐观锁插件,分页插件
    @Bean
    public 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 {
    
        @Bean
        public IKeyGenerator myKeyGenerator(){
            return new H2KeyGenerator();
        }
        //插件配置
        //乐观锁插件,分页插件
        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor() {
            MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    
            //添加插件
            interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());//乐观锁
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));//分页插件
            return interceptor;
        }
    }
    
    1. 测试分页插件效果
        //测试分页插件
        @Test
        public 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 {
        @Override
        public void insertFill(MetaObject metaObject) {
            this.setFieldValByName("gmtCreate",LocalDateTime.now(), metaObject);//gmtCreate为实体字段,不是表中字段 
            this.setFieldValByName("gmtModified",LocalDateTime.now(), metaObject);
        }
    
        @Override
        public 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;
    
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值