[Eight: (Adjust springboot+testng+mybatis+data verification]

Directory

    • 1. Code structure
      • config
      • controller
      • model
      • springboot startup class
    • 2. Configure resources
      • mysql.xml
      • application.yml
      • logback.xml
      • mybatis-config.xml
      • Database configuration
    • 3. Test verification

image.png

1. Code structure

config

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
@EnableSwagger2
public class SwaggerConfig {<!-- -->

    @Bean
    public Docket api() {<!-- -->
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .pathMapping("/")
                .select()
                .paths(PathSelectors.regex("/.*"))
                .build();
    }

    private ApiInfo apiInfo() {<!-- -->
        return new ApiInfoBuilder().title("UserManager service API")
                .contact(new Contact("dazhou", "", "[email protected]"))
                .description("this is UserManager service API")
                .version("1.0")
                .build();
    }
}

controller

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.*;
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",tags = "User Management System")
@RequestMapping("v1")
public class UserManager {<!-- -->


    //First get an object to execute the sql statement
    @Autowired
    private SqlSessionTemplate template;

    @ApiOperation(value = "Login interface",httpMethod = "POST")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Boolean login(HttpServletResponse response, @RequestBody User user){<!-- -->
        //Take the user and insert it into the database to see if there is this user
        //login01 needs to be consistent with the id in <!--Login interface sql--> in mysql.xml
        int i = template.selectOne("login01",user);
        //If there is, successfully return the corresponding cookie information login: true
        Cookie cookie = new Cookie("login","true");
        response.addCookie(cookie);
        log.info("The result viewed is " + i);
        if(i==1){<!-- -->
            return true;
        }
        return false;
    }
    @ApiOperation(value = "Add User Interface",httpMethod = "POST")
    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    public boolean addUser(HttpServletRequest request,@RequestBody User user){<!-- -->
        Boolean x = verifyCookies(request);
        int result = 0;
        if(x != null){<!-- -->
            result = template.insert("addUser",user);
        }
        if(result>0){<!-- -->
            log.info("The number of added users is:" + result);
            return true;
        }
        return false;
    }

    private Boolean verifyCookies(HttpServletRequest request) {<!-- -->
        Cookie[] cookies = request.getCookies();
        if(Objects.isNull(cookies)){<!-- -->
            log.info("cookies are empty");
            return false;
        }
        for(Cookie cookie : cookies){<!-- -->
            if(cookie.getName().equals("login") & amp; & amp;
                    cookie.getValue().equals("true")){<!-- -->
                log.info("cookies verification passed");
                return true;
            }
        }
        return false;
    }

    @ApiOperation(value = "Get user (list) information interface", 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("The number of users obtained by getUserInfo is " + users.size());
            return users;
        }else {<!-- -->
            return null;
        }
    }


    @ApiOperation(value = "Update/Delete User Interface",httpMethod = "POST")
    @RequestMapping(value = "/updateUserInfo", method = RequestMethod.POST)
    public int updateUser(HttpServletRequest request,@RequestBody User user){<!-- -->
        Boolean x = verifyCookies(request);
        int i = 0;
        if(x==true) {<!-- -->
            i = template.update("updateUserInfo", user);
        }
        log.info("The number of updated data entries is:" + i);
        return i;

    }


}

model

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;
}

springboot startup class

package com.course;

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

import javax.annotation.PreDestroy;

@EnableScheduling
@SpringBootApplication
public class Application {<!-- -->

    private static ConfigurableApplicationContext context;

    public static void main(String[] args) {<!-- -->
        Application.context = SpringApplication.run(Application.class,args);
    }

    @PreDestroy
    public void close(){<!-- -->
        Application.context.close();
    }

}

2. Configure resources

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">
  <!--Login interface sql-->
  <select id="login01" parameterType="com.course.model.User" resultType="Integer">
    select count(*) from user
    where userName=#{userName}
    and password=#{password}
  </select>

  <!--Add user interface-->
  <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>

  <!--Get user information sql-->
  <select id="getUserInfo" parameterType="com.course.model.User" resultType="com.course.model.User">
    select * from user
    <trim prefix="WHERE" prefixOverrides="and">
      <if test="null != id and '' !=id">
        AND id=#{id}
      </if>
      <if test="null != userName and '' !=userName">
        AND userName=#{userName}
      </if>
      <if test="null != sex and '' !=sex">
        AND sex=#{sex}
      </if>
      <if test="null != age and '' !=age">
        AND age=#{age}
      </if>
      <if test="null != permission and '' !=permission">
        AND permission=#{permission}
      </if>
      <if test="null != isDelete and '' !=isDelete">
        AND isDelete=#{isDelete}
      </if>
    </trim>
  </select>


  <!--Update/delete user information action-->
  <update id="updateUserInfo" parameterType="com.course.model.User">
    update user
    <trim prefix="SET" suffixOverrides=",">
      <if test="null != userName and '' !=userName">
        userName=#{userName},
      </if>
      <if test="null != sex and '' !=sex">
        sex=#{sex},
      </if>
      <if test="null != age and '' !=age">
        age=#{age},
      </if>
      <if test="null != permission and '' !=permission">
        permission=#{permission},
        </if>
        <if test="null != isDelete and '' !=isDelete">
        isDelete=#{isDelete},
        </if>
        </trim>
        where id = #{id}
        </update>

        </mapper>

application.yml

server:
   port: 8888

logging:
    # Path to log file
    path: logs
    file:
      # The name of the log file
      name: mylog.log
    pattern:
      # file refers to the format of the log in the log file
      console: "%d{yyyy/MM/dd-HH:mm:ss} [%thread] %-5level %logger{50}- %msg%n"
      file: "%d{yyyy/MM/dd-HH:mm:ss} ---- [%thread] %-5level %logger{50}- %msg%n"

spring:
   application:
          name: report
   datasource:
       driver-class-name: com.mysql.jdbc.Driver
       url: jdbc:mysql://localhost:3306/course
       username: root
       password: 123456

mybatis:
    type-aliases-package: com.course.model
    mapper-locations:
       - mapper/*

logback.xml

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

    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
    <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}}}"/>
    <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>

    <root level="INFO">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="FILE"/>
    </root>


</configuration>

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>

Database configuration

image.png

3. Test verification

image.png

You can see that the return value is true, indicating that the corresponding data has been found in the database.