0

Hi I'm reading myBatis' source code and my problem is that I don't understand the line SqlSessionManager.this.localSqlSession.get(). What's the meaning of SqlSessionManager.this?

My trying: If I remember it correctly When create a nested class say A.B nestedObjectB = new A.B(); It actually create an object A.B and an anonymous object A for it. So I guess SqlSessionManager.this is analogous to the object A here?

(In 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);
          }
        }
      }
    }
  }
NeoZoom.lua
  • 2,269
  • 4
  • 30
  • 64
  • 2
    Does this answer your question? [Java: Class.this](https://stackoverflow.com/questions/5530256/java-class-this) – Adwait Kumar Dec 24 '19 at 19:12
  • @AdwaitKumar: So why it is used here? If SqlSessionInterceptor doesn't has attribute `localSqlSession`? Why not just write `locatSqlSession.get()`? – NeoZoom.lua Dec 24 '19 at 19:25
  • Cause it wants to ensure that the outer class `localSqlSession` is referred, if you used this it would refer to the object of `SqlSessionInterceptor` which doesn't have a `localSqlSession` – Adwait Kumar Dec 24 '19 at 19:29

1 Answers1

1

SqlSessionManager.this refers to the outer class, if you just used this it would refer to SqlSessionInterceptor which doesn't have a localSqlSession.

If you used just localSqlSession it would refer to the immediate outer class. If there was another outerClass between SqlSessionManager and SqlSessionInterceptor, then it would refer to that class instead of SqlSessionManager. Adding SqlSessionManager.this explicitly declares to use the one present in SqlSessionManager

See : https://stackoverflow.com/a/1816462/ , https://stackoverflow.com/a/5530293

EDIT :

Referring to https://github.com/mybatis/mybatis-3/blob/master/src/main/java/org/apache/ibatis/session/SqlSessionManager.java#L347, it seems this is being done only for readability.

Adwait Kumar
  • 1,552
  • 10
  • 25