MyBatis Plus配置以及使用

1、MyBatais Plus安装(只能手动安装

在java文件目录下找到pom.xml,配置如下字段

 <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.1.tmp</version>
</dependency>

然后刷新Maven

2、MyBatis Plus数据库配置文件

server:
  port: 8888//端口号
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver//数据库类型
    url: jdbc:mysql://127.0.0.1:3306/springboot?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC//数据库链接地址
    username: root//数据库账号
    password: password//数据库密码
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl//打印Sql语句

3、创建对象文件,此时需要跟数据库表明保持一致,即首字母大写

image.png
package com.ybwork.mybitsplus.entity;

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

@Data
public class User {
    private Integer id;
    private String name;
    private String address;
    private String password;
}

4、创建Mapper接口文件,继承BaseMapper

package com.ybwork.mybitsplus.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ybwork.mybitsplus.entity.User;

public interface UserMapper extends BaseMapper<User> {

}

并在Application中添加扫描MapperScan,将下图红色框内字符串拼接起来即Mapper文件夹的路径


image.png
@MapperScan("com.xxx.xxx.mapper")

5、编写测试用例

package com.xxx.xxx.mapper;

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

import static org.junit.jupiter.api.Assertions.*;

@SpringBootTest
class AccountMapperTest {

    @Autowired
    private UserMapper mapper;

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

6、MyBatis Plus注解


@TabbleName

用法

@TableName(value = "user")

作用:

修改映射表名

package com.ybwork.mybitsplus.entity;

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

@Data
@TableName(value = "user")
public class Account {
    private Integer id;
    private String name;
    private String address;
    private String password;
}


@TableId

用法

修改主键字段映射
value设置字段名
type设置主键类型,type值为IdType(枚举)

public enum IdType {
    AUTO(0),
    NONE(1),
    INPUT(2),
    ASSIGN_ID(3),
    ASSIGN_UUID(4),
//已下三种已弃用,无需处理
    /** @deprecated */
    @Deprecated
    ID_WORKER(3),
    /** @deprecated */
    @Deprecated
    ID_WORKER_STR(3),
    /** @deprecated */
    @Deprecated
    UUID(4);

    private final int key;

    private IdType(int key) {
        this.key = key;
    }

    public int getKey() {
        return this.key;
    }
}
描述
AUTO 主键自增,无需开发者处理
NONE MP根据雪花算法自动生成,无需开发者处理(默认)
INPUT 开发者手动赋值,没有赋值的情况下等同默认效果
ASSIGN_ID MP自动赋值,类型为Long,String
ASSIGN_UUID MP自动赋值,类型只能为String
public class User {
    @TableId(type = IdType.ASSIGN_ID)
    private Long id;
    @TableField(value = "name",select = false)
    private String userName;
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
}

@TableField

用法

    @TableField(value = "name",select = false)

作用

修改非主键字段映射
value设置字段名
select设置是否查询
exist是否是数据库字段
fill是否字段填充数据(create_time,update_time)

fill使用

  • 生成实体类属性
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
  • 数据库添加对应字段
  • 重写自动填充方法
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);
    }
}
  • 测试
@Test
    void save(){
        User user = new User();
        user.setUserName("TableFill");
        mapper.insert(user);
    }

    @Test
    void updateById(){
        User user = mapper.selectById(1);
        user.setUserName("C罗");
        mapper.updateById(user);
    }

@Version

用法

  • 在数据库添加version字段
  • 在实体类中添加version字段并且添加@version注解
public class User {
    @TableId(type = IdType.ASSIGN_ID)
    private Long id;
    @TableField(value = "name",select = false)
    private String userName;
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
    @Version
    private Integer version;
}
@Configuration
public class MyBatisPlusConfig {
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor(){
        return new OptimisticLockerInterceptor();
    }
}

作用

保证同一时间内该数据只能被修改一次

@EnumValue

用法

  • 创建枚举类,并添加注释
public enum UserStatusEnums {
    WAIT_CHECK(1,"待审核"),
    CHECK_YES(2,"已通过"),
    CHECY_NO(3,"已拒绝");


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

    @EnumValue
    private Integer code;
    private String msg;
}
  • 在实体类中添加枚举字段
public class User {
    @TableId(type = IdType.ASSIGN_ID)
    private Long id;
    @TableField(value = "name",select = false)
    private String userName;
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
    @Version
    private Integer version;
    private UserStatusEnums userStatus;
}
  • 在YML文件中配置enums路径
  type-enums-package:
    com.xxx.xxx.enums

