MyBatis Plus

MyBatis Plus

mybatis plus可以节省我们大量工作时间,所有的crud代码都可以自动化实现。

特性:

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本 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 操作智能分析阻断,也可自定义拦截规则,预防误操作

快速入门:

使用第三方组件:

1.导入依赖


       <dependency>
           <groupId>com.baomidougroupId>
           <artifactId>mybatis-plus-boot-starterartifactId>
         <version>3.0.5version>
       dependency>

说明:不要同时导入mybatis依赖

2.研究依赖如何配置

  • 创建pojo

  • 创建mapper接口

  • /**
     * @author fjc23
     * 继承BaseMapper<操作的pojo>
     */
    
    
    public interface EmpMapper extends BaseMapper<Emp> {
    
        //所有的crud编写完成
    }
    
    @MapperScan("com.fjp.mapper")
    @SpringBootApplication
    public class MybatisplusTestApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(MybatisplusTestApplication.class, args);
        }
    
    }
    

    启动类中注入MapperScan对mapper进行扫描

  • 使用

  • @SpringBootTest
    class MybatisplusTestApplicationTests {
    
        @Autowired
        private EmpMapper empMapper;
        @Test
        void contextLoads() {
            //查询全部,参数是一个wapper,条件构造器,这里先不使用,写一个null
            List<Emp> emps = empMapper.selectList(null);
            emps.forEach(System.out::println);
        }
    
    }
    

3.代码如何编写

配置日志

在applicaton.yml中配置

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

CRUD扩展

insert:

Emp emp = new Emp();
emp.setEname("李乐乐");
emp.setPass("123456");
emp.setSalary(15000.0);
emp.setDid(2);
empMapper.insert(emp);

主键生成策略

默认:

ID_WORKER(3)

mybatis-plus会自动生成id,(uuid,自增id,雪花算法,redis,zookeeper)

参考此博客:https://www.cnblogs.com/haoxinyue/p/5208136.html

雪花算法:

snowflake是Twitter开源的分布式ID生成算法,结果是一个long型的ID。其核心思想是:使用41bit作为毫秒数,10bit作为机器的ID(5个bit是数据中心,5个bit的机器ID),12bit作为毫秒内的流水号(意味着每个节点在每毫秒可以产生 4096 个 ID),最后还有一个符号位,永远是0。具体实现的代码可以参看https://github.com/twitter/snowflake。雪花算法支持的TPS可以达到419万左右(2^22*1000)。

snowflake算法可以根据自身项目的需要进行一定的修改。比如估算未来的数据中心个数,每个数据中心的机器数以及统一毫秒可以能的并发数来调整在算法中所需要的bit数。

优点:

1)不依赖于数据库,灵活方便,且性能优于数据库。

2)ID按照时间在单机上是递增的。

缺点:

1)在单机上是递增的,但是由于涉及到分布式环境,每台机器上的时钟不可能完全同步,在算法上要解决时间回拨的问题。

主键自增

需要配置主键自增

1.实体类字段上@TableId(type = IdType.AUTO)
2.数据库字段一定要自增

public enum IdType {
    AUTO(0), //数据库id自增
    NONE(1), //未设置主键
    INPUT(2),// 手动输入
    ID_WORKER(3), //默认的全局id
    UUID(4), //uuid
    ID_WORKER_STR(5); //idwork的字符串表示
   

update

public void testUpdate(){
    Emp emp = new Emp();
    emp.setEid(2);
    emp.setEname("李怡潼");
    int i = empMapper.updateById(emp);

}

所有的sql都可以自动配置

自动填充

创建时间,修改时间,都自动化完成,

所有数据库表,gmt_create,gmt_modified几乎所有的表都要配置上,而且需要自动化

方式一:数据库级别的修改(工作中不不允许修改数据库)

在表中新增字段create_time,updata_time

测试:

插入

方式二:代码级别

在实体类中添加注解

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

给TableFiled设置

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推荐使用)
        // 或者
        this.strictInsertFill(metaObject, "createTime", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐)
        // 或者
        this.fillStrategy(metaObject, "createTime", LocalDateTime.now()); // 也可以使用(3.3.0 该方法有bug)
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推荐)
        // 或者
        this.strictUpdateFill(metaObject, "updateTime", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐)
        // 或者
        this.fillStrategy(metaObject, "updateTime", LocalDateTime.now()); // 也可以使用(3.3.0 该方法有bug)
    }
}

