[Spring Boot AOP records user operation logs] 1. Integrate mybatis basic framework

Keywords: Programming Mybatis Spring Java MySQL

In the Spring framework, using AOP with custom annotations can facilitate the monitoring of user operations. First, build a basic Spring Boot Web environment to start Spring Boot, and then introduce the necessary dependencies:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!--Common tools -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>

Create a database table for logging

CREATE TABLE `sys_oper_log` (
  `oper_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'Log key',
  `title` varchar(50) COLLATE utf8_bin DEFAULT '' COMMENT 'Module header',
  `business_type` int(2) DEFAULT '0' COMMENT 'Business type (0 other 1 new 2 modify 3 delete)',
  `method` varchar(100) COLLATE utf8_bin DEFAULT '' COMMENT 'Method name',
  `request_method` varchar(10) COLLATE utf8_bin DEFAULT '' COMMENT 'Request mode',
  `operator_type` int(1) DEFAULT '0' COMMENT 'Operation category (0 other 1 background user 2 mobile user)',
  `oper_name` varchar(50) COLLATE utf8_bin DEFAULT '' COMMENT 'Operator',
  `dept_name` varchar(50) COLLATE utf8_bin DEFAULT '' COMMENT 'Department name',
  `oper_url` varchar(255) COLLATE utf8_bin DEFAULT '' COMMENT 'request URL',
  `oper_ip` varchar(50) COLLATE utf8_bin DEFAULT '' COMMENT 'Host address',
  `oper_location` varchar(255) COLLATE utf8_bin DEFAULT '' COMMENT 'Operation place',
  `oper_param` varchar(2000) COLLATE utf8_bin DEFAULT '' COMMENT 'Request parameters',
  `json_result` varchar(2000) COLLATE utf8_bin DEFAULT '' COMMENT 'Return parameter',
  `status` int(1) DEFAULT '0' COMMENT 'Operation status (0 normal 1 abnormal)',
  `error_msg` varchar(2000) COLLATE utf8_bin DEFAULT '' COMMENT 'Error message',
  `oper_time` datetime DEFAULT NULL COMMENT 'Operation time',
  PRIMARY KEY (`oper_id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='Operation logging';

 

Configure application.yml database connection

server:
  port: 8080
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/aoplog?useUnicode=yes&characterEncoding=UTF-8&useSSL=false
    username: root
    password: 123456

 

New entity class domain folder

SysOperLog.java


import lombok.Data;

import java.util.Date;

/**
 * Operation log
 * 
 * @author hekang
 */
@Data
public class SysOperLog
{
    private static final long serialVersionUID = 1L;

    /** Log key */
    private Long operId;

    /** Operation module */
    private String title;

    /** Business type (0 other 1 new 2 modify 3 delete) */
    private Integer businessType;

    /** Business type array */
    private Integer[] businessTypes;

    /** Request method */
    private String method;

    /** Request mode */
    private String requestMethod;

    /** Operation category (0 other 1 background user 2 mobile user) */
    private Integer operatorType;

    /** Operator */
    private String operName;

    /** Department name */
    private String deptName;

    /** Request url */
    private String operUrl;

    /** Operation address */
    private String operIp;

    /** Operation place */
    private String operLocation;

    /** Request parameters */
    private String operParam;

    /** Return parameter */
    private String jsonResult;

    /** Operation status (0 normal 1 abnormal) */
    private Integer status;

    /** Error message */
    private String errorMsg;

    /** Operation time */
    private Date operTime;
}

If there is no @ Data annotation, please install lombok plug-in in IDEA

 

Create a new service interface class

package com.exception.exceptiondemo.service;


import com.aoplog.springbootaoplog.domain.SysOperLog;

import java.util.List;

/**
 * Operation log service layer
 * 
 * @author hekang
 */
public interface ISysOperLogService
{
    /**
     * New operation log
     * 
     * @param operLog Operation log object
     */
    public void insertOperlog(SysOperLog operLog);

    /**
     * Query system operation log collection
     * 
     * @param operLog Operation log object
     * @return Operation log collection
     */
    public List<SysOperLog> selectOperLogList(SysOperLog operLog);


    /**
     * Query operation log details
     * 
     * @param operId Operation ID
     * @return Operation log object
     */
    public SysOperLog selectOperLogById(Long operId);

    /**
     * Clear operation log
     */
    public void cleanOperLog();
}

 

Create a new service interface implementation class


import com.aoplog.springbootaoplog.domain.SysOperLog;
import com.aoplog.springbootaoplog.mapper.SysOperLogMapper;
import com.aoplog.springbootaoplog.service.ISysOperLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Operation log service layer processing
 *
 * @author hekang
 */
@Service
public class SysOperLogServiceImpl implements ISysOperLogService
{
    @Autowired
    private SysOperLogMapper operLogMapper;

    /**
     * New operation log
     *
     * @param operLog Operation log object
     */
    @Override
    public void insertOperlog(SysOperLog operLog)
    {
        operLogMapper.insertOperlog(operLog);
    }

    /**
     * Query system operation log collection
     *
     * @param operLog Operation log object
     * @return Operation log collection
     */
    @Override
    public List<SysOperLog> selectOperLogList(SysOperLog operLog)
    {
        return operLogMapper.selectOperLogList(operLog);
    }


    /**
     * Query operation log details
     *
     * @param operId Operation ID
     * @return Operation log object
     */
    @Override
    public SysOperLog selectOperLogById(Long operId)
    {
        return operLogMapper.selectOperLogById(operId);
    }

    /**
     * Clear operation log
     */
    @Override
    public void cleanOperLog()
    {
        operLogMapper.cleanOperLog();
    }
}

 

New mapper interface class


import com.aoplog.springbootaoplog.domain.SysOperLog;

import java.util.List;

/**
 * Operation log data layer
 *
 * @author hekang
 */
public interface SysOperLogMapper
{
    /**
     * New operation log
     *
     * @param operLog Operation log object
     */
    public void insertOperlog(SysOperLog operLog);

    /**
     * Query system operation log collection
     *
     * @param operLog Operation log object
     * @return Operation log collection
     */
    public List<SysOperLog> selectOperLogList(SysOperLog operLog);


    /**
     * Query operation log details
     *
     * @param operId Operation ID
     * @return Operation log object
     */
    public SysOperLog selectOperLogById(Long operId);

    /**
     * Clear operation log
     */
    public void cleanOperLog();
}

 

Create a mapper file for SQL

<?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.aoplog.springbootaoplog.mapper.SysOperLogMapper">

	<resultMap type="SysOperLog" id="SysOperLogResult">
		<id     property="operId"         column="oper_id"        />
		<result property="title"          column="title"          />
		<result property="businessType"   column="business_type"  />
		<result property="method"         column="method"         />
		<result property="requestMethod"  column="request_method" />
		<result property="operatorType"   column="operator_type"  />
		<result property="operName"       column="oper_name"      />
		<result property="deptName"       column="dept_name"      />
		<result property="operUrl"        column="oper_url"       />
		<result property="operIp"         column="oper_ip"        />
		<result property="operLocation"   column="oper_location"  />
		<result property="operParam"      column="oper_param"     />
		<result property="jsonResult"     column="json_result"    />
		<result property="status"         column="status"         />
		<result property="errorMsg"       column="error_msg"      />
		<result property="operTime"       column="oper_time"      />
	</resultMap>

	<sql id="selectOperLogVo">
        select oper_id, title, business_type, method, request_method, operator_type, oper_name, dept_name, oper_url, oper_ip, oper_location, oper_param, json_result, status, error_msg, oper_time
        from sys_oper_log
    </sql>
    
	<insert id="insertOperlog" parameterType="SysOperLog">
		insert into sys_oper_log(title, business_type, method, request_method, operator_type, oper_name, dept_name, oper_url, oper_ip, oper_location, oper_param, json_result, status, error_msg, oper_time)
        values (#{title}, #{businessType}, #{method}, #{requestMethod}, #{operatorType}, #{operName}, #{deptName}, #{operUrl}, #{operIp}, #{operLocation}, #{operParam}, #{jsonResult}, #{status}, #{errorMsg}, sysdate())
	</insert>
	
	<select id="selectOperLogList" parameterType="SysOperLog" resultMap="SysOperLogResult">
		<include refid="selectOperLogVo"/>
		<where>
			<if test="title != null and title != ''">
				AND title like concat('%', #{title}, '%')
			</if>
			<if test="businessType != null">
				AND business_type = #{businessType}
			</if>
			<if test="businessTypes != null and businessTypes.length > 0">
			    AND business_type in
			    <foreach collection="businessTypes" item="businessType" open="(" separator="," close=")">
		 			#{businessType}
		        </foreach> 
			</if>
			<if test="status != null">
				AND status = #{status}
			</if>
			<if test="operName != null and operName != ''">
				AND oper_name like concat('%', #{operName}, '%')
			</if>
		</where>
	</select>
 	
 	<select id="selectOperLogById" parameterType="Long" resultMap="SysOperLogResult">
		<include refid="selectOperLogVo"/>
		where oper_id = #{operId}
	</select>
	
	<update id="cleanOperLog">
        truncate table sys_oper_log
    </update>

</mapper> 

When creating a new folder, please note that it cannot be created like this:

In this way, first create a new mapper, and then create a new subdirectory system

 

 

New mybatis profile

<?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>

    <settings>
        <setting name="cacheEnabled"             value="true" />  <!-- Global mapper enable caching -->
        <setting name="useGeneratedKeys"         value="true" />  <!-- allow JDBC Support automatic generation of primary key -->
        <setting name="defaultExecutorType"      value="REUSE" /> <!-- Configure default actuator -->
        <setting name="logImpl"                  value="SLF4J" /> <!-- Appoint MyBatis The implementation of the logs used -->
        <!-- <setting name="mapUnderscoreToCamelCase" value="true"/>  Hump naming -->
    </settings>

</configuration>

 

Configure annotation to start class springbootaoplotapplication

@MapperScan("com.aoplog.**.mapper")

 

Configure mybatis scan directory in application.yml

mybatis:
  type-aliases-package: com.aoplog.springbootaoplog.domain
  configLocation: classpath:mybatis/mybatis-config.xml
  mapperLocations: classpath*:mapper/**/*Mapper.xml

 

New SysOperLogController

import com.aoplog.springbootaoplog.domain.SysOperLog;
import com.aoplog.springbootaoplog.service.ISysOperLogService;
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 SysOperLogController {
    @Autowired
    private ISysOperLogService iSysOperLogService;

    /**
     * Query all logs
     *
     * @return
     */
    @GetMapping("/api/operLog")
    public List<SysOperLog> selectOperLogList() {
        return this.iSysOperLogService.selectOperLogList(null);
    }
}

 

Startup project: http://127.0.0.1:8080/api/operLog

Posted by dirTdogE on Mon, 30 Dec 2019 06:08:42 -0800