小言_互联网的博客

如何运用SpringBoot+Mybatis逆向工程快速搭建后台工程

534人阅读  评论(0)

假设有一个需求:后台需要记录一条HTTP请求的信息并且设计出一个get请求接口。

SQL结构:

create table http_history( 
id int not null auto_increment primary key, 
method varchar(10) not null, 
request varchar(200) not null, 
response varchar(200), 
date DATETIME,
time int,
description varchar(200));

并且插入两条记录:

下面在IDEA中创建Spring Initializer项目

勾选依赖

 

这是完成后的项目结构,先给个图方便后面理解,刚创建完是没有controller,service,pojo以及dao的。

首先编辑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.1.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.zdy</groupId>
    <artifactId>httptesttool</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>httptesttool</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-data-jdbc</artifactId>
        </dependency>
        <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.1.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
            </plugin>
        </plugins>
    </build>

</project>

 

本案例不使用application.properties文件 而使用更加简洁的application.yml文件。将resource文件夹下原有的application.properties文件删除,创建application.yml配置文件(备注:其实SpringBoot底层会把application.yml文件解析为application.properties), 文件的内容如下(此处只配置最基本的):

编辑application.yml

server:
  port: 8081

spring:
  datasource:
    name: test
    url: jdbc:mysql://localhost:3306/HTTPtest
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
  mapper-locations: classpath:mapping/*Mapper.xml

配置mybatis generator 自动生成代码插件 (注意根据自己情况调整)

<?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>
    <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
    <classPathEntry  location="/Users/zhaodongyu/java/mysql-connector-java-8.0.13.jar"/>
    <context id="DB2Tables"  targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--数据库链接URL,用户名、密码
           1.一般jdbc数据库的版本6.x以上,都是com.mysql.cj.jdbc.Driver  其他的低版本就是com.mysql.jdbc.Driver
         -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/HTTPtest" userId="root" password="123456">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- 生成模型的包名和位置-->
        <javaModelGenerator targetPackage="com.zdy.httptesttool.pojo" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- 生成映射文件的包名和位置-->
        <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!-- 生成DAO的包名和位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.zdy.httptesttool.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
        <table tableName="http_history" domainObjectName="History" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
    </context>
</generatorConfiguration>

 打开IDEA右侧的MAVEN工具栏运行逆向工程

运行后会生成一个pojo.History对象,一个dao.HistoryMapper以及resource->mapping->HistoryMapper.xml

package com.zdy.httptesttool.pojo;

import java.util.Date;

public class History {
    private Integer id;

    private String method;

    private String request;

    private String response;

    private Date date;

    private Integer time;

    private String description;

    public Integer getId() {
        return id;
    }

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

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method == null ? null : method.trim();
    }

    public String getRequest() {
        return request;
    }

    public void setRequest(String request) {
        this.request = request == null ? null : request.trim();
    }

    public String getResponse() {
        return response;
    }

    public void setResponse(String response) {
        this.response = response == null ? null : response.trim();
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public Integer getTime() {
        return time;
    }

    public void setTime(Integer time) {
        this.time = time;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description == null ? null : description.trim();
    }
}
package com.zdy.httptesttool.dao;

import com.zdy.httptesttool.pojo.History;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface HistoryMapper {
    int insert(History record);

    int insertSelective(History record);

    List findAllHistory();//这是后来添加的
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.zdy.httptesttool.dao.HistoryMapper" >
  <resultMap id="BaseResultMap" type="com.zdy.httptesttool.pojo.History" >
    <result column="id" property="id" jdbcType="INTEGER" />
    <result column="method" property="method" jdbcType="VARCHAR" />
    <result column="request" property="request" jdbcType="VARCHAR" />
    <result column="response" property="response" jdbcType="VARCHAR" />
    <result column="date" property="date" jdbcType="TIMESTAMP" />
    <result column="time" property="time" jdbcType="INTEGER" />
    <result column="description" property="description" jdbcType="VARCHAR" />
  </resultMap>
  <insert id="insert" parameterType="com.zdy.httptesttool.pojo.History" >
    insert into http_history (id, method, request, 
      response, date, time, 
      description)
    values (#{id,jdbcType=INTEGER}, #{method,jdbcType=VARCHAR}, #{request,jdbcType=VARCHAR}, 
      #{response,jdbcType=VARCHAR}, #{date,jdbcType=TIMESTAMP}, #{time,jdbcType=INTEGER}, 
      #{description,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.zdy.httptesttool.pojo.History" >
    insert into http_history
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="method != null" >
        method,
      </if>
      <if test="request != null" >
        request,
      </if>
      <if test="response != null" >
        response,
      </if>
      <if test="date != null" >
        date,
      </if>
      <if test="time != null" >
        time,
      </if>
      <if test="description != null" >
        description,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="method != null" >
        #{method,jdbcType=VARCHAR},
      </if>
      <if test="request != null" >
        #{request,jdbcType=VARCHAR},
      </if>
      <if test="response != null" >
        #{response,jdbcType=VARCHAR},
      </if>
      <if test="date != null" >
        #{date,jdbcType=TIMESTAMP},
      </if>
      <if test="time != null" >
        #{time,jdbcType=INTEGER},
      </if>
      <if test="description != null" >
        #{description,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  
    <!--  这是后来添加的-->
  <select id="findAllHistory" resultType="com.zdy.httptesttool.pojo.History">
    select * from http_history
  </select>
</mapper>

Mybatis部分构建完毕,下面编写Service层和Controller层

service.HttpService

package com.zdy.httptesttool.service;

import java.util.List;

public interface HttpService {
    List findAllHistory();
}

service.HttpServiceImpl

import com.zdy.httptesttool.dao.HistoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class HttpServiceImpl implements HttpService {
    @Autowired
    HistoryMapper historyMapper;//这里有可能显示报错,不要担心

    @Override
    public List findAllHistory() {
        return historyMapper.findAllHistory();
    }
}

controller.HttpController

package com.zdy.httptesttool.controller;

import com.zdy.httptesttool.service.HttpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class HttpController {
    @Autowired
    HttpService httpService;

    @GetMapping("/history")
    public List getHistory(){
        return httpService.findAllHistory();
    }

}

到这里就大功告成了,运行测试下


转载:https://blog.csdn.net/qq_38905818/article/details/101365031
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场