乐观锁

顾名思义,十分乐观,他总是认为不会出现问题,无论干什么都不去上锁,出现问题再次更新值测试

version、new version

悲观锁

十分悲观,它认为总是出现问题,无论干什么都会上锁,再去操作

当要更新一条记录的时候,希望这条记录没有被别人更新
乐观锁实现方式:

  • 取出记录时,获取当前 version
  • 更新时,带上这个 version
  • 执行更新时, set version = newVersion where version = oldVersion
  • 如果 version 不对,就更新失败
乐观锁:1、先查询,获得版本号 version = 1
-- A
update user set name = "ChanV", version = version + 1
where id = 2 and version = 1

-- B 线程抢先完成,这个时候 version = 2,会导致 A 修改失败!
update user set name = "ChanV", version = version + 1
where id = 2 and version = 1

测试乐观锁插件

1.给数据库中增加version字段

2.实体类添加字段添加@Version注解,代表是乐观锁

@Version
private Integer version;

3.注册组件

@Configuration//注解代表是一个配置类
@EnableTransactionManagement //开启注解

4.配置插件

@MapperScan("com.fjp.mapper")
@EnableTransactionManagement
@Configuration
public class MybatisConfig {

    //注册乐观锁插件
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }
}

5.测试

//测试乐观锁成功
@Test
public void testOptimisticLocker(){
    //查询用户信息
    Emps emps = empMapper.selectById(1);
    //修改用户信息
    emps.setEname("八戒");
    emps.setEid(2);

    //模拟另一个线程插队操作
    Emps emps1= empMapper.selectById(1);
    //修改用户信息
    emps1.setEname("八戒1");
    emps1.setEid(2);
    empMapper.updateById(emps);//如果没有乐观锁,就会覆盖插队线程的值

}

删除

//测试删除
@Test
public void testDelete(){
    //通过id删除
    int i = empMapper.deleteById(34);
}

//批量删除
@Test
public void testBatchDelete(){
    empMapper.deleteBatchIds(Arrays.asList(23,26,27));
}


//通过map删除
@Test
public void testDeleteMap(){
    HashMap emp = new HashMap<>();
    emp.put("ename","张三");
    empMapper.deleteByMap(emp);
}

工作中使用逻辑删除

逻辑删除

物理删除:从数据库中直接删除

逻辑删除:数据库中没有被移除,而是通过变量失效,类似与回收站

在数据表中增加deleted字段

增加属性

@TableLogic
private Integer deleted;
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    db-config:
      logic-delete-field: flag # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2)
      logic-delete-value: 1 # 逻辑已删除值(默认为 1)
      logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)

显示删除成功,数据库未删除,本质是更新操作,且查询不到逻辑删除的字段

分页查询

mybatis plus内置了分页插件

1.配置拦截器

@Configuration
public class PageConfig {


