【开源中国 APP 全新上线】“动弹” 回归、集成大模型对话、畅读技术报告”
@JFinal 你好,想跟你请教个问题/**
* Get Connection. Support transaction if Connection in ThreadLocal
*/
public final Connection getConnection() throws SQLException {
Connection conn = threadLocal.get();
if (conn != null)
return conn;
return showSql ? new SqlReporter(dataSource.getConnection()).getConnection() : dataSource.getConnection();
}
showSql ? new SqlReporter(dataSource.getConnection()).getConnection() : dataSource.getConnection();
这行代码的意义是什么?从指定的数据源中获取连接,然后再创建一个SqlReporter对象,再获取这个连接(不是同一个么?)
showsql是?
SqlReporter的作用(自己理解):
1、用来处理,执行SQL语句时的日志显示
2、此外作用:麻烦补充下:
Connection getConnection() {
Class clazz = conn.getClass();
return (Connection)Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{Connection.class}, this);
}
这个,多谢!
showSql 是个开关变量,当值为 true 时会向控制台输出被执行的 sql 语句,方便开发时排错。
SqlReporter 实现了 java.lang.reflect.InvocationHandler 接口,所以是个代理类,它将为 Connection 对象提供代理功能,也即在 Connection 对象在调用方法时会首先调用 SqlReporter 类中的 invoke 方法,从而可以实现对目标对象方法的拦截,在目标方法执行之前输出 sql。
SqlReporter 结合 showSql 开关变量来用,就是当 showSql 为 true 时创建 SqlReporter 代理 Connection 以便实现代理,否则直接使用 Connection 对象。
google 一下 java 代理,了解一下 InvocatgionHandler 的用法就完全清楚了。至于Proxy.newProxyInstance(...) 这仅仅是 java 代理约定好的具体用法。