首页 > 编程语言 > 详细

mybatis 自定义插件 获取元数据 spring boot + mybatis plus(prepareStatement.getMetaData())

时间:2020-07-28 22:51:07      阅读:258      评论:0      收藏:0      [点我收藏+]
@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");
}

}



mybatis 自定义插件 获取元数据 spring boot + mybatis plus(prepareStatement.getMetaData())

原文:https://www.cnblogs.com/jingzhi-sksk/p/13393047.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!