    /**
     * 添加分页插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

重点:  interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));

2.直接使用

//测试分页查询
@Test
public void page(){
    //参数1,当前页,参数2:页面大小
    Page<Emps> page = new Page<>(1,5);
    empMapper.selectPage(page,null);
    page.getRecords().forEach(System.out::println);
}

条件构造器Wrapper

复杂sql可以使用条件构造器

@Test
public void contextLoads(){
    //查询create不为null,并且version=2的
    QueryWrapper<Emps> wrapper = new QueryWrapper<>();
    List<Emps> emps = empMapper.selectList(wrapper.isNotNull("create_time")
            .eq("version",2));
    emps.forEach(System.out::println);
}


@Test
public void test(){
    //姓名为八戒的
    QueryWrapper<Emps> wrapper = new QueryWrapper<>();
    System.out.println(empMapper.selectOne(wrapper.eq("ename", "八戒")));
}

@Test
public void test1() {
    //查询工资在5000-0000之间的用户
    QueryWrapper<Emps> wrapper = new QueryWrapper<>();
    wrapper.between("salary",5000,60000);
    Long aLong = empMapper.selectCount(wrapper);
    System.out.println(aLong);
}


@Test
public void test2() {
    //模糊查询
    QueryWrapper<Emps> wrapper = new QueryWrapper<>();
    //名字不包含八的
    wrapper.notLike("ename","八");
    //like包含
    empMapper.selectList(wrapper).forEach(System.out::println);
}

代码生成器

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

public class Code {
    public static void main(String[] args) {
        //需要构建一个 代码自动生成器 对象
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        //配置策略  
	//1、全局配置
    GlobalConfig gc = new GlobalConfig();
    String projectPath = System.getProperty("user.dir");
    gc.setOutputDir(projectPath + "/src/main/java");
    gc.setAuthor("ChanV");
    gc.setOpen(false);
    gc.setFileOverride(false);  //是否覆盖
    gc.setServiceName("%sService"); //去Service的I前缀
    gc.setIdType(IdType.ID_WORKER);
    gc.setDateType(DateType.ONLY_DATE);
    gc.setSwagger2(true);
    mpg.setGlobalConfig(gc);

    //2、设置数据源
    DataSourceConfig dsc = new DataSourceConfig();
    dsc.setUrl("jdbc:mysql://localhost:3306/mybatis-plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
    dsc.setDriverName("com.mysql.cj.jdbc.Driver");
    dsc.setUsername("root");
    dsc.setPassword("root");
    dsc.setDbType(DbType.MYSQL);
    mpg.setDataSource(dsc);

    //3、包的配置
    PackageConfig pc = new PackageConfig();
    pc.setModuleName("blog");
    pc.setParent("com.chanv");
    pc.setEntity("pojo");
    pc.setMapper("mapper");
    pc.setService("service");
    pc.setController("controller");
    mpg.setPackageInfo(pc);

    //4、策略配置
    StrategyConfig strategy = new StrategyConfig();
    strategy.setInclude("user");    //设置要映射的表名
    strategy.setNaming(NamingStrategy.underline_to_camel);
    strategy.setColumnNaming(NamingStrategy.underline_to_camel);
    strategy.setEntityLombokModel(true);    //自动lombok
    strategy.setLogicDeleteFieldName("deleted");
    //自动填充配置
    TableFill createTime = new TableFill("create_time", FieldFill.INSERT);
    TableFill updateTime = new TableFill("update_time", FieldFill.UPDATE);
    ArrayList<TableFill> tableFills = new ArrayList<>();
    tableFills.add(createTime);
    tableFills.add(updateTime);
    strategy.setTableFillList(tableFills);
    //乐观锁
    strategy.setVersionFieldName("version");
    strategy.setRestControllerStyle(true);
    strategy.setControllerMappingHyphenStyle(true);     //localhost:8080/hello_id_2
    mpg.setStrategy(strategy);

    mpg.execute();  //执行代码构造器
}
bleFill("create_time", FieldFill.INSERT);
    TableFill updateTime = new TableFill("update_time", FieldFill.UPDATE);
    ArrayList<TableFill> tableFills = new ArrayList<>();
    tableFills.add(createTime);
    tableFills.add(updateTime);
    strategy.setTableFillList(tableFills);
    //乐观锁
    strategy.setVersionFieldName("version");
    strategy.setRestControllerStyle(true);
    strategy.setControllerMappingHyphenStyle(true);     //localhost:8080/hello_id_2
    mpg.setStrategy(strategy);

    mpg.execute();  //执行代码构造器
}

你可能感兴趣的:(mybatis)