Last active
December 15, 2022 04:05
-
-
Save A-pZ/57952b2e50c2c22fc535fa13619a9e62 to your computer and use it in GitHub Desktop.
MyBatis Plugin(クエリ発行時にSQL-IDを出力)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8" ?> | |
<!DOCTYPE configuration | |
PUBLIC "-//mybatis.org//DTD Config 3.0//EN" | |
"https://mybatis.org/dtd/mybatis-3-config.dtd"> | |
<configuration> | |
<plugins> | |
<plugin interceptor="com.github.apz.sample.config.mybatis.SqlIdLoggingInterceptor"></plugin> | |
</plugins> | |
</configuration> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.github.apz.sample.config.mybatis; | |
import lombok.extern.slf4j.Slf4j; | |
import org.apache.ibatis.executor.Executor; | |
import org.apache.ibatis.mapping.MappedStatement; | |
import org.apache.ibatis.plugin.Interceptor; | |
import org.apache.ibatis.plugin.Intercepts; | |
import org.apache.ibatis.plugin.Invocation; | |
import org.apache.ibatis.plugin.Signature; | |
import org.apache.ibatis.session.ResultHandler; | |
import org.apache.ibatis.session.RowBounds; | |
@Intercepts({ | |
@Signature( | |
type = Executor.class, | |
method = "query", | |
args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class} | |
) | |
}) | |
@Slf4j | |
public class SqlIdLoggingInterceptor implements Interceptor { | |
@Override | |
public Object intercept(Invocation invocation) throws Throwable { | |
// @Signatureのtype属性に指定したクラスのarg属性(=ここではExecutorのメソッド引数になる)を取得。 | |
// MappedStatementはMyBatisがパラメータをバインドした結果のクエリを扱う | |
MappedStatement statement = (MappedStatement)invocation.getArgs()[0]; | |
// MyBatisのマッピングID(実行するクエリのMyBatisのid) | |
log.info("sql-id: {}", statement.getId()); | |
// クエリの実行 | |
Object result = invocation.proceed(); | |
// 実行後の制御をここに追記 | |
// インターセプトの終了 | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment