How to Build an Asynchronous MySQL Storage Service with Spring Boot & MyBatis

This article walks through rebuilding an asynchronous MySQL logging service using Spring Boot and MyBatis, providing full source code for the application entry point, DAO, service, controller, MyBatis mapper, and configuration, and shows the resulting database entries.

FunTester
FunTester
FunTester
How to Build an Asynchronous MySQL Storage Service with Spring Boot & MyBatis

Background

A previous API testing framework stored request/response data in MySQL via a custom service for asynchronous persistence. After learning Spring Boot and MyBatis, the same functionality was re‑implemented as a Spring Boot application.

Spring Boot Application Entry

package com.fun;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.context.annotation.Configuration;

@Configuration
@MapperScan("com.fun.dao") // scan DAO interfaces
@SpringBootApplication(exclude = {MongoAutoConfiguration.class})
public class ApiTestMysqlserviceApplication {
    public static void main(String[] args) {
        SpringApplication.run(ApiTestMysqlserviceApplication.class, args);
        System.out.println("-----------------------------------start-----------------------------------");
    }
}

Data Access Layer (DAO)

package com.fun.dao;

import com.fun.model.RequestBean;

public interface UserDao {
    int insertRequest(RequestBean requestBean);
}

Service Layer

package com.fun.user.impl;

import com.fun.dao.UserDao;
import com.fun.model.RequestBean;
import com.fun.user.UserService;
import org.springframework.stereotype.Service;

@Service(value = "userService")
public class UserServiceImpl implements UserService {
    private final UserDao userDao;

    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public int insertRequest(RequestBean requestBean) {
        return userDao.insertRequest(requestBean);
    }
}

Service Interface

package com.fun.user;

import com.fun.model.RequestBean;

public interface UserService {
    int insertRequest(RequestBean requestBean);
}

Controller Endpoint

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ApiController {
    private final UserService userService;
    private final Logger logger = LoggerFactory.getLogger(ApiController.class);

    public ApiController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/test")
    @ResponseBody
    public ResultUtil test(RequestBean requestBean) {
        logger.info(requestBean.toString());
        int rows = userService.insertRequest(requestBean);
        return ResultUtil.build(rows);
    }
}

MyBatis Mapper Configuration (mapper.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.fun.dao.UserDao">
    <sql id="REQUEST_TABLE">request</sql>
    <insert id="insertRequest" parameterType="com.fun.model.RequestBean">
        INSERT INTO
        <include refid="REQUEST_TABLE"/>
        <trim prefix="(" suffix=")" suffixOverrides=",">
            domain,api,type,expend_time,data_size,status,code,method,local_ip,local_name,create_time,
        </trim>
        <trim prefix="VALUES(" suffix=")" suffixOverrides=",">
            #{domain},#{api},#{type},#{expend_time},#{data_size},#{status},#{code},#{method},#{local_ip},#{local_name},#{create_time}
        </trim>
    </insert>
</mapper>

Application Properties (application.properties)

spring.datasource.url=jdbc:mysql://HOST:3306/fan?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=YOUR_PASSWORD
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.fun.model

pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql
pagehelper.returnPageInfo=check

Result

When a POST request is sent to /test, the request data is persisted asynchronously into the request table. The following screenshot shows a sample row stored in MySQL.

Database storage result
Database storage result
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaBackend DevelopmentSpring BootmysqlMyBatisAsync Storage
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.