MyBatis Plus

MyBatis Plus

国产的开源框架,基于MyBatis

核心功能就是简化MyBatis的开发,提高效率。

Mybatis Plus快速上手

SpringBoot+MyBatisPlus(国产的开原框架,并没有接入到Spring官方孵化器中)

  1. 创建maven工程

    image-20220122091140478

     

  2. pom.xml引入MybatisPlus的依赖

     <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.3.1</version>
    </dependency>
  3. 创建实体类

    package com.southwind.mybatisplus.entity;

    import lombok.Data;

    @Data
    public class User {
       private Integer id;
       private String name;
       private String age;
    }
  4. 创建Mapper接口

    package com.southwind.mybatisplus.mapper;

    import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    import com.southwind.mybatisplus.entity.User;

    public interface UserMapper extends BaseMapper<User>{
    }
  5. application.yml

    spring:
    datasource:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&characterEncoding=UTF-8
      username: root
      password: root
    mybatis-plus:
    configuration:
      log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

     

  6. 启动类需要添加@MapperScan("mapper所在的包"),否则无法加载Mapper Bean

    package com.southwind.mybatisplus;

    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;

    @SpringBootApplication
    @MapperScan("com.southwind.mybatisplus.mapper")
    public class MybatisplusApplication {

       public static void main(String[] args) {
           SpringApplication.run(MybatisplusApplication.class, args);
      }
    }
  7. 测试

    package com.southwind.mybatisplus.mapper;

    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;

    @SpringBootTest
    class UserMapperTest {
       @Autowired
       private UserMapper mapper;

       @Test
       void Test(){
           mapper.selectList(null).forEach(System.out::println);
      }
    }

常用注解

@TableName

映射数据库的表名

package com.southwind.mybatisplus.entity;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

@Data
@TableName("user")
public class Account {
   private Integer id;
   private String name;
   private String age;
}

@TableId

设置主键映射,value映射主键字段名

type设置主键类型,主键的生成策略,

AUTO, NONE, INPUT, ASSIGN_ID, ASSIGN_UUID, 
/**
* @deprecated
*/
@java.lang.Deprecated
ID_WORKER, /**
* @deprecated
*/
@java.lang.Deprecated
ID_WORKER_STR, /**
* @deprecated
*/
@java.lang.Deprecated
UUID;
描述
Auto 数据库自增
NONE MP set 主键,雪花算法实现
INPUT 需要开发者手动赋值
ASSIGN_ID MP分配ID,Long,Integer,String
ASSIGN_UUID 分配UUID,String

INPUT如果开发者没有手动赋值,则数据库通过自增的方式给主键赋值。前提是,数据库id设置自动递增。如果开发者手动赋值,则存入该值。

AUTO默认就是数据库自增,开发者无需赋值。

ASSIGN_ID MP 自动赋值,雪花算法。

ASSIGN_UUID 主键的数据类型必须是String,自动生成UUID进行赋值。

@TableField

映射非主键字段,value映射字段名

exist 表示是否为数据库字段false,如果实体类中的成员变量在数据库中没有对应的字段,则可以使用exit,VO、DTO用的比较多

select 表示是否查询该字段

