当前位置: 移动技术网 > IT编程>开发语言>Java > SpringBoot整合MybatisPlus的简单教程实现(简单整合)

SpringBoot整合MybatisPlus的简单教程实现(简单整合)

2019年07月19日  | 移动技术网IT编程  | 我要评论

最近在研究springboot,顺便就会看看数据库连接这一块的知识 ,所以当我发现有通用mapper和mybatisplus这两款网络上比较火的简化mybatis开发的优秀软件之后。就都想试一下,看看哪一款比较适合自己。

先创建一个springboot的项目,可以参考我之前的文章spring boot 的简单教程(一) spring boot 项目的创建

创建好springboot之后就需要整合mybatis和mybatis-plus了。

打开pom.xml文件,将最新的mybatis相关的包都引用进来。

    <!-- 这是mysql的依赖 -->
    <dependency>
      <groupid>mysql</groupid>
      <artifactid>mysql-connector-java</artifactid>
      <scope>runtime</scope>
    </dependency>
    <!-- 这是lombok的依赖 -->
    <dependency>
      <groupid>org.projectlombok</groupid>
      <artifactid>lombok</artifactid>
      <optional>true</optional>
    </dependency>
    <!-- 这是mybatis-plus依赖 -->
    <dependency>
      <groupid>com.baomidou</groupid>
      <artifactid>mybatis-plus-boot-starter</artifactid>
      <version>3.1.1</version>
    </dependency>
    <!-- 这是mybatis-plus的代码自动生成器 -->
    <dependency>
      <groupid>com.baomidou</groupid>
      <artifactid>mybatis-plus-generator</artifactid>
      <version>3.1.1</version>
    </dependency>
    <!-- 这是模板引擎依赖 -->
    <dependency>
      <groupid>org.freemarker</groupid>
      <artifactid>freemarker</artifactid>
      <version>2.3.28</version>
    </dependency>

需要对application.yml进行相关的配置。

  #端口号
  server:
   port: 8088
  #数据库的配置信息
  spring:
   datasource:
    url: jdbc:mysql://localhost:3306/*** #自己的数据库名称
    username: root
    password: 123456
  mybatis:
   #开启驼峰命名法
   configuration:
    map-underscore-to-camel-case: true
  mybatis-plus:
   # xml地址
   mapper-locations: classpath:mapper/*mapper.xml
   # 实体扫描,多个package用逗号或者分号分隔
   type-aliases-package: ***  #自己的实体类地址
   configuration:
    # 这个配置会将执行的sql打印出来,在开发或测试的时候可以用
    log-impl: org.apache.ibatis.logging.stdout.stdoutimpl

自动生成模块的方法,在相应的位置上添加上自己的一些包名就可以运行生成相应的entity、mapper、mapper xml、service、controller 等各个模块的代码。

public class codegenerator {

  /**
   * <p>
   * 读取控制台内容
   * </p>
   */
  public static string scanner(string tip) {
    scanner scanner = new scanner(system.in);
    stringbuilder help = new stringbuilder();
    help.append("请输入" + tip + ":");
    system.out.println(help.tostring());
    if (scanner.hasnext()) {
      string ipt = scanner.next();
      if (stringutils.isnotempty(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("jobob");
    gc.setopen(false);
    // gc.setswagger2(true); 实体属性 swagger2 注解
    mpg.setglobalconfig(gc);

    // 数据源配置
    datasourceconfig dsc = new datasourceconfig();
    dsc.seturl("jdbc:mysql://localhost:3306/***?useunicode=true&usessl=false&characterencoding=utf8");
    // dsc.setschemaname("public");
    dsc.setdrivername("com.mysql.cj.jdbc.driver");
    dsc.setusername("root");
    dsc.setpassword("***");
    mpg.setdatasource(dsc);

    // 包配置
    packageconfig pc = new packageconfig();
    //这里有个模块名的配置,可以注释掉不用。
//    pc.setmodulename(scanner("模块名"));
    pc.setparent("com.zhouxiaoxi.www");
    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/mapper/"
//            + + pc.getmodulename() + 如果放开上面的模块名,这里就有一个模块名了
            + "/" + tableinfo.getentityname() + "mapper" + stringpool.dot_xml;
      }
    });
    /*
    cfg.setfilecreate(new ifilecreate() {
      @override
      public boolean iscreate(configbuilder configbuilder, filetype filetype, string filepath) {
        // 判断自定义文件夹是否需要创建
        checkdir("调用默认方法创建的目录");
        return false;
      }
    });
    */
    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);
    //数据库表字段映射到实体的命名策略, 未指定按照 naming 执行
    strategy.setcolumnnaming(namingstrategy.underline_to_camel);
    //自定义继承的entity类全称,带包名
//    strategy.setsuperentityclass("***");
    strategy.setentitylombokmodel(true);
    strategy.setrestcontrollerstyle(true);
    //自定义继承的controller类全称,带包名
//    strategy.setsupercontrollerclass("***");
    strategy.setinclude(scanner("表名,多个英文逗号分割").split(","));
    //自定义基础的entity类,公共字段(可添加更多)
//    strategy.setsuperentitycolumns("id");
    //驼峰转连字符
    strategy.setcontrollermappinghyphenstyle(true);
    //表前缀
//    strategy.settableprefix(pc.getmodulename() + "_");
    mpg.setstrategy(strategy);
    mpg.settemplateengine(new freemarkertemplateengine());
    mpg.execute();
  }

}

在生成的controller里面添加对应的方法启动就可以正常进行访问了。

当然还需要在 spring boot 启动类中添加 @mapperscan 注解,扫描 mapper 文件夹:

@springbootapplication
@mapperscan("***.*.mapper") //对应你的mapper存放的地址
public class application {

  public static void main(string[] args) {
    springapplication.run(quickstartapplication.class, args);
  }

}

 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网