spring boot + mybatis 开发接口

在这里插入图片描述


功能介绍

使用spring boot + mybatis开发接口,实现对user数据表的增删改查,并生成日志、接口swagger文档,具体接口如下:

  • /v1/login:登陆接口uri
  • /v1/getUserInfo:获取用户信息接口uri
  • /v1/getUserInfo:获取用户列表接口uri
  • /v1/updateUserInfo:更新用户信息接口uri
  • /v1/addUser:添加用户接口uri



使用框架

  • spring boot
  • mybatis(连接mysql数据库)
  • logback(日志)
  • lombok(简化代码)
  • ExtentReport(生成报告)
  • swagger(生成接口文档)



依赖

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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.testfan</groupId>
    <artifactId>Server</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--引入父类-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
    </parent>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

	<!--依赖-->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>1.5.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.1</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.14</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.38</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>
    </dependencies>

    <!--
    	打包需要的配置
		除了<mainClass>标签,需要根据实际程序修改外,其他配置可以拿到其他的项目直接用。
	-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <!--使用spring boot和maven进行集成后,程序的入口-->
                    <!--配置启动程序文件-->
                    <mainClass>com.course.Application</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                    <compilerArguments>
                        <!--指定lib目录-->
                        <extdirs>${project.basedir}/lib</extdirs>
                    </compilerArguments>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>



配置

spring boot外化配置

外化配置文件可以是properties或yaml文件
这里使用application.yml

# 设置tomcat访问端口
server:
  port: 8888  # 注意冒号后面必须有一个空格

 # 设置生成日志
logging:
  path: logs  # 日志路径
  file: userManager.log  # 日志名称
  level:
    root: debug # 打印mybatis的sql日志

# 设置spring相关
spring:
  application:
    name: userManager  # application名称
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver  # JDBC驱动程序的完全限定名
    url: jdbc:mysql://localhost:3306/course?serverTimezone=GMT%2B8  # 指定时间使用东8区的
    username: root  # 数据库用户名
    password: 123456  # 数据库密码

