MybaitsPlus入门使用

MyBaits-Plus

GitHub地址
有什么用
mybatis-plus是对Mybaits的增强,为我们提供好了一些CRUD的操作.
1.导入Mybaits-plus所需依赖

  • 尽量不要与Mybaits同时导入
 <!-- mybatis plus 代码生成器依赖 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.1</version>
        </dependency>
        <!--默认模板引擎-->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.2</version>
        </dependency>

编写配置文件

server:
  port: 8083
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/shiro?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver         #数据源,连接数据库
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl   #配置日志文件
  global-config:     #逻辑删除
    db-config:
      logic-delete-field: flag 		#全局逻辑删除字段
      logic-delete-value: 1			#逻辑已删除(默认为1)
      logic-not-delete-value: 0		#逻辑未删除(默认为0) 

POJO

package com.demo.pojo;

import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;


@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("user")
public class User {
    private Integer id;
    private String username;
    private String role;
    @TableField(fill = FieldFill.INSERT)//自动插入添加时间
    private Date createTime;
    @TableField(fill = FieldFill.INSERT_UPDATE)//自动插入添加时
    private Date updateTime;
    @Version
    private Integer version;
    @TableLogic           //逻辑删除
    private Integer deleted;
}

dao层
继承BaseMapper

package com.demo.dao;


import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.demo.pojo.User;

public interface UserMapper extends BaseMapper<User> {
}

config配置文件
此处乐观锁插件与分页插件后续会用到,主要是对dao层文件的扫MapperScan

package com.demo.config;

import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
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//自动管理事务
//扫描mapper文件夹
@MapperScan("com.demo.dao")
@Configuration//配置类
public class MyBatisPlusConfig {

    // 注册乐观锁插件
    @Bean
    public OptimisticLockerInterceptor
    optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }

    // 分页插件
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

此时Mybaits-plus的基础环境已经搭建好了

使用

  1. 注入dao层的对象,可以直接调用selectList方法查询所有,参数为Wrapper,先定义为null
    在这里插入图片描述
    方法扩展
方法名调用解释
insert()userMapper.insert(user);添加
updateById()userMapper.updateById(user);根据id更新
selectById()userMapper.selectById(1);根据Id查询
selectBatchIds()userMapper.selectBatchIds(Arrays.asList(1, 2));根据多个id查询
selectByMap()userMapper.selectByMap(map);条件查询,参数为map
selectPage()userMapper.selectPage(userPage, null).getRecords();分页查询,此时就需要config中的开启分页插件
deleteById()userMapper.deleteById(10);根据id删除
deleteBatchIds()userMapper.deleteBatchIds(Arrays.asList(12, 13));批量删除
deleteByMap()userMapper.deleteByMap(map);条件删除

自动填充
自动生成创建时间和更新时间,不需要手动维护

  1. 设计create_ time, update_time两个字段

  2.  @TableField(fill = FieldFill.INSERT)//自动插入添加时间
     private Date createTime;
     @TableField(fill = FieldFill.INSERT_UPDATE)//自动插入添加时
     private Date updateTime;
    
  3. 编写处理器去处理注解

package com.demo.util;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j//日志
@Component//被spring扫描,加到ioc容器中
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 insert fill...");
        this.setFieldValByName("updateTime", new Date(),
                metaObject);
    }


}

这样每次对数据做添加或者修改的话就会自动插入日期
逻辑删除
物理删除是直接从数据库中移除,逻辑删除是同过变量让字段失效

  1. 设计deleted字段
  2. @TableLogic private Integer deleted; 给属性加上该注解
  3. 配置yml文件,上文已配

调用删除方法,deleted字段为1的不能被查询出来,为0是没有被逻辑删除的数据

条件构造器
复杂的SQL使用条件构造器

// 条件构造器
QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();

在这里插入图片描述
条件构造器扩展方法

方法名说明
isNotNull(“name”)不为空的字段
ge("",null)大于等于
eq(“name”,"")相同
between(“name”,null,null)在,a与b之间
notLike(“name”,“3”)name不包含3的
likeRight(“name”,“a”)a开头的
inSql(“name”,“sql语句”)子查询
orderByDesc(“id”)根据id降序查询

代码生成器

package com.demo.util;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
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.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.ArrayList;

/**
 * @author zhangjian1
 * @date 2020/5/20
 */
// 代码自动生成器
public class AutomaticCodeCx {
    public static void main(String[] args) {
        // 需要构建一个代码自动生成器对象
        AutoGenerator mpg = new AutoGenerator();
        // 配置策略
        // 1、全局配置
        GlobalConfig gc = new GlobalConfig();
        // 获取当前父项目目录
        String projectPath = System.getProperty("user.dir");
        // 输出目录 要选择自己模块 如:projectPath + "/test_plus/src/main/java"
        gc.setOutputDir(projectPath + "/test_rabbitmq/src/main/java");
        // 设置作者名
        gc.setAuthor("YmEcJx");
        // 是否打开资源管理器
        gc.setOpen(false);
        gc.setFileOverride(false); // 是否覆盖
        gc.setServiceName("%sService"); // 去Service的I前缀
        // 主键类型
        gc.setIdType(IdType.ID_WORKER);
        // 日期类型
        gc.setDateType(DateType.ONLY_DATE);
        // 配置Swagger文档
        gc.setSwagger2(true);
        // 把配置丢到自动生成器里
        mpg.setGlobalConfig(gc);
/*//2、设置数据源 例子1:postgre 记得导postgre的驱动
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:postgresql://101.200.35.54:5432/Testing");
        dsc.setDriverName("org.postgresql.Driver");
        dsc.setUsername("postgres");
        dsc.setPassword("postgres2020");
        // 什么驱动
        dsc.setDbType(DbType.POSTGRE_SQL);
        mpg.setDataSource(dsc);*/
        // 例子2:mysql 记得导mysql的驱动
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/kjexam03?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai");
        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();
        // 在com.cx下,不设置就写空
        pc.setModuleName("");
        // 在什么包下
        pc.setParent("com.cx");
        // 实体类的名字 自己会生成,
/*        pc.setEntity("entity");
        pc.setMapper("mapper");
        pc.setService("service");
        pc.setServiceImpl("serviceImpl");
        pc.setController("controller");*/
        mpg.setPackageInfo(pc);
        // 4、策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setInclude("type"); // 设置要映射的表名
        // 设置包命名的规则
        strategy.setNaming(NamingStrategy.underline_to_camel);
        // 列的命名
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true); // 自动lombok;
        strategy.setLogicDeleteFieldName("deleted");
        // 自动填充配置 这里要对应自己的数据库里创建和更新时间的字段
        TableFill gmtCreate = new TableFill("create_time", FieldFill.INSERT);
        TableFill gmtModified = new TableFill("update_time", FieldFill.INSERT_UPDATE);
        // 创建集合,将策略添加
        ArrayList<TableFill> tableFills = new ArrayList<>();
        tableFills.add(gmtCreate);
        tableFills.add(gmtModified);
        strategy.setTableFillList(tableFills);
        // 乐观锁
        strategy.setVersionFieldName("version");
        // 驼峰命名
        strategy.setRestControllerStyle(true);
        // 跟controller层的字段,改为true请求就会LocaLhost: 8080/hello id 2,现在很多网站会使用下划线,驼峰不明确.
        strategy.setControllerMappingHyphenStyle(true);
        mpg.setStrategy(strategy);
        mpg.execute(); //执行
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值