微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

【idea版】springcloud微服务2之整合mybatis-plus查询数据库信息

文章目录

【idea版】springcloud微服务(2)之整合mybatis-plus查询数据库信息

1.mybatis-plus是什么?

官网地址:https://mp.baomidou.com/
官网的原话,详细请看官网
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

特性

2.创建项目

根据教程:【idea版】springcloud微服务(1)之多模块版本新建一个springcloud项目
创建一个子模块:springcloud-mybatisPlus-example

3.引包

1)pom.xml的基础web包文件

<?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>springcloud-example</artifactId>
        <groupId>org.example</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springcloud-mybatisPlus-example</artifactId>

    <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>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.5.RELEASE</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

2)引入mybatis-plus的核心包,在 dependencies里加入

<!--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>

3)完成引包

4.新建配置文件

在resources里新建文件application.yml

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

5.自动生产代码

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

在这里插入图片描述

CodeGenerator类代码

package generator;

import com.baomidou.mybatisplus.annotation.DbType;
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.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.VeLocityTemplateEngine;

import java.util.ArrayList;
import java.util.List;

public class CodeGenerator {

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setoutputDir(projectPath + "/springcloud-mybatisPlus-example/src/main/java");
        gc.setAuthor("binggoling");
        gc.setopen(false);
        gc.setEntityName("%sEntity");
        gc.setBaseColumnList(true);
        gc.setBaseResultMap(true);
        gc.setDateType(DateType.ONLY_DATE);
        gc.setSwagger2(false); //实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:MysqL://localhost:3306/test?useSSL=false");
//        dsc.setDriverName("dm.jdbc.driver.DmDriver");  //jdk 1.8使用这个 9之后就要下面的
        dsc.setDriverName("com.MysqL.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("***");
        dsc.setDbType(DbType.MysqL);
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
//        pc.setModuleName(scanner("模块名"));
        pc.setParent("com.example");
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 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;
                return projectPath + "/springcloud-mybatisPlus-example/src/main/resources/mapper" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName().replace("Entity","") + "Mapper"
                        + StringPool.DOT_XML;
            }
        });

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
         templateConfig.setEntity("templates/entity.java");
        // templateConfig.setService();
         templateConfig.setController(null);
        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("table1");
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new VeLocityTemplateEngine());
        mpg.execute();
    }
}

准备一个数据库表:

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;

直接运行main方法,然后生产实体代码
生产之后的结果:

在这里插入图片描述

6.application类

新建MybatisApplication.java

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @description:
 * @time: 2021/5/24 9:58
 */
@SpringBootApplication
public class MybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisApplication.class, args);
    }
}

7.配置类

新建MybatisPlusConfig.java

package com.example.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @description:
 * @time: 2021/3/22 10:41
 */
@Configuration
@MapperScan("com.example.mapper")
public class MybatisPlusConfig {

    /**
    * 分页配置,不配不能使用分页
    */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MysqL));
        return interceptor;
    }

}

8.控制层controller

package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.Metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.entity.Table1Entity;
import com.example.service.ITable1Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @description:
 * @author: libingwei
 * @time: 2021/5/24 10:04
 */
@RestController
public class TestController {

    @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:9000/list

返回值:

[Table1Entity(test1=1, test2=1, test3=1, test4=1, test5=1), 
Table1Entity(test1=aa, test2=ss, test3=dd, test4=ff, test5=2),
 Table1Entity(test1=aa, test2=ss, test3=dd, test4=ff, test5=3)]

10.完成整合使用

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

相关推荐