MyBatis Interceptor를 이용한 SQL 추적
MyBatis Interceptor는 쿼리가 실행되기 전/후의 흐름을 가로채는 기능이다. 이를 이용하면 다음과 같은 작업이 가능하다:
- SQL 실행 시간 측정
- 파라미터 값 로그 출력
- 공통 값 주입 (userId, tenantId 등)
- 느린 쿼리 감지 및 경고 로그
🧪 예제: SQL 파라미터 로깅용 MyBatis Interceptor
@Intercepts({
@Signature(
type = Executor.class,
method = "query",
args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
)
})
public class SqlLogInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement ms = (MappedStatement) invocation.getArgs()\[0\];
Object parameterObject = invocation.getArgs()\[1\];
String sql = ms.getBoundSql(parameterObject).getSql();
List parameterMappings = ms.getBoundSql(parameterObject).getParameterMappings();
Map paramMap = (parameterObject instanceof Map) ? (Map) parameterObject : new HashMap<>();
// 파라미터 가공
for (ParameterMapping pm : parameterMappings) {
Object value = extractPart(paramMap, pm);
sql = sql.replaceFirst("\\\\?", value.toString());
}
System.out.println("실행 SQL: " + sql);
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) { }
}
🔍 핵심 유틸: extractPart() 함수
위 Interceptor에서 사용된 이 함수는 SQL 파라미터를 실제 SQL에서 사용할 수 있도록 포맷팅해주는 핵심 도우미다.
Object extractPart(Map p, ParameterMapping m) {
Object out = p.get(m.getProperty());
if (out instanceof String) {
return "'" + out + "'";
} else if (out == null) {
return "NULL";
}
return out;
}
🎯 역할 요약
쿼리결과가 아래처럼 로그가 찍힘
"홍길동" (String) -> '홍길동'
null -> NULL
30 (Integer) -> 30
이렇게 포맷팅된 값들을 순서대로 치환해서, 완성된 SQL 로그를 만들 수 있다.
✅ 마무리 요약
SQL 로그 추적 시 Interceptor + extractPart() 유용 |
---|
고급 디버깅/분석 가능 |
---|
반응형
'기타' 카테고리의 다른 글
adsp 벼락치기 - 아답터 유튜브 강의 요약(3. 데이터분석 일부) (4) | 2025.08.04 |
---|---|
[ADsP] 헷갈리는 통계(표본추출법, 가설검정) (1) | 2025.08.04 |
[ADsP] 40회 기출문제 풀이 오답정리 (3) | 2025.08.03 |
[ADsP] 데이터분석 부분 챗지피티와 공부한 내용 요약 (4) | 2025.08.02 |
MyBatis 설정 파일(sql-mapper-config, mybatis-config 등) 기본 설명 (0) | 2025.04.15 |