SoFunction
Updated on 2025-04-11

Two ways to count SQL runtime in Mybatis

need:

Spring Boot + Mybatis web project, counts the SQL runtime, is used to analyze slow SQL and optimizes system speed.

There are two solutions:

  • Customize Interceptor to implement more flexible.
  • Using the existing dependency library (Druid): The advantage is that it is simple and easy to get started, but only sql information is counted and no call parameter information is found.

1. Mybatis native interceptor

Record the execution time of SQL query and SQL statements in MyBatis. You can use MyBatis' Interceptor. By implementing a custom interceptor, you can capture the start and end times of SQL execution, calculate the execution time, and log the SQL statements to the log.

  • Custom interceptor, example:
import ;
import .*;
import ;
import ;
import ;
import ;

import ;
import ;

@Intercepts({
    @Signature(type = , method = "query", args = {, }),
    @Signature(type = , method = "update", args = {}),
    @Signature(type = , method = "batch", args = {})
})
public class SqlExecutionInterceptor implements Interceptor {

    private static final Log logger = ();

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // Get SQL statement        StatementHandler statementHandler = (StatementHandler) ();
        BoundSql boundSql = ();
        String sql = ().replaceAll("\\s+", " ").trim();

        // Record the start time        long startTime = ();

        // Execute SQL        Object result = ();

        // Calculate execution time        long endTime = ();
        long executionTime = endTime - startTime;

        // Record SQL statements and execution time        ("SQL: " + sql);
        ("Execution time: " + executionTime + " ms");

