The creation of mybatis - mapper.java

1, Mapper.java creation process

When registering the bean, the beanClass is replaced with MapperFactoryBean. When creating an instance, the getObject() method of MapperFactoryBean will be called to get the instance

  @Override
  public T getObject() throws Exception {
    return getSqlSession().getMapper(this.mapperInterface);
  }

  public SqlSession getSqlSession() {
    return this.sqlSession;
  }

The sqlSession here is the SqlSessionTemplate instance created in the configuration class

Therefore, getMapper calls the getMapper method of SqlSessionTemplate. The specific calling process is a bit tortuous. Finally, it will call the getMapper method of MapperRegistry

  // SqlSessionTemplate.java
  @Override
  public <T> T getMapper(Class<T> type) {
    return getConfiguration().getMapper(type, this);
  }

 |
 |
\|/
 
// Configuration.java public <T> T getMapper(Class<T> type, SqlSession sqlSession) { return mapperRegistry.getMapper(type, sqlSession); } | | \|/
// MapperRegistry.java public <T> T getMapper(Class<T> type, SqlSession sqlSession) { final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type); if (mapperProxyFactory == null) { throw new BindingException("Type " + type + " is not known to the MapperRegistry."); } try { return mapperProxyFactory.newInstance(sqlSession); } catch (Exception e) { throw new BindingException("Error getting mapper instance. Cause: " + e, e); } }

newInstance calls MapperProxyFactory's method:

  //MapperProxyFactory.java
public T newInstance(SqlSession sqlSession) { final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache); return newInstance(mapperProxy); } protected T newInstance(MapperProxy<T> mapperProxy) { return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy); }

From here, we can see that for the UserMapper.java interface, the jdk proxy is used to create an instance, and the proxy processing class is MapperProxy

Tags: Java JDK

Posted on Thu, 13 Feb 2020 12:37:48 -0800 by smclay