springboot集成mybatis(逆向工程),热部署以及整合Swagger2

本文是作者原创,版权归作者所有.若要转载,请注明出处.

springboot集成mybatis和mybatis-generator插件

1.新建Springboot项目(略)

2.导入相关依赖


    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.1.6.RELEASEversion>
    parent>
    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF8project.reporting.outputEncoding>
        <java.version>1.8java.version>
    properties>

    <dependencies>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.1.1version>
        dependency>
        
        <dependency>
            <groupId>org.mybatis.generatorgroupId>
            <artifactId>mybatis-generator-coreartifactId>
            <version>1.3.7version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.1.21version>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <optional>trueoptional>
            <scope>truescope>
        dependency>
        
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger2artifactId>
            <version>2.9.2version>
        dependency>
        
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger-uiartifactId>
            <version>2.9.2version>
        dependency>
        
    dependencies>

    <build>
        <plugins>
            
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
            
            <plugin>
                <groupId>org.mybatis.generatorgroupId>
                <artifactId>mybatis-generator-maven-pluginartifactId>
                <version>1.3.7version>
                <configuration>
                    <configurationFile>src/main/resources/generatorConfig.xmlconfigurationFile>
                    <verbose>trueverbose>
                    <overwrite>trueoverwrite>
                configuration>
            plugin>
        plugins>

        
        <resources>
            <resource>
                <directory>src/main/resourcesdirectory>
            resource>
            <resource>
                <directory>src/main/javadirectory>
                <includes>
                    <include>**/*.xmlinclude>
                    <include>**/*.propertiesinclude>
                    <include>**/*.tldinclude>
                includes>
                <filtering>falsefiltering>
            resource>
        resources>
    build>

3. 修改application.yml配置文件

server:
  port: 5000 #端口号
  servlet:
    context-path: /pdzx #项目路径

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://10.3.11.69:3306/pdzx?characterEncoding=utf8&useSSL=false&allowMultiQueries=true&serverTimezone=GMT%2B8
    username: pdzx_pro
    password: cde35TGB3910
  jackson:
    #格式化日期
    date-format:  yyyy-MM-dd HH:mm:ss
    #时区配置
    time-zone: Asia/Shanghai
  devtools:
      restart:
        enabled: true  #设置开启热部署
        additional-paths: src/main/java #重启资源目录

mybatis:
  type-aliases-package: com.pdzx.po #别名
  mapper-locations: classpath:com/pdzx/mapper/*.xml  #mybatis的sql文件xml路径配置

3. 新建包名,如下图

springboot集成mybatis(逆向工程),热部署以及整合Swagger2_第1张图片

 

 

4. 自动生成代码文件generatorConfig.xml配置

xml version="1.0" encoding="UTF-8"?>
DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">


<generatorConfiguration>

    
    
    <properties resource="datasource.properties"/>

    
    
    

    <classPathEntry location="D:/repository/mysql/mysql-connector-java/8.0.16/mysql-connector-java-8.0.16.jar"/>

    
    <context id="default" targetRuntime="MyBatis3">

        
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin">plugin>
        
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
            <property name="javaFileEncoding" value="UTF-8"/>
        commentGenerator>

        
        <jdbcConnection
                driverClass="${jdbc.driverClass}"
                connectionURL="${jdbc.url}"
                userId="${jdbc.username}"
                password="${jdbc.password}">
        jdbcConnection>

        
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        javaTypeResolver>

        
        <javaModelGenerator targetPackage="com.pdzx.entity" targetProject="src/main/java">
            
            <property name="enableSubPackages" value="false"/>
            
            <property name="constructorBased" value="false"/>
            
            <property name="immutable" value="false"/>
            
            <property name="trimStrings" value="false"/>
        javaModelGenerator>

        
        <sqlMapGenerator targetPackage="com.pdzx.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
        sqlMapGenerator>

        
        
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.pdzx.dao" targetProject="src/main/java">
            
            <property name="enableSubPackages" value="false" />
        javaClientGenerator>

        
        <table tableName="b_video_info"
               domainObjectName="VideoInfo"
               enableCountByExample="false"
               enableUpdateByExample="false"
               enableDeleteByExample="false"
               enableSelectByExample="false"
               selectByExampleQueryId="false">
            
            
            <property name="useActualColumnNames" value="false" />
        table>

    context>
generatorConfiguration>

5. 引用的数据库配置文件datasource.properties

jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://10.3.11.69:3306/pdzx?characterEncoding=utf8&useSSL=false&allowMultiQueries=true&nullCatalogMeansCurrent=true
jdbc.username=pdzx_pro
jdbc.password=cde35TGB3910

注意:如果mysql的驱动版本较高,mybatis自动生成代码可能只有insert()和insertSelective()

解决方案:在jdbc url后增加nullCatalogMeansCurrent=true即可

6.在idea中执行maven插件,如下

springboot集成mybatis(逆向工程),热部署以及整合Swagger2_第2张图片

 

生成的逻辑代码和自己写的文件如下

dao层

@Repository
public interface VideoInfoMapper {

    int deleteByPrimaryKey(Integer id);

    int insert(VideoInfo record);

    int insertSelective(VideoInfo record);

    VideoInfo selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(VideoInfo record);

    int updateByPrimaryKey(VideoInfo record);
}

service层

public interface VideoInfoService {
    VideoInfo selectByPrimaryKey(Integer id);
}

实现类

@Service
public class VideoInfoServiceImpl implements VideoInfoService {

    @Autowired
    private VideoInfoMapper videoInfoMapper;

    @Override
    public VideoInfo selectByPrimaryKey(Integer id) {
        return videoInfoMapper.selectByPrimaryKey(id);
    }
}

controller层

@RequestMapping("video")
@RestController
public class VideoInfoController {
    @Autowired
    private VideoInfoService videoInfoService;

    @GetMapping("/selectByPrimaryKey")
    public VideoInfo selectByPrimaryKey(Integer id){
        return videoInfoService.selectByPrimaryKey(id);
    }

    @GetMapping("/hello")
    public String hello(){
        return "hello springboot-mybatis-xml";
    }

    @GetMapping("/hi")
    public String hi(){
        return "hi springboot-mybatis-xml";
    }

}

 7.生成文件后在启动类中添加注解@MapperScan

@MapperScan("com.pdzx.dao")
@SpringBootApplication
public class VideoApplication {

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

}

8.访问以下路径,测试

http://localhost:5000/pdzx/video/selectByPrimaryKey?id=83

看结果

springboot集成mybatis(逆向工程),热部署以及整合Swagger2_第3张图片

 

 

 至此,springboot集成mybatis和mybatis-generator插件成功

 

springboot集成热部署

1.注意依赖


        
            org.springframework.boot
            spring-boot-devtools
            true
            true
        

2.注意配置

spring:
  devtools:
      restart:
        enabled: true  #设置开启热部署
        additional-paths: src/main/java #重启资源目录

3.设置IDEA的自动编译:,如图

springboot集成mybatis(逆向工程),热部署以及整合Swagger2_第4张图片

 

 

 4.安装ctrl + shift + alt + /,选择Registry,勾上 Compiler autoMake allow when app running,如图

springboot集成mybatis(逆向工程),热部署以及整合Swagger2_第5张图片

 

 

 5.重启idea即可生效

 

SpringBoot整合Swagger2

1.两个Swagger2相关的依赖

     
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger2artifactId>
            <version>2.9.2version>
        dependency>
        
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger-uiartifactId>
            <version>2.9.2version>
        dependency>

2.Swagger2配置

package com.pdzx.config;

import springfox.documentation.service.Contact;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Created by bianxh on 2019/1/21.
 */
