SpringBoot整合MybatisPlus 自动生成controller、mapper、entity、service

news2024/10/1 19:20:07

首先创建SpringBoot项目

        选择依赖

        把application的后缀改为.yml,方便些。

 pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.xgsm</groupId>
    <artifactId>mybatisplus</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mybatisplus</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.jupiter</groupId>
                    <artifactId>junit-jupiter-api</artifactId>
                </exclusion>
            </exclusions>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.spring4all</groupId>
            <artifactId>swagger-spring-boot-starter</artifactId>
            <version>1.7.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <scope>test</scope>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <scope>test</scope>
            <version>2.3.31</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.7.0</version>
                <configuration>
                    <fork>true</fork>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

需要在application.yml中配置下数据源,并修改端口。

application.yml:

server:
  port: 8080
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/ssm-java1?useSSL=false&&characterEncoding=UTF-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456

写个HelloController测试下

HelloController:

package com.example.laozhang.controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author java爱好者
 * @since 2023-06-26
 */
@RestController
@RequestMapping("/test-user")
public class TestUserController {
    @RequestMapping("/hello")
    public String hello(){
        return "keafmd";
    }
}

 

 到此证明SpringBoot没有问题。

使用代码生成器生成代码

添加所需的依赖

pom.xml中添加以下依赖:

<dependency>
   <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <scope>test</scope>
    <version>3.4.0</version>
</dependency>
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <scope>test</scope>
    <version>2.3.31</version>
</dependency>

由于代码生成器并不会在生产环境使用,只是在开发环境中使用了下。所以我们把代码生成器写在test包中即可,依赖的使用场景也定义成test即可。

CodeGenerator

package com.example.mp;

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;
/**
 * Keafmd
 *
 * @ClassName: CodeGenerator
 * @Description:
 * @author:
 * @date:
 */
// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
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.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");
//        System.out.println("projectPath = " + projectPath);
        gc.setOutputDir(projectPath + "/src/main/java");