# 设置mybatis
mybatis:
  type-aliases-package: com.course.model  # 包的路径,设置在什么路径下,搜索Java Bean
  mapper-locations:  # mapper路径
    - mapper/*  # 加载mapper/下面的所有xml文件


Logback配置

logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
    <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
    <property name="FILE_LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{80} - %msg%n"/>
    <property name="LOG_PATH" value="${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}}"/>

    <!--滚动记录到文件,默认文件最大10M-->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_PATH}/${LOG_FILE}</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_PATH}/${LOG_FILE}.%d{yyyy-MM-dd}</fileNamePattern>
        </rollingPolicy>
        <encoder charset="UTF-8">
            <pattern>${FILE_LOG_PATTERN}</pattern>
        </encoder>
    </appender>

    <!--输出到控制台-->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>${FILE_LOG_PATTERN}</pattern>
        </encoder>
    </appender>


    <appender name="CRAWLER_LOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_PATH}/event.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_PATH}/event.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>30</maxHistory>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>%msg%n</pattern>
        </encoder>
    </appender>



    <logger name="com.business.intelligence.util.CrawlerLogger" level="INFO" additivity="false">
        <appender-ref ref="CRAWLER_LOG"/>
    </logger>

    <!--level日志级别,分为TRACE/DEBUG/INFO/WARN/ERROR/OFF-->
    <root level="INFO">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="FILE"/>
    </root>


</configuration>

mybatis配置

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <typeAliases>
        <package name="com.course.model"/>
    </typeAliases>
    <mappers>
        <mapper resource="mapper/mysql.xml"/>
    </mappers>
</configuration>

swagger配置

SwaggerConfig.java

package com.course.config;

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.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration  //表示这是一个配置类,通过@Configuration注解,让Spring来加载该类配置
@EnableSwagger2 //@EnableSwagger2注解来启用Swagger2
public class SwaggerConfig {

    @Bean
    public Docket api(){

        return new Docket(DocumentationType.SWAGGER_2) //主要api配置机制初始化为swagger规范2.0
                .apiInfo(apiInfo())
                .pathMapping("/")
                .select()
                .paths(PathSelectors.regex("/.*"))  //过滤的接口
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("UseManager service API")  // 标题
                .contact(new Contact("xiaohei", "", "123456@qq.com"))  // 联系方式
                .description("this is UseManager service API")  // 描述信息
                .version("1.0") //版本号
                .build();
    }
}


程序主入口

Application.java

package com.course;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableScheduling
@SpringBootApplication
public class Application {

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


用户信息

user表的sql文件

对应的user数据表sql文件

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userName` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
  `password` varchar(255) COLLATE utf8_bin DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `sex` varchar(255) COLLATE utf8_bin DEFAULT NULL,
  `permission` int(11) DEFAULT NULL,
  `isDelete` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=64 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'zhangsan', '123456', '23', '1', '0', '0');
INSERT INTO `user` VALUES ('2', 'hahahaha', '123456', '23', '1', '0', '0');
INSERT INTO `user` VALUES ('3', 'wangwu', '123456', '23', '1', '0', '0');
INSERT INTO `user` VALUES ('4', 'zhaoliu', '123456', '23', '1', '0', '0');
INSERT INTO `user` VALUES ('5', 'tianqi', '123', '23', '1', '0', '0');
INSERT INTO `user` VALUES ('6', 'huba', 'wqer', '23', '1', '0', '0');
INSERT INTO `user` VALUES ('7', 'xiaohei', '789', '23', '1', '0', '0');
INSERT INTO `user` VALUES ('8', 'xiaohua', '123', '21', '0', '1', '1');
INSERT INTO `user` VALUES ('62', 'zhao9', 'zhaozhao', '35', '0', '1', '0');
INSERT INTO `user` VALUES ('63', 'zhao9', 'zhaozhao', '35', '0', '1', '0');

User bean对象

User.java

package com.course.model;

import lombok.Data;

@Data
public class User {
    private int id;
    private String userName;
    private String password;
    private String age;
    private String sex;
    private String permission;
    private String isDelete;

    @Override
    public String toString(){
        return (
                "id:"+id+","+
                        "userName:"+userName+","+
                        "password:"+password+","+
                        "age:"+age+","+
                        "sex:"+sex+","+
                        "permission:"+permission+","+
                        "isDelete:"+isDelete+"}"
        );
    }
}

开发接口

UserManager.java

package com.course.Controller;

import com.course.model.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

@Log4j
@RestController
@Api(value = "v1", description = "用户管理系统")
@RequestMapping("/v1")
public class UserManager {

    @Autowired
    private SqlSessionTemplate template; //访问数据库的对象

    @ApiOperation(value = "登录接口", httpMethod = "POST")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    //@requestBody注解常用来处理content-type不是默认的application/x-www-form-urlcoded编码的内容,
    // 比如说:application/json或者是application/xml等。一般情况下来说常用其来处理application/json类型。
    //通过@requestBody可以将请求体中的JSON字符串绑定到相应的bean上,当然,也可以将其分别绑定到对应的字符串上。
    public Boolean login(HttpServletResponse response, @RequestBody User user){
        int i = template.selectOne("login", user); //查看数据库中是否有这个用户
        Cookie cookie =new Cookie("login", "true");
        response.addCookie(cookie);
        log.info("查询到的结果是" + i);
        if (i == 1){
            log.info("登录的用户是:" + user.getUserName());
            return true;
        }
        return false;
    }


    /**
     * 添加用户
     */
    @ApiOperation(value = "添加用户接口", httpMethod = "POST")
    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    public boolean addUser(HttpServletRequest request, @RequestBody User user){
        Boolean x = verifyCookies(request); //验证cookie
        int result = 0;
        if (x != null){
            result = template.insert("addUser", user);
        }
        if (result > 0){
            log.info("添加用户的数量是:" + result);
            return true;
        }
        return false;
    }

    @ApiOperation(value = "获取用户(列表)信息接口", httpMethod = "POST")
    @RequestMapping(value = "/getUserInfo", method = RequestMethod.POST)
    public List<User> getUserInfo(HttpServletRequest request, @RequestBody User user){
        Boolean x = verifyCookies(request);
        if (x == true){
            List<User> users = template.selectList("getUserInfo", user); //实现单个或多个用户查询
            log.info("getUserInfo获取到的用户数量是" + users.size());
            return users;
        }else {
            return null;
        }
    }

    //注意:这里的删除为逻辑删除,即把isDelete置为1
    @ApiOperation(value = "更新/删除用户接口", httpMethod = "POST")
    @RequestMapping(value = "/updateUserInfo", method = RequestMethod.POST)
    public int updateUser(HttpServletRequest request, @RequestBody User user){
        System.out.println(user);
        Boolean x = verifyCookies(request);
        //若不传id或id非法,则不更新
        if (user.getId() == 0){
            return 0;
        }
        int i = 0;
        if (x == true){
            i = template.update("updateUserInfo", user);
        }
        log.info("更新数据的条目数为:" + i);
        return i;
    }

    private Boolean verifyCookies(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (Objects.isNull(cookies)){
            log.info("cookies为空");
            return false;
        }
        for (Cookie cookie:cookies){
            if (cookie.getName().equals("login") && cookie.getValue().equals("true")){
                log.info("cookies验证通过");
                return true;
            }
        }
        return false;
    }
}