fill表示是否自动填充,将对象存入到数据库的时候,由MyBatis Plus 自动给某些字段赋值,create_time、update_time

  1. 给表添加create_time、update_time

  2. 给实体类中添加变量

    package com.southwind.mybatisplus.entity;
    import com.baomidou.mybatisplus.annotation.*;
    import lombok.Data;
    import java.util.Date;

    @Data
    @TableName(value = "user")
    public class User {
       @TableId(type = IdType.ASSIGN_UUID)
       private String id;
       @TableField(value = "name",select = false)
       private String title;
       private Integer age;
       @TableField(exist = false)
       private String genner;
       @TableField(fill = FieldFill.INSERT)
       private Date createTime;
       @TableField(fill = FieldFill.INSERT_UPDATE)
       private Date updateTime;
    }
  3. 创建自动填充处理器

    package com.southwind.mybatisplus.handler;

    import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
    import org.apache.ibatis.reflection.MetaObject;
    import org.springframework.stereotype.Component;

    import java.util.Date;
    @Component
    public class MyMetaObjectHandler implements MetaObjectHandler {
       @Override
       public void insertFill(MetaObject metaObject) {
           this.setFieldValByName("createTime",new Date(),metaObject);
           this.setFieldValByName("updateTime",new Date(),metaObject);
      }

       @Override
       public void updateFill(MetaObject metaObject) {
           this.setFieldValByName("updateTime",new Date(),metaObject);
      }
    }

    @Version

    标记乐观锁,通过version字段来保证数据的安全性,当修改数据的时候,会以version作为条件,当条件成立的时候才会修改成功。

    version = 1

    线程1:update ... set version = 2 where version = 1

    线程2:update ... set version = 2 where version = 1

    1. 数据库表添加version字段,默认值为1

    2. 实体类添加 version 成员变量,并且添加@Version

      package com.southwind.mybatisplus.entity;
      import com.baomidou.mybatisplus.annotation.*;
      import lombok.Data;
      import java.util.Date;

      @Data
      @TableName(value = "user")
      public class User {
         @TableId(type = IdType.ASSIGN_UUID)
         private Long id;
         @TableField(value = "name",select = false)
         private String title;
         private Integer age;
         @TableField(exist = false)
         private String genner;
         @TableField(fill = FieldFill.INSERT)
         private Date createTime;
         @TableField(fill = FieldFill.INSERT_UPDATE)
         private Date updateTime;
         @Version
         private Integer version;
      }
    3. 注册配置类

      package com.southwind.mybatisplus.config;

      import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;

      @Configuration
      public class MyBatisPlusConfig {

         @Bean
         public OptimisticLockerInterceptor optimisticLockerInterceptor(){
             return new OptimisticLockerInterceptor();
        }
      }

      @EnumValue

      通用枚举类注解,将数据库字段映射成实体类的枚举类型成员变量

      package com.southwind.mybatisplus.enums;

      import com.baomidou.mybatisplus.annotation.EnumValue;

      public enum StatusEnum {
         WORK(1,"上班"),
         REST(0,"休息");

         StatusEnum(Integer code, String msg) {
             this.code = code;
             this.msg = msg;
        }
         @EnumValue
         private Integer code;
         private String msg;
      }
      package com.southwind.mybatisplus.entity;

      import com.baomidou.mybatisplus.annotation.*;
      import com.southwind.mybatisplus.enums.StatusEnum;
      import lombok.Data;

      import java.util.Date;

      @Data
      @TableName(value = "user")
      public class User {
         @TableId(type = IdType.ASSIGN_UUID)
         private Long id;
         @TableField(value = "name",select = false)
         private String title;
         private Integer age;
         @TableField(exist = false)
         private String genner;
         @TableField(fill = FieldFill.INSERT)
         private Date createTime;
         @TableField(fill = FieldFill.INSERT_UPDATE)
         private Date updateTime;
         @Version
         private Integer version;
         private StatusEnum status;
      }

      Application.yml

      type-enums-package:
      com.southwind.mybatisplus.enums

      2、实现接口

      package com.southwind.mybatisplus.enums;

      import com.baomidou.mybatisplus.annotation.IEnum;

      public enum AgeEnum implements IEnum<Integer> {
         WCN(14,"未成年"),
         CN(19,"成年人");

         @Override
         public String toString() {
             return msg;
        }

         AgeEnum(Integer code, String msg) {
             this.code = code;
             this.msg = msg;
        }

         private Integer code;
         private String msg;

         @Override
         public Integer getValue() {
             return this.code;
        }
      }

    @TableLogic

    1. 数据表添加deleted字段

    2. 实体类添加注解

      package com.southwind.mybatisplus.entity;

      import com.baomidou.mybatisplus.annotation.*;
      import com.southwind.mybatisplus.enums.AgeEnum;
      import com.southwind.mybatisplus.enums.StatusEnum;
      import lombok.Data;

      import java.util.Date;

      @Data
      @TableName(value = "user")
      public class User {
         @TableId(type = IdType.ASSIGN_UUID)
         private Long id;
         @TableField(value = "name",select = false)
         private String title;
         private AgeEnum age;
         @TableField(exist = false)
         private String genner;
         @TableField(fill = FieldFill.INSERT)
         private Date createTime;
         @TableField(fill = FieldFill.INSERT_UPDATE)
         private Date updateTime;
         @Version
         private Integer version;
         private StatusEnum status;
         @TableLogic
         private Integer deleted;
      }
    3. application.yml添加配置

       global-config:
      db-config:
        logic-not-delete-value: 0
        logic-delete-value: 1

    查询

     //mapper.selectList(null);
           QueryWrapper wrapper = new QueryWrapper();

           // 多条件查询 name = ? and age = ?
    //       Map<String,Object> map = new HashMap<>();
    //       map.put("name","老八秘制小汉堡");
    //       map.put("age",14);
    //       wrapper.allEq(map);

           //age < ?
    //       wrapper.lt("age",19);

        //age <= ?
    //       wrapper.le("age",19);

           //age > ?
    //       wrapper.gt("age",10);

        //age >= ?
    //       wrapper.ge("age",20);

           // name != ?
    //       wrapper.ne("name","老八秘制小汉堡");

        // age >= ? and age <= ?
    //       wrapper.between("age",11,40);

           // ! age >= ? and age <= ?
    //       wrapper.notBetween("age",11,40);
           // like '% ? %'
    //       wrapper.like("name","!");

           // not like '% ? %'
    //       wrapper.notLike("name","12");

           // name like '% ?'
    //       wrapper.likeLeft("name","!");

           // name like '? %'
    //       wrapper.likeRight("name","苍");

           // ? is null
    //       wrapper.isNull("age");

           // ? is not null
    //       wrapper.isNotNull("age");

           //inSql
    //       wrapper.inSql("id","select id from user where id < 10");
    //       wrapper.inSql("age","select age from user where age < 21");

    //       wrapper.orderByAsc("age");
    //       wrapper.having("id < 10");
           mapper.selectList(wrapper).forEach(System.out::println);
    //        System.out.println(mapper.selectById(2));
    //       mapper.selectBatchIds(Arrays.asList(1,2)).forEach(System.out::println);

           //Map 只能做等值判断,逻辑判断需要使用 Wrapper 来处理
    //       Map<String,Object> map = new HashMap<>();
    //       map.put("id",1);
    //       mapper.selectByMap(map).forEach(System.out::println);

           QueryWrapper wrapper = new QueryWrapper();
           wrapper.lt("id",2);
    //       System.out.println(mapper.selectCount(wrapper));

           //将查询的结果集封装到Map中
    //       mapper.selectMaps(wrapper).forEach(System.out::println);
    //       System.out.println("----------------------------------");
    //       mapper.selectList(wrapper).forEach(System.out::println);

           //分页查询
    //       Page<User> page = new Page<>(2,2);
    //       Page<User> result = mapper.selectPage(page,null);
    //       System.out.println(result.getSize());
    //       System.out.println(result.getTotal());
    //       result.getRecords().forEach(System.out::println);

    //       Page<Map<String,Object>> page = new Page<>(2,2);
    //       mapper.selectMapsPage(page,null).getRecords().forEach(System.out::println);

    //       mapper.selectObjs(null).forEach(System.out::println);

           System.out.println(mapper.selectOne(wrapper));

    自定义SQL(多表关联查询)

    package com.southwind.mybatisplus.entity;

    import lombok.Data;

    @Data
    public class ProductVo {
       private Integer category;
       private Integer count;
       private String description;
       private Long userId;
       private String userName;
    }
    package com.southwind.mybatisplus.mapper;

    import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    import com.southwind.mybatisplus.entity.ProductVo;
    import com.southwind.mybatisplus.entity.User;
    import org.apache.ibatis.annotations.Select;

    import java.util.List;

    public interface UserMapper extends BaseMapper<User>{
       @Select("select p.*,u.name userName from product p,user u where p.user_id = u.id and u.id = #{id};")
       List<ProductVo> productList(Long id);
    }

    添加

    User user = new User();
    user.setTitle("奥利给!");
    user.setAge(19);
    mapper.insert(user);

    删除

    //        mapper.deleteById(1);
    //       mapper.deleteBatchIds(Arrays.asList(1L,2L));
    //       QueryWrapper wrapper = new QueryWrapper();
    //       wrapper.eq("age",19);
    //       mapper.delete(wrapper);
           Map<String,Object> map = new HashMap<>();
           map.put("age",21);
           mapper.deleteByMap(map);

    修改

    //        User user = mapper.selectById(1);
    //       user.setTitle("战胜恐惧最好的办法就是面对恐惧,加油!奥利给!");
    //       mapper.updateById(user);
           User user = mapper.selectById(1485060035716374529L);
           user.setTitle("求芭比毛宁宁");
           QueryWrapper wrapper = new QueryWrapper();
           wrapper.eq("age",31);
           mapper.update(user,wrapper);

    MyBatisPlus自动生成

    根据数据表自动生成实体类、mapper、service、serviceImpl、controller

    1. pom.xml导入MyBatis Plus Generator

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

      <dependency>
          <groupId>org.apache.velocity</groupId>
          <artifactId>velocity</artifactId>
          <version>1.7</version>
      </dependency>

      velocity(默认)、Freemarker、Beetl

      package com.southwind.mybatisplus;

      import com.baomidou.mybatisplus.annotation.DbType;
      import com.baomidou.mybatisplus.generator.AutoGenerator;
      import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
      import com.baomidou.mybatisplus.generator.config.GlobalConfig;
      import com.baomidou.mybatisplus.generator.config.PackageConfig;
      import com.baomidou.mybatisplus.generator.config.StrategyConfig;
      import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

      public class Main {
         public static void main(String[] args) {
             //创建generator对象
             AutoGenerator autoGenerator = new AutoGenerator();
             //创建数据源
             DataSourceConfig dataSourceConfig = new DataSourceConfig();
             dataSourceConfig.setDbType(DbType.MYSQL);
             dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8");
             dataSourceConfig.setUsername("root");
             dataSourceConfig.setPassword("root");
             dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
             autoGenerator.setDataSource(dataSourceConfig);
             //全局配置
             GlobalConfig globalConfig = new GlobalConfig();
             globalConfig.setOutputDir(System.getProperty("user.dir")+"/src/main/java");
             globalConfig.setOpen(false);
             globalConfig.setServiceName("%sService");
             globalConfig.setAuthor("石智韬");
             autoGenerator.setGlobalConfig(globalConfig);

             //包信息
             PackageConfig packageConfig = new PackageConfig();
             packageConfig.setParent("com.southwind.mybatisplus");
             packageConfig.setModuleName("generator");
             packageConfig.setController("controller");
             packageConfig.setService("service");
             packageConfig.setServiceImpl("service.impl");
             packageConfig.setMapper("mapper");
             packageConfig.setEntity("entity");
             autoGenerator.setPackageInfo(packageConfig);

             //配置策略
             StrategyConfig strategyConfig = new StrategyConfig();
             strategyConfig.setEntityLombokModel(true);
             strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
             autoGenerator.setStrategy(strategyConfig);

             autoGenerator.execute();

        }
      }
    2.  

posted @ 2022-01-24 09:11  將錯  阅读(29)  评论(0)    收藏  举报