Java/mybatis

Mybatis 쿼리 결과 출력하기

바리새인 2025. 1. 18. 17:22

Interceptor 생성

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.mapping.BoundSql;

import java.sql.Connection;
import java.util.Properties;

@Slf4j
@Intercepts({
    @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
})
public class SqlLogInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        BoundSql boundSql = statementHandler.getBoundSql();
        Object parameterObject = boundSql.getParameterObject();
        String sql = boundSql.getSql();

        // Format and replace '?' with actual parameter values
        String formattedSql = formatSql(sql, parameterObject);

        // Log the executed SQL
        log.info("Executed SQL: {}", formattedSql);

        return invocation.proceed();
    }

    private String formatSql(String sql, Object parameterObject) {
        if (parameterObject == null) {
            return sql;
        }

        // Replace '?' with parameter values
        String formattedSql = sql;
        if (parameterObject instanceof java.util.Map) {
            // Handle parameters passed as a Map
            @SuppressWarnings("unchecked")
            java.util.Map<String, Object> paramMap = (java.util.Map<String, Object>) parameterObject;
            for (Object value : paramMap.values()) {
                formattedSql = formattedSql.replaceFirst("\\?", formatValue(value));
            }
        } else {
            // Handle single parameter object
            formattedSql = formattedSql.replaceFirst("\\?", formatValue(parameterObject));
        }

        return formattedSql;
    }

    private String formatValue(Object value) {
        if (value instanceof String) {
            return "'" + value + "'";
        } else if (value == null) {
            return "NULL";
        }
        return value.toString();
    }

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

    @Override
    public void setProperties(Properties properties) {
        // No properties to set
    }
}

Interceptor 추가: mybatis-config.xml

<plugins>
    <plugin interceptor="com.example.SqlLogInterceptor"/>
</plugins>