嗨,我正在阅读myBatis的源代码,我的问题是我不理解SqlSessionManager.this.localSqlSession.get()
行。 SqlSessionManager.this
是什么意思?
[我的尝试:如果我没记错的话]创建嵌套类时说A.B nestedObjectB = new A.B();
它实际上为它创建了一个对象A.B
和一个匿名对象A
。所以我猜SqlSessionManager.this
类似于对象A
?
(在SqlSessionManager.java
中]
private class SqlSessionInterceptor implements InvocationHandler {
public SqlSessionInterceptor() {
// Prevent Synthetic Access
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
final SqlSession sqlSession = SqlSessionManager.this.localSqlSession.get(); // *
if (sqlSession != null) {
try {
return method.invoke(sqlSession, args);
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
} else {
try (SqlSession autoSqlSession = openSession()) {
try {
final Object result = method.invoke(autoSqlSession, args);
autoSqlSession.commit();
return result;
} catch (Throwable t) {
autoSqlSession.rollback();
throw ExceptionUtil.unwrapThrowable(t);
}
}
}
}
}
[SqlSessionManager.this
指的是外部类,如果您只使用了this
,它将指的是没有SqlSessionInterceptor
的localSqlSession
。
如果仅使用localSqlSession
,它将引用直接外部类。如果SqlSessionManager
和SqlSessionInterceptor
之间还有另一个externalClass,则它将引用该类而不是SqlSessionManager
。显式添加SqlSessionManager.this
声明使用SqlSessionManager
请参见:https://stackoverflow.com/a/1816462/,https://stackoverflow.com/a/5530293
编辑:
参考https://github.com/mybatis/mybatis-3/blob/master/src/main/java/org/apache/ibatis/session/SqlSessionManager.java#L347,看来这样做只是为了提高可读性。