Java/mybatis

Mybatis 로그에 실행 쿼리 출력하기

바리새인 2025. 1. 29. 00:23
import java.util.List;
import java.util.Map;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;

public List<Map<String, Object>> getList(Map<String, Object> where) {
    // Get the MappedStatement
    Configuration configuration = sqlSessionFactory.getConfiguration();
    MappedStatement mappedStatement = configuration.getMappedStatement("test.getList");
    
    // Get the BoundSql
    BoundSql boundSql = mappedStatement.getBoundSql(where);
    
    // Get the raw SQL
    String rawSql = boundSql.getSql();
    
    // Replace '?' placeholders with parameter values
    String finalSql = replacePlaceholdersWithValues(rawSql, boundSql, configuration, where);

    // Log the final SQL
    log.debug("Executing SQL: {}", finalSql);

    // Execute the query
    return attachMapper.getList(where);
}

private String replacePlaceholdersWithValues(String rawSql, BoundSql boundSql, Configuration configuration, Map<String, Object> parameterObject) {
    // Get the parameter values from the BoundSql
    List<org.apache.ibatis.mapping.ParameterMapping> parameterMappings = boundSql.getParameterMappings();
    
    if (parameterMappings == null || parameterMappings.isEmpty()) {
        return rawSql; // No parameters, return the raw SQL
    }

    // Replace '?' with actual parameter values
    for (org.apache.ibatis.mapping.ParameterMapping parameterMapping : parameterMappings) {
        String propertyName = parameterMapping.getProperty();
        Object value = parameterObject.get(propertyName); // Get the parameter value
        String valueAsString = (value == null) ? "null" : "'" + value.toString() + "'";
        rawSql = rawSql.replaceFirst("\\?", valueAsString); // Replace the first '?' with the value
    }

    return rawSql;
}