MyBatis-Plus(狂神)

一.特点

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

二.快速入门

官网地址:MyBatis-Plus

按照官方文档实现步骤:

1.首先我们创建数据库和表:

CREATE DATABASE mybatis_plus;
USE mybatis_plus;

DROP TABLE IF EXISTS USER;

CREATE TABLE USER
(
    id BIGINT(20) NOT NULL COMMENT '主键ID',
    NAME VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
    age INT(11) NULL DEFAULT NULL COMMENT '年龄',
    email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
    PRIMARY KEY (id)
);

DELETE FROM USER;

INSERT INTO USER (id, NAME, age, email) VALUES
(1, 'Jone', 18, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');

 2.创建一个springboot项目只需要添加web支持然后导入依赖:

    尽量不要同时导入mybatis和mybatis-plus因为版本有差异!

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.0.5</version>
        </dependency>

 3.连接数据库和mybatis相同

# mysql 5 驱动不同  com.mysql.jdbc.Driver
# mysql 8 驱动不同 com.mysql.cj.jdbc.Driver . 需要增加时区的配置 serverTimezone=GMT%2B8
# DataSource Config
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
    username: root
    password: 201408181

4.编写我们的dao层的User类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;

}

 5.编写我们的mapper接口

//使用mybatis-plus后我们不用在写xml文件了,所有CRUD操作都已经编写完成了
// 在对应的mapper上面继承基本的类 BaseMapper
@Reference
public interface UserMapper extends BaseMapper<User> {

}

6.在主启动类MybatisPlusApplication上扫描我们Mapper包下的所有接口

@MapperScan("com.jiu.mapper")

7.测试类中测试


    @Autowired
    private UserMapper userMapper;

    @Test
    void contextLoads() {
        //参数是一个Wrapper , 条件构造器,这里我们先不用 null
        //查询全部用户
        List<User> users = userMapper.selectList(null);
        users.forEach(System.out::println);
    }

三.配置日志

# 配置日志  (默认控制台输出)
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

再次测试就会输入配置文件

四.CRUD扩展 

1.查询操作

  • 查询一个数据
    @Test
    public void testSelectById() {
        //查询一个数据
        User user = userMapper.selectById(1L);
        System.out.println(user);

    }
  • 查询多个数据 
    @Test
    public void testSelectBatchIds() {;
        //查询多个数据
        List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
        users.forEach(System.out::println);
    }
  • 条件查询 
    @Test
    public void testSelectBatchId() {;
        //条件查询
        HashMap<String, Object> map = new HashMap<>();
        map.put("name","白泽");
        map.put("age",20);
        List<User> users = userMapper.selectByMap(map);
        users.forEach(System.out::println);
    }

2.插入数据

  @Test
    public void testInsert() {
        User user = new User();
        user.setName("jiuqi");
        user.setAge(19);
        user.setEmail("[email protected]");
        int result = userMapper.insert(user);
        System.out.println(result);
        System.out.println(user);
    }

3.主键生成策略

  • 分布式系统唯一id生成: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.几乎全球唯一

  • 在实体类上加@TableId(type = IdType.ID_WORKER)     全局唯一id对应数据库中的主键(uuid.自增id.雪花算法.redis.zookeeper)  这是默认生成的id
  • 在实体类上加入@TableId(type = IdType.AUTO)             主键自增,当然我们数据库对应字段一定要是自增
  • 在实体类上加入@TableId(type = IdType.INPUT)            手动输入,我们需要手动添加否则为null,当我们不添加任何注解是手动添加id也能成功,如果使用上面俩个注解手动添加无效

4.更新数据 

     sql语句是动态sql

  @Test
    public void testUpdate() {
        User user = new User();
        user.setId(6L);
        user.setName("九七哟");
        user.setAge(20);
        user.setEmail("[email protected]");
        userMapper.updateById(user);          //updateById()参数是 一个对象!
    }

5.自动填充

阿里巴巴开发手册:所有的数据库表:gmt_create .gmt_modified几乎所有的表都要配置上!而且需要自动化!

第一种方法:我们需要在数据库新增对应字段(一般不使用)

 在实体类上也要加上新增的字段

private Date createTime;
private Date updateTime;

 第二种方法:在代码上修改

  • 删除数据库默认值取消更新 ​​​​​​
  •  实体类上加上注解
    @TableField(fill = FieldFill.INSERT)
    private Date creatseTime;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
  •  创建handler包写MyMetaObjectHandler类
    import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.ibatis.reflection.MetaObject;
    import org.springframework.stereotype.Component;
    import java.util.Date;
    
    @Slf4j
    @Component
    public class MyMetaObjectHandler implements MetaObjectHandler {
        @Override
        public void insertFill(MetaObject metaObject) {
            log.info("start insert fill ....");
            this.setFieldValByName("createTime",new Date(),metaObject);
            this.setFieldValByName("updateTime",new Date(),metaObject);
        }
    
        @Override
        public void updateFill(MetaObject metaObject) {
            log.info("start update fill ....");
            this.setFieldValByName("updateTime",new Date(),metaObject);
        }
    }
    

6.乐观锁悲观锁

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

