MyBatis-Plus的使用、代码生成器

官网:

简介 | MyBatis-Plus (baomidou.com)https://baomidou.com/pages/24112f/

MyBatis-Plus:为简化开发而生,对Mybatis封装,简化操作

是一个 MyBatis的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

特点:

1.自动实现单表的CRUD

2.注解:简化代码

3.分页插件

4.条件查询的封装

5.逆向生成工具(代码生成器)

具体实现操作:

1、导入Jar包

<!--        Mybatis-plus 封装了Mybatis 简化,Mybatis-plus和Mybatis包不可重复导入-->
<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>mybatis-plus-boot-starter</artifactId>
  <version>3.4.3.4</version>
</dependency>

2、使用分页插件

@Configuration
public class MybatisConfig {
    @Bean
    public MybatisPlusInterceptor createInterceptor(){
        MybatisPlusInterceptor interceptor=new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }
}

3、代码生成器

  1. 使用插件Easy Code,在file->setting->plugins中下载,另推荐插件MybatisX(快速开发神器)配合使用
  2. 官方推荐,如下封装工具类

导入依赖:

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.velocity/velocity-engine-core -->
        <!--        velocity模板引擎,mybatis-plus代码生成器需要-->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.3</version>
        </dependency>

 封装工具类:

package com.example.pageDemo.business.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.ArrayList;
import java.util.List;

public class MybatisPlusCode {
    public static void main(String[] args) { // 需要构建一个 代码自动生成器 对象
        AutoGenerator mpg = new AutoGenerator(); // 配置策略
        // 1、全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath+"/business/src/main/java");
        gc.setAuthor("sll");
        gc.setOpen(false);
        gc.setFileOverride(false); // 是否覆盖
        gc.setServiceName("%sService"); // 去Service的I前缀
        gc.setIdType(IdType.AUTO);
        gc.setDateType(DateType.ONLY_DATE);
        gc.setSwagger2(true);
        mpg.setGlobalConfig(gc);
        //2、设置数据源
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:postgresql://localhost:3306/lu?characterEncoding=utf8&useSSL=false");
        dsc.setDriverName("org.postgresql.Driver");
        dsc.setUsername("postgres");
        dsc.setPassword("postgres@123");
        dsc.setDbType(DbType.POSTGRE_SQL);

//        dsc.setUrl("jdbc:mysql://localhost:3306/lu?useUnicode=true&useSSL=false&characterEncoding=UTF-8&serverTimezone=UTC");
//        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
//        dsc.setUsername("root");
//        dsc.setPassword("123456");
//        dsc.setDbType(DbType.MYSQL);

        mpg.setDataSource(dsc);
        //3、包的配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName("business");   //模块名
        pc.setParent("com.example.pageDemo");    //生成com.sll.demo
        pc.setEntity("model");
        pc.setMapper("mapper");
        pc.setService("service");
        pc.setController("controller");
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 freemarker
//        String templatePath = "/templates/mapper.xml.ftl";
//         如果模板引擎是 velocity
        String templatePath = "/templates/mapper.xml.vm";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return projectPath + "/business/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);



        //4、策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setInclude("report_management","company"); // 设置要映射的表名,可以有多个(用逗号隔开)
        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(); //执行
    }

}

4、条件构造器QueryWrapper

详细操作参考官方文档:

条件构造器 | MyBatis-Plus (baomidou.com)


        //1.实例化条件构造器对象  底层-动态SQL
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        //2.设置查询条件
        queryWrapper.eq("name",name);//=
        queryWrapper.or().gt("age",age);//>
        queryWrapper.orderByDesc("id");//设置排序
  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值