@Configuration
@EnableSwagger2//启用Swagger2
public class SwaggerApp {

    //http://localhost:5000/pdzx/swagger-ui.html   项目路径/swagger-ui.html
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .pathMapping("/")//配置映射路径和要扫描的接口的位置
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.pdzx.controller"))//配置要扫描的接口的位置
                .paths(PathSelectors.any())
                .build().apiInfo(new ApiInfoBuilder()//配置一下Swagger2文档网站的信息
                        .title("SpringBoot整合Swagger")//网站的title
                        .description("本站是平大客户端的接口文档信息")//网站的描述
                        .version("9.0")//接口版本
                        .contact(new Contact("平大开发部","http://www.shpingda.com/","[email protected]"))//联系人的信息
                        .license("The Apache License")//使用的协议
                        .licenseUrl("http://www.baidu.com")//
                        .build());
    }
}

3.创建接口

@RestController
@Api(tags = "用户管理相关接口")//可以用来标记当前Controller的功能
@RequestMapping("/user")
public class UserController {

    @PostMapping("/addUser")
    @ApiOperation("添加用户的接口")//用来标记一个方法的作用
    @ApiImplicitParams(//如果有多个参数,多个@ApiImplicitParam注解需要放在一个@ApiImplicitParams注解中
            {
                //用来描述一个参数,可以配置参数的中文含义,也可以给参数设置默认值,这样在接口测试的时候可以避免手动输入
            @ApiImplicitParam(name = "username", value = "用户名", defaultValue = "李四"),
            //假如开发者需要指定一个参数必填,@RequestParam(required = true)注解不能省略
            @ApiImplicitParam(name = "address", value = "用户地址", defaultValue = "深圳", required = true)
            }
    )
    public User addUser(@RequestParam( "username") String username, @RequestParam( "address") String address) {
        User user = new User();
        user.setUsername(username);
        user.setAddress(address);
        return user;
    }

    @GetMapping("/getUserById")
    @ApiOperation("根据id查询用户的接口")
    @ApiImplicitParam(name = "id", value = "用户id", defaultValue = "99", required = true)
    public User getUserById(@RequestParam( "id")  Integer id) {
        User user = new User();
        user.setId(id);
        return user;
    }

    @PutMapping("/updateUserById")
    @ApiOperation("根据id更新用户的接口")//如果参数是一个对象(例如上文的更新接口),对于参数的描述也可以放在实体类中
    public User updateUserById(@RequestBody User user) {
        return user;
    }
}

user

@ApiModel
public class User {

    @ApiModelProperty(value = "用户id")
    private Integer id;
    @ApiModelProperty(value = "用户名")
    private String username;
    @ApiModelProperty(value = "用户地址")
    private String address;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

}

4.访问一下路径(项目路径/swagger-ui.html)

http://localhost:5000/pdzx/swagger-ui.html

看结果

springboot集成mybatis(逆向工程),热部署以及整合Swagger2_第6张图片

 

 5.测试,点击Execute按钮,表示发送请求进行测试。测试结果会展示在下面的Response中

springboot集成mybatis(逆向工程),热部署以及整合Swagger2_第7张图片

 

你可能感兴趣的:(springboot集成mybatis(逆向工程),热部署以及整合Swagger2)