作用

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

枚举也可以通过实现接口的方式使用枚举

public enum UserStatusEnums implements IEnum<Integer> {
    WAIT_CHECK(1,"待审核"),
    CHECK_YES(2,"已通过"),
    CHECY_NO(3,"已拒绝");


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

    private Integer code;
    private String msg;

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

@TableLogic

用法

  • 数据表添加删除字段
  • 实体类添加字段以及注解
  • 在YML文件文件中添加配置
  global-config:
    db-config:
      logic-not-delete-value: 0
      logic-delete-value: 1

作用

映射逻辑删除


7、数据库操作

查询

  • 不添加任何条件查询
 //不添加任何条件查询
 mapper.selectList(null).forEach(System.out::println);
  • 单条件查询
QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("name","333");
mapper.selectList(wrapper).forEach(System.out::println);
  • 多条件查询
//多条件查询
QueryWrapper wrapper = new QueryWrapper();
Map<String,Object> map = new HashMap<>();
map.put("name","333");
map.put("phone","11111111111");
wrapper.allEq(map);
mapper.selectList(wrapper).forEach(System.out::println);
  • wraper部分属性
描述
gt 大于筛选条件
lt 小于筛选条件
ne 不等于筛选条件
ge 大于等于筛选条件
le 小于等于筛选条件
orderByAsc 升序
orderByDesc 降序
like 模糊查询
likeLeft 以查询参数结尾的
likeRight 以查询参数开头的

MP条件构造器官方文档

  • 联合查询
QueryWrapper wrapper = new QueryWrapper();
wrapper.inSql("id","select id from user where id > 2");
wrapper.inSql("name","select name from user where name = '333'");
mapper.selectList(wrapper).forEach(System.out::println);
  • 分页查询
//分页查询
        Page<User> page = new Page<>(1,2);
        Page<User> result =  mapper.selectPage(page,null);
        System.out.println(result.getSize());
        System.out.println(result.getTotal());
        result.getRecords().forEach(System.out::println);

添加

User user = new User();
        user.setUserName("TableFill");
        mapper.insert(user);

删除

 //通过id删除
        mapper.deleteById(5);

        //通过wrapper删除,选择器跟查询一致
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.gt("id",2);
        mapper.delete(wrapper);

        //通过map删除
        Map<String,Object> map = new HashMap<>();
        map.put("id",1);
        mapper.deleteByMap(map);

        //多个ID删除
        mapper.deleteBatchIds(Arrays.asList(1,2));

修改

User user = new User();
        user.setId(3);
        user.setUserName("updata");

        mapper.updateById(user);

自定义SQL、多表关联

@Select("SELECT d.*,u.name user_name FROM device d,user u WHERE d.user_id = u.id and u.id = #{id}")
    List<DeviceVO> deviceList(Integer id);

8、MyBatis Plus自动生成

<dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.1.tmp</version>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.7</version>
//数据源
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setUrl("jdbc:mysql://127.0.0.1:3306/springboot?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC");
        dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
        dataSourceConfig.setUsername("root");
        dataSourceConfig.setPassword("wyb123456");

        //全局配置
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java");//获取工程路径
        globalConfig.setOpen(false);//是否打开创建好的文件
        globalConfig.setAuthor("wyb");//作者

        //包信息
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setParent("com.ybwork.mybitsplus");//设置软件包路径
        packageConfig.setModuleName("generator");//设置generator 存放位置
        packageConfig.setController("contorller");//设置contorller存放位置
        packageConfig.setService("service");//接口存放位置
        packageConfig.setServiceImpl("service.impl");//impl路径
        packageConfig.setEntity("entity");//实体类存放位置
        packageConfig.setMapper("mapper");//mapper存放位置

        //配置策略
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig.setEntityLombokModel(true);//自动生成Lombok注解
        strategyConfig.setNaming(NamingStrategy.underline_to_camel);//设置字段名 下划线转驼峰
        strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);//设置字段名 下划线转驼峰

        //创建generator对象
        AutoGenerator generator = new AutoGenerator();
        generator.setDataSource(dataSourceConfig);//配置数据源
        generator.setGlobalConfig(globalConfig);//设置全局配置
        generator.setPackageInfo(packageConfig);//配置包信息
        generator.setStrategy(strategyConfig);//配置策略

        generator.execute();//执行

9、Spring Boot + MyBatis Plus 打包应用发布

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容