赞
踩
一、mybatis-Plus介绍
Mybatis-Plus(以下简称MP)是Mybatis的增强工具(MBG和通用Mapper可看成插件),在Mybatis的基础上增加了很多功能,简化开发,提高效率。、
二、mybatis-plus集成
1.在pom.xml文件中添加依赖
- <!-- mybatis-plus-generator代码生成器依赖-->
- <dependency>
- <groupId>com.baomidou</groupId>
- <artifactId>mybatis-plus-generator</artifactId>
- <version>3.3.2</version>
- </dependency>
2.创建CodeGenerator.java文件
- package com.hng.business;
-
- import ch.qos.logback.core.net.SyslogOutputStream;
- 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;
-
- /**
- * @Author 郝南过
- * @Date 2023/11/6 16:30
- * @Version 1.0
- * mybatis-plus代码生成器官网地址 https://baomidou.com/pages/d357af/
- */
- public class CodeGenerator {
-
- // 数据库连接字段配置
- private static final String JDBC_URL = "jdbc:mysql://xxx.xxx.xxx.xxx:3306/hng?useUnicode=true&useSSL=false&characterEncoding=utf8";
- private static final String JDBC_USER_NAME = "root";
- private static final String JDBC_PASSWORD = "xxxxx";
-
- // 包名和模块名
- private static final String PACKAGE_NAME = "com.hng";
- private static final String MODULE_NAME = "business";
-
- // 表名,多个表使用英文逗号分割
- private static final String[] TBL_NAMES = {"student", "subject", "sheet"};
-
- // 表名的前缀,从表生成代码时会去掉前缀
- private static final String TABLE_PREFIX = "tbl_";
-
- /**
- * <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.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")+"/"+MODULE_NAME;
- gc.setOutputDir(projectPath + "/src/main/java");
- gc.setAuthor("郝南过");
- gc.setOpen(false);
- //实体属性 Swagger2 注解
- gc.setSwagger2(true);
- //再次调用时是否覆盖原文件
- //gc.setFileOverride(true);
- //去掉Service接口自动生成的首字母I
- gc.setServiceName("%sService");
- mpg.setGlobalConfig(gc);
-
- // 数据源配置
- DataSourceConfig dsc = new DataSourceConfig();
- //只需要把moon_light修改为你自己的数据库即可
- dsc.setUrl(JDBC_URL);
- // dsc.setSchemaName("public");
- dsc.setDriverName("com.mysql.cj.jdbc.Driver");
- dsc.setUsername(JDBC_USER_NAME);
- dsc.setPassword(JDBC_PASSWORD);
- mpg.setDataSource(dsc);
-
- // 包配置
- PackageConfig pc = new PackageConfig();
- //pc.setModuleName(scanner("模块名"));
- pc.setModuleName(MODULE_NAME);
- //你的项目包结构名
- pc.setParent(PACKAGE_NAME);
- 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 的名称会跟着发生变化!!
- // ( pc.getModuleName()如果前面设置了null,这里应该不写)
- //return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
- return projectPath + "/src/main/resources/mapper/"
- + "/" + 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("m_"); //(没有前缀就只写_)
- strategy.setTablePrefix(pc.getModuleName() + "_");
- mpg.setStrategy(strategy);
- mpg.setTemplateEngine(new FreemarkerTemplateEngine());
- mpg.execute();
- }
-
- }
3.运行CodeGenerator.java中的main()方法即可生成对应的Controller、service、serviceImpl、mapper(注意mapper文件上默认没有注解@Repository)、mapper.xml、entity文件。且可以开启swagger注解,便于在swagger中查看和调试。
三、mybatis-plus使用
生成的mapper.xml为空,默认方法都baseMapper中,可在ServiceImpl中直接使用baseMapper进行调用使用,且提供了大量基础常用的方法。包括分页等。
【具体详细的使用可参考官方文档】:https://baomidou.com/pages/d357af/
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。