//        gc.setOutputDir("D:\\test");
        gc.setAuthor("java爱好者");
        gc.setOpen(false);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        gc.setServiceName("%sService");
        mpg.setGlobalConfig(gc);
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC");
        // 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(null);
        pc.setParent("com.example.laozhang");
        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/"
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix("m_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}

运行代码生成器,在控制台输入想要生成的表

 这样就会生成一些包及相应的代码,注意CodeGenerator中的相关代码(如数据库的,包名的)需要改成你们需要的。

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/686828.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

一次完整的性能测试,测试人员需要做什么

目录 前言&#xff1a; 一、 规范性能测试实施流程的意义 二、 性能测试实施流程 1. 需求调研阶段 2. 测试准备阶段 3. 测试执行阶段 4. 测试报告阶段 5. 测试总结阶段 前言&#xff1a; 进行一次完整的性能测试需要经过多个阶段&#xff0c;包括需求分析、测试计划编…

OpenStack(3)--vxlan网络实战

目录 一、ML2配置文件 二、上传cirros镜像 三、创建vxlan10网络 四、创建实例/同vxlan通信测试 五、不同vxlan通信测试 5.1 新建vxlan11 5.2 新建路由/添加路由接口 5.3 不同vxlan通信测试 5.4 qemu-vnc报错 六、深度剖析vxlan 七、认识 Bridge br-ex、Bridge br-in…

「一本通 3.2 练习 6」汽车加油行驶

目录 第一步&#xff0c;二维转一维&#xff08;此步仅为方便&#xff0c;可以省略&#xff09; 第二步&#xff0c;建边&#xff08;啥都行&#xff0c;只要死不了&#xff09; 第三部&#xff0c;bfs&#xff08;你要dfs也行&#xff09; 第一步 第二步 第三步 可CA呢…

蓝桥杯专题-试题版-【01字符串】【2n皇后问题】【A+B问题】【Fibonacci数列】

点击跳转专栏>Unity3D特效百例点击跳转专栏>案例项目实战源码点击跳转专栏>游戏脚本-辅助自动化点击跳转专栏>Android控件全解手册点击跳转专栏>Scratch编程案例点击跳转>软考全系列点击跳转>蓝桥系列 &#x1f449;关于作者 专注于Android/Unity和各种游…

ECS 简略版说明一:Entities and components

目录 Entities and components Worlds and EntityManagers Archetypes Chunks Queries Entity IDs IComponentData Managed IComponentData components DynamicBuffer components Aspects Allocator overview Allocator.Temp Allocator.TempJob Allocator.Persis…

MySQL性能测试及调优中的死锁处理方法

目录 前言&#xff1a; 1、死锁检测 2、死锁避免 3、死锁解决 前言&#xff1a; MySQL死锁是指多个会话同时请求相同资源时发生的一种资源争用现象&#xff0c;导致会话无法继续执行。死锁的发生会导致事务无法提交或者回滚&#xff0c;影响应用程序的正常运行。因此&#xff0…

consul简介与安装

一、Consul简介 Consul 是 HashiCorp 公司推出的开源产品&#xff0c;用于实现分布式系统的服务发现、服务隔离、服务配置&#xff0c;这些功能中的每一个都可以根据需要单独使用&#xff0c;也可以同时使用所有功能。Consul 官网目前主要推 Consul 在服务网格中的使用。 与其…

【人工智能】教你如何让 AI 赢得贪吃蛇游戏----强化学习(初探)

人工智能--AI贪吃蛇&#xff0c;每一个代码都有详细的注释&#xff0c;希望多多收藏&#xff0c;点赞&#xff0c;评论 1.前言&#xff1a;训练ai玩游戏的可行性2.代码实现思路&#xff1a;3.代码完整实现3.1 Game Game.py 完整实现3.1.1 安装pygame库3.1.2 编写游戏逻辑代码 3…

Sangfor华东天勇战队:某咖啡还原密钥

最近学习了密钥还原&#xff0c;复现下并记录思路 function wbaes_encrypt_ecb(){var module_base Module.findBaseAddress("libcryptoDD.so")var func_base module_base.add(0x17BD41)Interceptor.attach(func_base,{onEnter:function (args){console.log("E…

风控引擎如何快速接入不同的数据源?

目录 数据是风控引擎的重要组成 风控引擎的数据接入 风控引擎是一种基于数据分析和机器学习算法的系统&#xff0c;能够实时识别和处理各种风险问题&#xff0c;适用于金融、电商、智能制造、交通运输等各领域&#xff0c;能够提高企业的风险管理水平和业务效率。 风控引擎主…

我心中的TOP1编程语言—JavaScript

作为一名研发工程师&#xff08;程序员&#xff09;&#xff0c;平时工作中肯定会接触或了解很多编程语言。每个人都会有自己工作中常用的语言&#xff0c;也会有偏爱的一些编程语言。而我心中的最爱&#xff0c;毫无疑问&#xff0c;就是 JavaScript。 JavaScript 是一门编程…

23. 数据结构之位图

前言 之前在讲散列表的时候&#xff0c;提到过位图的概念。位图&#xff08;Bitmap&#xff09;作为一种特殊的数据结构&#xff0c;它使用一系列位来表示数据&#xff0c;每个位只有两个状态&#xff08;0或1&#xff09;。由于它的高效性和节省空间的特性&#xff0c;位图在…

SpringBoot的配置环境属性

SpringBoot的配置环境属性 在本文中&#xff0c;我们将讨论SpringBoot的配置环境属性。我们将了解如何使用这些属性来配置我们的应用程序&#xff0c;以便在不同的环境中运行。我们还将了解如何使用SpringBoot的配置文件来管理这些属性。最后&#xff0c;我们将介绍一些最佳实…

java的嵌套类(nested class)、内部类(inner class)的区别

嵌套类即nested class&#xff0c;内部类即Inner class。 概括来说&#xff0c;嵌套类的概念比内部类概念大。嵌套类包含内部类和非内部类。一个内部类一定是一个嵌套类&#xff0c;但一个嵌套类不一定是一个内部类。 在一个类内部或者接口内部声明的类是嵌套类。 下面这些类是…

《Java面向对象程序设计教程》课后编程题

文章目录 第 1 章 Java 概述第 2 章 Java 语言基础第 3 章 Java 面向对象编程第 4 章 Java 图形用户界面程序设计第 5 章 Applet 设计第 6 章 Java 输入输出流与文件操作第 7 章 Java 的多线程机制第 9 章 常用工具类与集合框架 第 1 章 Java 概述 试编写 Java 程序&#xff0…

Android studio新建项目运行遇到的问题

文章目录 The emulator process for AVD xxx has terminated原因&#xff08;环境变量问题&#xff09;解决其他原因 新建的练习项目更改SDK默认位置更改方法 The emulator process for AVD xxx has terminated 运行虚拟机时报此错误 原因&#xff08;环境变量问题&#xff0…

555 timer circuit

#1, Block & principle 1.1&#xff0c; The threshold and trigger levels normally are two- thirds and one-third, respectively, of VCC.(分压&#xff09; 1.2&#xff0c;These levels can be altered by use of the control-voltage terminal. When the trigger in…

生成式 AI:通信服务提供商云转型的下一阶段

【本文由Cloud Ace 整理发布。Cloud Ace 是谷歌云全球战略合作伙伴&#xff0c;拥有 300 多名工程师&#xff0c;也是谷歌最高级别合作伙伴&#xff0c;多次获得 Google Cloud 合作伙伴奖。作为谷歌托管服务商&#xff0c;我们提供谷歌云、谷歌地图、谷歌办公套件、谷歌云认证培…

spring boot引入swagger报错处理

目录 1. 报错说明 2. 查找原因 2.1 此前笔者的代码 3. 问题解决说明 4. 解决方案 4.1 在pom.xml引入springdoc包 4.2 创建配置文件&#xff08;可省略&#xff09; 4.3 在controller加入注解 4.4 查看接口文档 4.5 常用注解 1. 报错说明 在java项目中引入swagger 2.9.2…

Linux设置进程名称(标题) ( 7) -【Linux通信架构系列 】

系列文章目录 C技能系列 Linux通信架构系列 C高性能优化编程系列 深入理解软件架构设计系列 高级C并发线程编程 期待你的关注哦&#xff01;&#xff01;&#xff01; 现在的一切都是为将来的梦想编织翅膀&#xff0c;让梦想在现实中展翅高飞。 Now everything is for the…