当前位置: 代码网 > it编程>编程语言>Java > springboot如何使用MybatisPlus

springboot如何使用MybatisPlus

2024年09月09日 Java 我要评论
mybatisplus帮助文档地址:代码生成器 | mybatis-plus导入相关依赖<!-- https://mvnrepository.com/artifact/com.baomidou/

 mybatisplus帮助文档地址:代码生成器 | mybatis-plus

 导入相关依赖

<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
        <dependency>
            <groupid>com.baomidou</groupid>
            <artifactid>mybatis-plus-boot-starter</artifactid>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupid>com.baomidou</groupid>
            <artifactid>mybatis-plus-generator</artifactid>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupid>org.freemarker</groupid>
            <artifactid>freemarker</artifactid>
            <version>2.3.28</version>
        </dependency>

第一个为mybatisplus的起步依赖,后面两个依赖是为逆向生成服务的。

 代码生成器

package cn.xzit.springbootmybatisplus;
import com.baomidou.mybatisplus.core.exceptions.mybatisplusexception;
import com.baomidou.mybatisplus.core.toolkit.stringpool;
import com.baomidou.mybatisplus.core.toolkit.stringutils;
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.tableinfo;
import com.baomidou.mybatisplus.generator.config.rules.namingstrategy;
import com.baomidou.mybatisplus.generator.engine.freemarkertemplateengine;
import java.util.arraylist;
import java.util.list;
import java.util.scanner;
/*该工具类用于生成实体类,mapper,service,controller
 * 用法:右键run该类,控制台输入表名,回车即可
 * */
/**
 * @author nobody
 */
public class codegenerator {
    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static string scanner(string tip) {
        scanner scanner = new scanner(system.in);
        system.out.println("请输入" + tip + ":");
        if (scanner.hasnext()) {
            string ipt = scanner.next();
            if (stringutils.isnotblank(ipt)) {
                return ipt;
            }
        }
        throw new mybatisplusexception("请输入正确的" + tip + "!");
    }
    public static void main(string[] args) {
        // 代码生成器
        autogenerator mpg = new autogenerator();
        // 全局配置
        globalconfig gc = new globalconfig();
        string projectpath = system.getproperty("user.dir");
        gc.setoutputdir(projectpath + "/src/main/java");
        gc.setauthor("jyz");
        gc.setopen(false);
        gc.setbaseresultmap(true);
        // gc.setswagger2(true); 实体属性 swagger2 注解
        mpg.setglobalconfig(gc);
        // 数据源配置
        datasourceconfig dsc = new datasourceconfig();
        dsc.seturl("jdbc:mysql://localhost:3306/mybatis?useunicode=true&usessl=false&characterencoding=utf8");
        // dsc.setschemaname("public");
        dsc.setdrivername("com.mysql.cj.jdbc.driver");
        dsc.setusername("root");
        dsc.setpassword("123456");
        mpg.setdatasource(dsc);
        // 包配置
        packageconfig pc = new packageconfig();
        //  pc.setmodulename(scanner("模块名"));
        pc.setparent("cn");/*生成的所有entity mapper等会放进主包里面*/
        pc.setentity("entity");
        pc.setmapper("mapper");
        pc.setservice("service");
        pc.setserviceimpl("service.impl");
        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 + "/src/main/resources/mapping/" + pc.getmodulename()
                        + "/" + tableinfo.getentityname() + "mapper" + stringpool.dot_xml;
            }
        });
/*        cfg.setfilecreate(new ifilecreate() {
            @override
            public boolean iscreate(configbuilder configbuilder, filetype filetype, string filepath) {
                // 判断自定义文件夹是否需要创建
                checkdir("调用默认方法创建的目录,自定义目录用");
                if (filetype == filetype.mapper) {
                    // 已经生成 mapper 文件判断存在,不想重新生成返回 false
                    return !new file(filepath).exists();
                }
                // 允许生成模板文件
                return true;
            }
        });*/
        cfg.setfileoutconfiglist(foclist);
        mpg.setcfg(cfg);
        // 配置模板
        templateconfig templateconfig = new templateconfig();
        // 配置自定义输出模板
        //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateconfig.setentity("templates/entity2.java");
        // templateconfig.setservice();
        // templateconfig.setcontroller();
        templateconfig.setxml(null);
        mpg.settemplate(templateconfig);
        // 策略配置
        strategyconfig strategy = new strategyconfig();
        strategy.setnaming(namingstrategy.underline_to_camel);
        strategy.setcolumnnaming(namingstrategy.underline_to_camel);
        //strategy.setsuperentityclass("你自己的父类实体,没有就不用设置!");
        strategy.setentitylombokmodel(true);
        strategy.setrestcontrollerstyle(true);
        // 公共父类
        //strategy.setsupercontrollerclass("你自己的父类控制器,没有就不用设置!");
        // 写于父类中的公共字段
        // strategy.setsuperentitycolumns("id");
        strategy.setinclude(scanner("表名,多个英文逗号分割").split(","));
        strategy.setcontrollermappinghyphenstyle(true);
        strategy.settableprefix(pc.getmodulename() + "_");
        mpg.setstrategy(strategy);
        mpg.settemplateengine(new freemarkertemplateengine());
        mpg.execute();
    }
}

 创建一个generator包,包下面创建一个codegenerator类,类中放以上的代码,修改其中的数据库名和用户名以及密码,右键运行。输入需要逆向生成的表名,多个表用逗号隔开,然后回车。

注意要修改主包,我的主包为cn,读者可以自行修改代码中的setparent中的内容。

配置文件.yml文件

server:
  port: 8080
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.driver
    url: jdbc:mysql://localhost:3306/mybatis?servertimezone=asia/shanghai&useunicode=true&characterencoding=utf-8&zerodatetimebehavior=converttonull&usessl=false&allowpublickeyretrieval=true
    username: root
    password: 123456
    hikari:
      connection-timeout: 6000
      maximum-pool-size: 5
#  jackson:
#    date-format: yyyy-mm-dd hh:mm:ss
#    time-zone: gmt+8
#    serialization:
#      write-dates-as-timestamps: false
mybatis-plus:
  configuration:
    #开启驼峰功能,数据库字段hello_world 实体类helloworld 也能对应匹配
    map-underscore-to-camel-case: true
    #结果集自动映射(resultmap)
    auto-mapping-behavior: full
    log-impl: org.apache.ibatis.logging.stdout.stdoutimpl
  mapper-locations: classpath*:mapping/*mapper.xml
  global-config:
    # 逻辑删除配置
    db-config:
      # 删除前
      logic-not-delete-value: 1
      # 删除后
      logic-delete-value: 0

到此这篇关于springboot使用mybatisplus的文章就介绍到这了,更多相关springboot使用mybatisplus内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com