生成sql的mapper文件

mysql.xml

<?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.course">
    <!--登录接口sql-->
    <select id="login" parameterType="com.course.model.User" resultType="Integer">
        select count(*) from user
        where userName=#{userName} and password=#{password}
    </select>
    <!--添加用户sql-->
    <insert id="addUser" parameterType="com.course.model.User">
        insert into
        user (userName, password, sex, age, permission, isDelete)
        values
        (#{userName}, #{password}, #{sex}, #{age}, #{permission}, #{isDelete});
    </insert>
    <!--获取用户信息-->
    <!--此处trim的作用:在trim包裹的部分添加where,并去除第一个if中的and-->
    <select id="getUserInfo" parameterType="com.course.model.User" resultType="com.course.model.User">
        select * from user
        <trim prefix="WHERE" prefixOverrides="and">
            <if test="id != null and id != ''">
                and id=#{id}
            </if>
            <if test="userName != null and userName != ''">
                and userName=#{userName}
            </if>
            <if test="password != null and password != ''">
                and password=#{password}
            </if>
            <if test="sex != null and sex != ''">
                and sex=#{sex}
            </if>
            <if test="age != null and age != ''">
                and age=#{age}
            </if>
            <if test="permission != null and permission != ''">
                and permission=#{permission}
            </if>
            <if test="isDelete != null and isDelete != ''">
                and isDelete=#{isDelete}
            </if>
        </trim>
    </select>
    <!--更新/删除用户信息-->
    <!--trim的作用是在trim包裹的部分添加set,并去除最后if中的-->
    <update id="updateUserInfo" parameterType="com.course.model.User">
        update user
        <trim prefix="SET" suffixOverrides=",">
            <if test="userName != null and userName != ''">
                userName=#{userName},
            </if>
            <if test="sex != null and sex != ''">
                sex=#{sex},
            </if>
            <if test="age != null and age != ''">
                age=#{age},
            </if>
            <if test="permission != null and permission != ''">
                permission=#{permission},
            </if>
            <if test="isDelete != null and isDelete != ''">
                isDelete=#{isDelete},
            </if>
        </trim>
        <trim prefix="WHERE" prefixOverrides="and">
            <if test="id != null and id != ''">
                and id=#{id}
            </if>
        </trim>
        ;
    </update>
</mapper>

在swagger文档中测试接口

在浏览器中输入"ip地址/swagger-ui.html",打开swagger文档。执行application.java中的main方法启动接口,在文档中对实现的接口进行测试
在这里插入图片描述


打jar包

首先打jar包,需要先在pom.xml文件中添加一些插件,参考本文pom.xml文件中build部分。

在terminal中,在项目路径下,执行命令mvn clean package,在target目录下生成jar包。
使用java -jar jar包名 就可以将jar包启动起来,我们就可以访问开发的接口了。

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述



下面我们对开发好的接口 进行java接口自动化测试

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值