1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.ibatis.logging.jdbc;
17
18 import java.lang.reflect.InvocationHandler;
19 import java.lang.reflect.Method;
20 import java.lang.reflect.Proxy;
21 import java.sql.CallableStatement;
22 import java.sql.PreparedStatement;
23 import java.sql.ResultSet;
24
25 import org.apache.ibatis.logging.Log;
26 import org.apache.ibatis.reflection.ExceptionUtil;
27
28
29
30
31
32
33
34
35 public final class PreparedStatementLogger extends BaseJdbcLogger implements InvocationHandler {
36
37 private final PreparedStatement statement;
38
39 private PreparedStatementLogger(PreparedStatement stmt, Log statementLog, int queryStack) {
40 super(statementLog, queryStack);
41 this.statement = stmt;
42 }
43
44 @Override
45 public Object invoke(Object proxy, Method method, Object[] params) throws Throwable {
46 try {
47 if (Object.class.equals(method.getDeclaringClass())) {
48 return method.invoke(this, params);
49 }
50 if (EXECUTE_METHODS.contains(method.getName())) {
51 if (isDebugEnabled()) {
52 debug("Parameters: " + getParameterValueString(), true);
53 }
54 clearColumnInfo();
55 if ("executeQuery".equals(method.getName())) {
56 ResultSet rs = (ResultSet) method.invoke(statement, params);
57 return rs == null ? null : ResultSetLogger.newInstance(rs, statementLog, queryStack);
58 } else {
59 return method.invoke(statement, params);
60 }
61 } else if (SET_METHODS.contains(method.getName())) {
62 if ("setNull".equals(method.getName())) {
63 setColumn(params[0], null);
64 } else {
65 setColumn(params[0], params[1]);
66 }
67 return method.invoke(statement, params);
68 } else if ("getResultSet".equals(method.getName())) {
69 ResultSet rs = (ResultSet) method.invoke(statement, params);
70 return rs == null ? null : ResultSetLogger.newInstance(rs, statementLog, queryStack);
71 } else if ("getUpdateCount".equals(method.getName())) {
72 int updateCount = (Integer) method.invoke(statement, params);
73 if (updateCount != -1) {
74 debug(" Updates: " + updateCount, false);
75 }
76 return updateCount;
77 } else {
78 return method.invoke(statement, params);
79 }
80 } catch (Throwable t) {
81 throw ExceptionUtil.unwrapThrowable(t);
82 }
83 }
84
85
86
87
88
89
90
91
92
93 public static PreparedStatement newInstance(PreparedStatement stmt, Log statementLog, int queryStack) {
94 InvocationHandler handler = new PreparedStatementLogger(stmt, statementLog, queryStack);
95 ClassLoader cl = PreparedStatement.class.getClassLoader();
96 return (PreparedStatement) Proxy.newProxyInstance(cl, new Class[]{PreparedStatement.class, CallableStatement.class}, handler);
97 }
98
99
100
101
102
103
104 public PreparedStatement getPreparedStatement() {
105 return statement;
106 }
107
108 }