Previous: The creation process of SqlSession in mybatis source code analysis
https://my.oschina.net/u/657390/blog/663991
It focuses on the creation process of SqlSession. After the successful creation of SqlSession:
String resource = "com/analyze/mybatis/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
Map map = sqlSession.selectOne("com.analyze.mybatis.mapper.UserMapper.getUA");
sqlSession.close();
String resource = "com/analyze/mybatis/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
Map map = userMapper.getUA();
sqlSession.close();
The above two pieces of code will end up with the same result.
The difference between the two pieces of code can be found by comparison:
Map map = sqlSession.selectOne("com.analyze.mybatis.mapper.UserMapper.getUA");
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
Map map = userMapper.getUA();
根据sqlSession.selectOne("com.analyze.mybatis.mapper.UserMapper.getUA");
It is conceivable that selectOne will use com.analyze.mybatis.mapper.UserMapper.getUA to find the corresponding configuration, and then execute sql.
Then analyze sqlSession.selectOne()
DefaultSqlSession.java
public <T> T selectOne(String statement) {
return this.<T>selectOne(statement, null);
}
public <T> T selectOne(String statement, Object parameter) {
// Popular vote was to return null on 0 results and throw exception on too many.
List<T> list = this.<T>selectList(statement, parameter);
if (list.size() == 1) {
return list.get(0);
} else if (list.size() > 1) {
throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
} else {
return null;
}
}
public <E> List<E> selectList(String statement, Object parameter) {
return this.selectList(statement, parameter, RowBounds.DEFAULT);
}
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
try {
//从配置中获取statement信息
MappedStatement ms = configuration.getMappedStatement(statement);
//调用执行器
return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
But UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
Map map = userMapper.getUA(); These two lines of code can see some problems, the interface UserMapper is not implemented in the code, that is to say userMapper.getUA() ; is not implemented, but it can be called in the end. So how is this implemented?
Further analysis of the source code:
DefaultSqlSession.java
public <T> T getMapper(Class<T> type) {
return configuration.<T>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);
}
}
It can be seen from the above code that the final call is mapperProxyFactory.newInstance()
Then analyze the source code of MapperProxyFactory
public class MapperProxyFactory<T> {
private final Class<T> mapperInterface;
private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();
public MapperProxyFactory(Class<T> mapperInterface) {
this.mapperInterface = mapperInterface;
}
public Class<T> getMapperInterface() {
return mapperInterface;
}
public Map<Method, MapperMethod> getMethodCache() {
return methodCache;
}
@SuppressWarnings("unchecked")
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[]{mapperInterface}, mapperProxy);
}
public T newInstance(SqlSession sqlSession) {
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
}
From the MapperProxy in newInstance, it is easy to see that a dynamic proxy is used.
Let's take a look at the invoke in MapperProxy
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//当执行的方法是继承自Object时执行this里的相应方法
if (Object.class.equals(method.getDeclaringClass())) {
try {
return method.invoke(this, args);
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
}
final MapperMethod mapperMethod = cachedMapperMethod(method);
//最终执行的是execute方法
return mapperMethod.execute(sqlSession, args);
}
It can be seen from the above code that mapperMethod.execute(sqlSession, args) is executed when calling the interface in mapper;
Continue to follow up the code and you will find that the above example finally executes
sqlSession.selectOne(command.getName(), param);
It can be said to be the same destination.
The classes involved in mapper dynamic proxy are MapperRegistry, MapperProxyFactory, MapperProxy, MapperMethod
MapperRegistry's data source Configuration.java
MapperRegistry mapperRegistry = new MapperRegistry(this);
The method parseConfiguration() in XMLConfigBuilder calls mapperElement(root.evalNode("mappers"));
mapperElement() will call addMapper() and finally add data to knownMappers in MapperRegistry
After analyzing the source code, you can follow the code above to implement your own functions:
public interface UserService {
Map getUser();
}
public class ServiceProxy implements InvocationHandler {
public <T> T newInstance(Class<T> clz) {
return (T) Proxy.newProxyInstance(clz.getClassLoader(), new Class[]{clz}, this);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (Object.class.equals(method.getDeclaringClass())) {
return method.invoke(this, args);
}
System.out.println("----proxy----" + method.getName());
return null;
}
}
//测试代码
public static void main(String[] args) {
UserService userService = new ServiceProxy().newInstance(UserService.class);
userService.toString();
userService.getUser();
}
//输出结果
----proxy----getUser