悲观锁;顾名思义十分悲观,他总是认为出现问题,无论干什么都会上锁!再去操作!

乐观锁实现方式:

  • 取出记录时,获取当前version
  • 更新时,带上这个version
  • 执行更新时,set version = newVersion where version = oldVersion
  • 如果version不对,就更新失败

测试下乐观锁

  • 给数据库添加version 

  •   给我们实体类加上version
    @Version
    private int version;
  •  注册组件   我们新建config包写MyBatisPlusConfig类,这是配置类我们可以把读取mapper文件的注解拿过来@MapperScan("com.jiu.mapper")
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@EnableTransactionManagement   //自动管理事务,默认开启可以不用写
@MapperScan("com.jiu.mapper")  //这是配置类我们可以把读取mapper文件的注解拿过来
@Configuration
public class MyBatisPlusConfig {
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
       return new OptimisticLockerInterceptor();
    }
}

7.分页查询

  • 配置类上添加配置
 //分页插件
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
  • 测试
    @Test
    public void testPage() {
        Page<User> page = new Page<>(2, 5);
        userMapper.selectPage(page, null);
        page.getRecords().forEach(System.out::println);
        System.out.println(page.getTotal());  //获取查询的总数
    }

8.删除操作和查询操作一样,把select换成delete就行

9.逻辑删除

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

逻辑删除: 在数据库中没有被移除,而是通过一个变量来让他失效! deleted=0=>deleted=1,执行的是一个update操作再次查询也没有这个数据,管理员可以查看被删除的记录!防止数据的丢失,类似于回收站!

  • 首先我们在数据库表上填上我们要测试的数据

  •  实体类加上delete
    @TableLogic
    private Integer del;

  • 配置类中添加配置 
//注册逻辑删除
@Bean
public ISqlInjector sqlInjector(){
    return new LogicSqlInjector();
}
  •  yaml加添加配置
# 配置日志  (默认控制台输出)
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    # 配置逻辑删除
  global-cb-config:
      logic-delete-value: 1
      logic-not-delete-value: 0

五.性能分析插件

  • 配置开发环境 
spring:
  profiles:
    active: dev
  •  导入插件
 @Bean
    @Profile({"dev","test"})                                  //设置dev 和 test环境开启
    public PerformanceInterceptor performanceInterceptor(){
        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
        performanceInterceptor.setMaxTime(100);                //设置sql执行的最大时间,超过则不执行
        performanceInterceptor.setFormat(true);
        return performanceInterceptor;
    }

 六.条件构造器

@SpringBootTest
public class WrapperTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    void contextLoads() {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper
                .isNotNull("email")            //查询邮箱不为空
                .isNotNull("name")            //查询名字不为空
                .ge("age",20);            //查询年龄大于20的

        userMapper.selectList(wrapper).forEach(System.out::println);
    }

    @Test
    public void test2() {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("name","九七");    //名字等于九七的
        List<User> users = userMapper.selectList(wrapper);
                users.forEach(System.out::println);
    }
    @Test
    public void test3() {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.between("age",20,30);   //年龄在20到30之间
        List<User> users = userMapper.selectList(wrapper);
        users.forEach(System.out::println);
    }

    @Test
    public void test4() {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like("name","九");          //名字中带有九的
        List<User> users = userMapper.selectList(wrapper);
        users.forEach(System.out::println);
    }

    @Test
    public void test5() {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.notLike("name","九");          //名字中不含有九的
        List<User> users = userMapper.selectList(wrapper);
        users.forEach(System.out::println);
    }

    @Test
    public void test6() {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.likeRight("email","t");          //邮箱以t开头的
        List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);
        maps.forEach(System.out::println);
    }

    @Test
    public void test7(){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.inSql("id","select id from user where id<3");  //id在子查询中查出来
        List<Object> objects = userMapper.selectObjs(wrapper);
        objects.forEach(System.out::println);
    }
    @Test
    public void test8(){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("id");               //通过id进行排序
        List<Object> objects = userMapper.selectObjs(wrapper);
        objects.forEach(System.out::println);
    }
}

 七.代码自动生成

 这是老版本,新版本可以去官网看

导入依赖

       <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.0.5</version>
        </dependency>

        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.0</version>
        </dependency>
public class CodeTest {
    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("九七");                                   //设置作者名字
        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("201408181");
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);

        //3、包的配置
        PackageConfig pc = new PackageConfig();
        //只需要改实体类名字 和包名 还有 数据库配置即可
        pc.setModuleName("blog");    //设置模块
        pc.setParent("com.jiu");     //存放的位置
        pc.setEntity("entity");      //实体类名字
        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 gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
        TableFill gmtModified = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE);
        ArrayList<TableFill> tableFills = new ArrayList<>();
        tableFills.add(gmtCreate);
        tableFills.add(gmtModified);
        strategy.setTableFillList(tableFills);

        // 乐观锁
        strategy.setVersionFieldName("version");
        strategy.setRestControllerStyle(true);
        strategy.setControllerMappingHyphenStyle(true);        // localhost:8080/hello_id_2
        mpg.setStrategy(strategy);
        mpg.execute(); //执行
    }
}

猜你喜欢

转载自blog.csdn.net/qq_51923226/article/details/129440574