Mybatis配置之请求数据库时打印SQL语句,一份字节跳动面试官给你的Java技术面试指南

本文介绍了如何使用Mybatis的SQLInterceptor来实现运行时打印SQL语句,以便于调试和优化数据库操作。同时,文章还提及了一线大厂Java面试中可能涉及的技术点,包括后端开发的相关知识。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SQLInterceptor.java

package com.guide.util;

i

《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》

【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 完整内容开源分享

mport java.sql.Connection;

import java.util.Date;

import java.util.Properties;

import org.apache.ibatis.executor.statement.BaseStatementHandler;

import org.apache.ibatis.executor.statement.RoutingStatementHandler;

import org.apache.ibatis.executor.statement.StatementHandler;

import org.apache.ibatis.mapping.BoundSql;

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.Plugin;

import org.apache.ibatis.plugin.Signature;

/**

  • 运行时SQL输出

*/

@Intercepts({ @Signature(type = StatementHandler.class, method = “prepare”, args = { Connection.class }) })

public class SQLInterceptor implements Interceptor {

public Object intercept(Invocation invocation) throws Throwable {

RoutingStatementHandler statementHandler = (RoutingStatementHandler) invocation.getTarget();

BoundSql boundSql = statementHandler.getBoundSql();

BaseStatementHandler delegate = (BaseStatementHandler) ReflectHelper.getValueByFieldName(statementHandler,

“delegate”);

MappedStatement mappedStatement = (MappedStatement) ReflectHelper.getValueByFieldName(delegate,

“mappedStatement”);

System.err.println("-------------------------------------------------" + mappedStatement.getId());

System.out.println(“sql:”+DateUtil.getDetailDate(new Date())+":"+boundSql.getSql());

return invocation.proceed();

}

public Object plugin(Object arg0) {

return Plugin.wrap(arg0, this);

}

public void setProperties(Properties properties) {

}

}

ReflectHelper.java

package com.guide.util;

import java.lang.reflect.Field;

/**

  • 反射工具

*/

public class ReflectHelper {

/**

  • 获取obj对象fieldName的Field

  • @param obj

  • @param fieldName

  • @return

*/

public static Field getFieldByFieldName(Object obj, String fieldName) {

for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {

try {

return superClass.getDeclaredField(fieldName);

} catch (NoSuchFieldException e) {

}

}

return null;

}

/**

  • 获取obj对象fieldName的属性值

  • @param obj

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值