快速搭建springcloud+mybatisplus

1)多模块版本:

1.新建,选择maven,模板不用选择,直接下一步

2.输入项目名springcloud-example,然后点击完成

3.创建完成,一个纯净版的springcloud项目

4.把src目录删除,这个是我们不需要的

2)创建子模块

1.在目录上右键,new->Module,新建子模块

2.新建,选择maven,模板不用选择,直接下一步

2.输入项目名springcloud-mybatisPlus-example,然后点击完成

3.创建完成,一个纯净版的子模块创建完成项目

4.根据自己实际业务的划分创建多个子模块

3)springcloud引包

1、在父mul的pom.xml文件引入,我这里已经把阿里巴巴的springcloud已经写入,为了后续可以使用nacos注册和配置中心的使用

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>myLearnDemo</artifactId>
        <groupId>com.steven</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springcloud-mybatisPlus-example</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <spring-boot.version>2.4.3</spring-boot.version>
        <spring-cloud.version>2020.0.2</spring-cloud.version>
        <spring-cloud-alibaba.version>2.2.1.RELEASE</spring-cloud-alibaba.version>
        <java.version>8</java.version>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!--swagger文档-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <!--mysql begin-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>
        <!-- mysql end-->
        <!--mybatis-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-support</artifactId>
            <version>2.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!--docker镜像build插件-->
            <plugin>
                <groupId>com.spotify</groupId>
                <artifactId>docker-maven-plugin</artifactId>
                <version>1.2.0</version>
                <configuration>
                    <!-- 注意imageName一定要是符合正则[a-z0-9-_.]的,否则构建不会成功 -->
                    <imageName>cike/${project.artifactId}</imageName>
                    <dockerDirectory>${project.basedir}/src/main/docker</dockerDirectory>
                    <rm>true</rm>
                    <resources>
                        <resource>
                            <targetPath>/</targetPath>
                            <directory>${project.build.directory}</directory>
                            <include>${project.build.finalName}.jar</include>
                        </resource>
                    </resources>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

4)新建配置文件

1、在resources里新建文件application.yml

server:
  port: 8008
# 数据库设置
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
    username: 用户名
    password: 密码
# mybatis-plu设置
mybatis-plus:
  mapper-locations: classpath*:mapper/*Mapper.xml #扫描的xml文件路径
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #控制台日志输出

5)自动生产代码

1、mybatis有一个自动生产实体,serive,mapper接口类和mapper.xml文件的工具类(官网也有实例)在test目录下创建一个SqlCodeInfo类和CodeGenerator

2、编写SqlCodeInfo类代码:

import lombok.Data;
import lombok.experimental.Accessors;

/**
 * @Date 2022/8/12 12:03
 */
@Data
@Accessors(chain = true)
public class SqlCodeInfo {
    private String projectPath = System.getProperty("user.dir");
    private String parentPackage;

    private String author = "auto";
    private String dbIp;
    private Integer dbPort;
    private String dbBase;
    private String dbUser;
    private String dbPwd;
    private String moduleName;
    private String tables;
    private Boolean fileOverride = false;

}

CodeGenerator.java

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.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class CodeGenerator {
    public void generatorCode(SqlCodeInfo sqlCodeInfo) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = sqlCodeInfo.getProjectPath();
        gc.setOutputDir(projectPath + "src/main/java");
        gc.setAuthor(sqlCodeInfo.getAuthor());
        gc.setFileOverride(sqlCodeInfo.getFileOverride());
        // XML 二级缓存
        gc.setEnableCache(false);
        // XML ResultMap
        gc.setBaseResultMap(true);
        // XML columList
        gc.setBaseColumnList(true);
        gc.setOpen(false);
        gc.setEntityName("%sEntity");
        gc.setSwagger2(true);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(String.format("jdbc:mysql://%s:%d/%s?serverTimezone=UTC&useUnicode=true&useSSL=false&characterEncoding=utf8",
                sqlCodeInfo.getDbIp(), sqlCodeInfo.getDbPort(), sqlCodeInfo.getDbBase()));
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername(sqlCodeInfo.getDbUser());
        dsc.setPassword(sqlCodeInfo.getDbPwd());
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(sqlCodeInfo.getModuleName());
        pc.setParent(sqlCodeInfo.getParentPackage());
        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.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.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setChainModel(true);
        // 公共父类
//        strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
        // 写于父类中的公共字段
//        strategy.setSuperEntityColumns("id");
        strategy.setInclude(sqlCodeInfo.getTables().split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new VelocityTemplateEngine());
        mpg.execute();
    }

    public static void main(String[] args) {

        new CodeGenerator().generatorCode(new SqlCodeInfo()
                .setDbIp("124.222.242.153")//数据库ip
                .setDbBase("test")//数据库库名
                .setDbPort(3306)//端口
                .setDbUser("xxx")//用户
                .setDbPwd("xxx")//密码
                .setFileOverride(true)
                .setModuleName("")//模块名
                .setParentPackage("com.fs.springcloud")//包名
                .setTables("user")//数据库建好的表名
                .setProjectPath(System.getProperty("user.dir") + "/springcloud-mybatisPlus-example" + File.separator));//项目名称
    }
}

3、准备一个数据库表:

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for table1
-- ----------------------------
DROP TABLE IF EXISTS `table1`;
CREATE TABLE `table1`  (
  `test1` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `test2` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `test3` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `test4` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `test5` int(255) NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of table1
-- ----------------------------
INSERT INTO `table1` VALUES ('1', '1', '1', '1', 1);
INSERT INTO `table1` VALUES ('aa', 'ss', 'dd', 'ff', 2);
INSERT INTO `table1` VALUES ('aa', 'ss', 'dd', 'ff', 3);
SET FOREIGN_KEY_CHECKS = 1;

4、直接运行main方法,然后生产实体代码

生成之后的结果:

6)application类

1、新建MybatisApplication.java

/**
 * @Description MybatisApplication
 **/
@SpringBootApplication
public class MybatisPlusApplication {
    public static void main(String[] args) {
        SpringApplication.run(MybatisPlusApplication.class, args);
    }
}

7)配置类

1、新建MybatisPlusConfig.java

/**
 * @Description MybatisPlusConfig
 **/
@Configuration
@MapperScan("com.steven.springcloud.mapper")
public class MybatisPlusConfig {
    /**
     * 分页配置,不配不能使用分页
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

8)控制层controller

/**
 * @description:测试controller
 */
@RestController
public class Table1Controller{
    @Autowired
    private ITable1Service table1Service;
    @RequestMapping("/test")
    public String getA(){
        return "success";
    }
    @RequestMapping("/list")
    public String getList(){
        return table1Service.list().toString();
    }
    //分页查询
    @RequestMapping("/listPage")
    public String getListPage(@RequestParam Integer page, @RequestParam Integer size){
        IPage<Table1Entity> iPage = new Page<>(page, size);
        QueryWrapper<Table1Entity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Table1Entity::getTest1,"1");
        iPage = table1Service.page(iPage, queryWrapper);
        return iPage.getRecords().toString();
    }
}

9) 访问服务

http://localhost:8008/list

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南方的晨露

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值