1. 程式人生 > 實用技巧 >mybatis 自定義外掛 獲取元資料 spring boot + mybatis plus(prepareStatement.getMetaData())

mybatis 自定義外掛 獲取元資料 spring boot + mybatis plus(prepareStatement.getMetaData())

@org.springframework.context.annotation.Configuration
@MapperScan(basePackages = {"xxx.xxx.xxx"})
public class MybatisPlusConfig {

@Bean
public ConfigurationCustomizer configurationCustomizer() {
ConfigurationCustomizer time = new ConfigurationCustomizer() {
@Override
public void customize(Configuration configuration) {
MyMetaDataInterceptor myPlugin = new MyMetaDataInterceptor();
Properties properties = new Properties();
//這裡設定慢查詢閾值為1毫秒,便於測試
properties.setProperty("xxxtest", "xxx");
myPlugin.setProperties(properties);
configuration.addInterceptor(myPlugin);
}
};
return time;
}

}




@Intercepts({
@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
})
public class MyMetaDataInterceptor implements Interceptor {
private static Logger log = LoggerFactory.getLogger(MyMetaDataInterceptor.class);
private String xxxtest;
//方法攔截
@Override
public Object intercept(Invocation invocation) throws Throwable {
log.info("測試配置檔案的值:"+xxxtest);
//通過StatementHandler獲取執行的sql
StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
Connection con = (Connection) invocation.getArgs()[0];
MetaObject metaObject = MetaObject.forObject(statementHandler, SystemMetaObject.DEFAULT_OBJECT_FACTORY, SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY, new DefaultReflectorFactory());
//String value= (String) metaObject.getValue("delegate.mappedStatement.id");
//log.info("方法名為:"+value);
BoundSql boundSql = statementHandler.getBoundSql();
String sql = boundSql.getSql();
PreparedStatement prepareStatement = con.prepareStatement(sql);
//ParameterHandler paraHander = (ParameterHandler) metaObject.getValue("delegate.parameterHandler");
//paraHander.setParameters(prepareStatement);
ResultSetMetaData rsmd = prepareStatement.getMetaData();
for (int i = 0; i < rsmd.getColumnCount(); i++) {
String cloName=rsmd.getColumnLabel(i + 1);
log.info(cloName);
}
Object proceed = invocation.proceed();
return proceed;
}

//獲取到攔截的物件,底層也是通過代理實現的,實際上是拿到一個目標代理物件
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}

@Override
public void setProperties(Properties properties) {
this.xxxtest = properties.getProperty("xxxtest");
}

}