        return result;
    }

    @Override
    public Object plugin(Object target) {
        return (target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // Parameters can be passed to the interceptor through the configuration file    }
}

  • Inject Bean
@Configuration
public class MyBatisConfig {
    @Bean
    public SqlExecutionInterceptor sqlExecutionInterceptor() {
        return new SqlExecutionInterceptor();
    }
}

Note: You can print logs into separate log files in combination with logback and other configurations.

2. Use Druid for monitoring

2.1 Druid

  • Add dependencies:
<dependency>
    <groupId></groupId>
    <artifactId>druid</artifactId>
    <version>1.2.8</version> <!-- Use the latest version number -->
</dependency>
  • Configure Druid data source
spring:
  datasource:
    druid:
      url: jdbc:mysql://localhost:3306/your_database
      username: your_username
      password: your_password
      driver-class-name: 
      # Enable Druid monitoring function      filters: stat
      # Configure slow SQL records      maxActive: 20
      initialSize: 1
      minIdle: 1
      maxWait: 60000
      # Set the slow query threshold in milliseconds      slowSqlMillis: 2000
      logSlowSql: true
  • Enable Druid monitoring Servlets and Filters
import ;
import ;
import ;
import ;
import ;
import ;

@Configuration
public class DruidConfig {

    // Register Druid's monitoring Servlet    @Bean
    public ServletRegistrationBean<StatViewServlet> druidServlet() {
        ServletRegistrationBean<StatViewServlet> servletRegistrationBean = 
                new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
        // Set the login username and password        ("loginUsername", "admin");
        ("loginPassword", "admin123");
        return servletRegistrationBean;
    }

    // Register Druid's monitoring filter    @Bean
    public FilterRegistrationBean<WebStatFilter> filterRegistrationBean() {
        FilterRegistrationBean<WebStatFilter> filterRegistrationBean = 
                new FilterRegistrationBean<>(new WebStatFilter());
        // Set filtered URL mode        ("/*");
        // Ignored resources        ("exclusions", "*.js,*.css,/druid/*");
        return filterRegistrationBean;
    }
}
  • Visit the Druid monitoring page: After starting the application, you can access http://localhost:8080/druid (the default port is 8080) in the browser, and check the SQL execution status, slow SQL and other detailed information after logging in.

2.2 druid-spring-boot-starter

Just like Spring Boot and Spring, Alibaba provides druid-spring-boot-starter to enable related Filters based on configuration more conveniently.

  • Add dependencies:
 <dependency>
    <groupId></groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.8</version>
</dependency>

  • Configure data sources and monitoring information
############# Monitoring configuration# Whether to enable StatFilter, the default value is false=true
# Set the url pattern for monitoring intercepting. If you do not configure the default, all requests will be intercepted.-pattern=/*
# Set unintercepted urls, separated by English commas=/druid/*
# Whether to enable Session statistics function, the default value is true-stat-enable=true
# Set the maximum number of session statistics, -1 means no limit, the default value is 1000-stat-max-count=1000
# Set the Principal name of Session statistics, the default value is "sessionStat"-session-name=sessionStat
# Set the cookie name that saves the Session ID, the default value is "sessionStatMaxCount"-cookie-name=sessionStatMaxCount
# Whether to enable the profile, if it is enabled, you need to configure the filter for Druid monitoring: profile-enable=true

######### StatViewServlet Configuration# Whether to enable StatViewServlet, the default value is false (considering security issues, it is recommended to set passwords or whitelists to ensure security if you need to enable)=true
# Set the access path of the monitoring page, default is /druid/*-pattern=/druid/*
# Whether to allow resetting of monitoring data, the default value is true-enable=true
# Set the login username of the monitoring page, which is empty by default (if the login username and password are set, the login box will pop up when accessing the monitoring page)-username=admin
# Set the login password for the monitoring page, which is empty by default (if the login username and password are set, the login box will pop up when accessing the monitoring page)-password=123456
# Set the IP address list that allows access to the monitoring page. Multiple IP addresses are separated by English commas, and the default is empty (if a whitelist is set, only the IP addresses in the whitelist can access the monitoring page)=127.0.0.1,192.168.1.1
# Set the IP address list that prohibits access to the monitoring page. Multiple IP addresses are separated by English commas, and the default is empty (if a blacklist is set, the IP addresses in the blacklist cannot access the monitoring page)=192.168.1.2

#### Slow sql# Enable Druid monitoring filter=true
# Is it slow to record SQL query-slow-sql=true
# Database type, here is MySQL-type=mysql
# Define the threshold for slow SQL queries in milliseconds-sql-millis=1000
  • Log configuration
 &lt;!--   slowsql   --&gt;
    &lt;appender name="slowSqlLog" class=""&gt;
        &lt;File&gt;${}/slow_sql-${}.log&lt;/File&gt;
        &lt;!--Scrolling strategy,Scroll by time TimeBasedRollingPolicy--&gt;
        &lt;rollingPolicy class=""&gt;
            &lt;!--File path,Defines the way to split the logs——Archives the logs of each day into a file,To prevent logs from filling the entire disk space--&gt;
            &lt;FileNamePattern&gt;${}/arch/slow_sql/slow_sql.%d{yyyy-MM-dd}.%&lt;/FileNamePattern&gt;
            &lt;!-- The most single log files 100MB --&gt;
            &lt;maxFileSize&gt;100MB&lt;/maxFileSize&gt;
            &lt;!--Keep only the most recent10Day's log--&gt;
            &lt;maxHistory&gt;10&lt;/maxHistory&gt;
            &lt;!--Used to specify the upper limit size of the log file,Then this value,The old log will be deleted--&gt;
            &lt;totalSizeCap&gt;1GB&lt;/totalSizeCap&gt;
        &lt;/rollingPolicy&gt;
        &lt;!--Log output encoding format--&gt;
        &lt;encoder&gt;
            &lt;charset&gt;UTF-8&lt;/charset&gt;
            &lt;pattern&gt;[%d{yyyy-MM-dd HH:mm:ss}|%mdc{traceId}|] - %msg%n&lt;/pattern&gt;
        &lt;/encoder&gt;
    &lt;/appender&gt;

    &lt;logger name="" level="info" additivity="false"&gt;
        &lt;appender-ref ref="slowSqlLog"/&gt;
    &lt;/logger&gt;

The above is the detailed content of two ways to count SQL runtime in Mybatis. For more information on Mybatis stating SQL runtime, please pay attention to my other related articles!