不要把时间、财力和劳动,浪费在空洞多余的话语上。永远以用心乐观的心态去拓展自我和身外的世界
回顾
上节初始化说道
我们可以通过两种形式来执行CURD操作
DefaultSqlSession形式
User user = (User)sqlsession.selectOne("com.wqd.mapper.UserMapper.selectUser","111");
Mapper形式
UserMapper userMapper = sqlsession.getMapper(UserMapper.class);
User user = userMapper.selectUser("111");
第一种形式虽然有很简单,但是我们需要自己找对应SQL 的定位id(namsespace+id)写到方法参数中。
反而第二种方式,采用方法调用的方式,不见了SQL定位字符串,更加符合开发人员的开发习惯。
Mapper 是如何实现的?如何解决SQL定位的问题呢?
Mapper原理
当我们从sqlsession获取一个Mapper时,sqlsession会以 mapper的Class对象与 当前sqlsession 自身 为参数去configuration对象中取。
public class DefaultSqlSession implements SqlSession {
public <T> T getMapper(Class<T> type) {
return configuration.<T>getMapper(type, this);
}
}
Configuration#getMapper 要从mapperRegistry 中获取
public class Configuration {
protected final MapperRegistry mapperRegistry = new MapperRegistry(this);
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
return mapperRegistry.getMapper(type, sqlSession);
}
}
MapperRegistry为每一个Mapper 配一个MapperProxyFactory工厂。列如UserMapper <--->new MapperProxyFactory<>(UserMapper.class)
public class MapperRegistry {
private final Configuration config;
//mapper缓存,一个Mapper接口对应一个工厂。
private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();
//获取Mapper
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
//取出Mapper对应的MapperProxyFactory 工厂
final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
if (mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
}
try {
//从对应的工厂中生产一个Mapper代理类
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception e) {
throw new BindingException("Error getting mapper instance. Cause: " + e, e);
}
}
}
Mapper的关键点至此浮出水面:为每一个Mapper配一个MapperProxyFactory 工厂。
下面看看MapperProxyFactory的生产过程
public class MapperProxyFactory<T> {
private final Class<T> mapperInterface;
//方法缓存
private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();
@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);
}
}
- 首先创建一个MapperProxy,从其继承图来看。 MapperProxy 其实就是InvocationHandler ,也就是增强器。
- 其次使用Proxy 为UserMapper 创建一个代理类,并用(InvocationHandler )MapperProxy 增强器对其进行增强。
也就是当我们调用
UserMapper userMapper = session.getMapper(UserMapper.class)
- 我们获取到的userMapper是一个由MapperProxyFactory 为我们创建的代理类对象。
- userMapper代理对象会被一个MapperProxy增强器,进行增强。
- 当执行UserMapper的方法时,会执行增强器MapperProxy 的invoke方法
MapperProxy
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if (Object.class.equals(method.getDeclaringClass())) {
return method.invoke(this, args);
} else if (isDefaultMethod(method)) {
return invokeDefaultMethod(proxy, method, args);
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
//创建并缓存一个MapperMethod
final MapperMethod mapperMethod = cachedMapperMethod(method);
//执行方法。
return mapperMethod.execute(sqlSession, args);
}
// 创建MapperMethod方法,并缓存
private MapperMethod cachedMapperMethod(Method method) {
MapperMethod mapperMethod = methodCache.get(method);
if (mapperMethod == null) {
mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
methodCache.put(method, mapperMethod);
}
return mapperMethod;
}
MapperMethod
真正的执行方法会被MapperMethod进行包装。
//构造方法:
public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
this.command = new SqlCommand(config, mapperInterface, method);
this.method = new MethodSignature(config, mapperInterface, method);
}
public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) {
//找到SQL对应的MappedStatement
MappedStatement ms = resolveMappedStatement(mapperInterface, methodName, declaringClass,
configuration);
//把MappedStatement.id做为SqlCommand.name(=namespace.id)
name = ms.getId();
}
我看看其execute方法
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
switch (command.getType()) {
case INSERT: {
Object param = method.convertArgsToSqlCommandParam(args);
//更加command.getName 来定位SQL
result = rowCountResult(sqlSession.insert(command.getName(), param));
break;
}
case UPDATE: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.update(command.getName(), param));
break;
}
....
}
可以看到:
- session 还 是那个session
- command.getName() 其实就是 MappedStatement #getId 也就是namsespace.id
- 最终还是依靠session.xxxx方法来执行。
殊途同归
我们再重新看一下这两种方式:
1.DefaultSqlSession形式:直接使用namespace.id进行SQL目标的定位
User user = (User)sqlsession.selectOne("com.wqd.mapper.UserMapper.selectUser","111");
2.Mapper形式: 通过方法调用的形式
UserMapper userMapper = sqlsession.getMapper(UserMapper.class);
User user = userMapper.selectUser("111");
其背后的工作:
- MapperProxyFactory 为UserMapper接口创建一个代理类对象,并用
(InvocationHandler)MapperProxy
对其进行增强 - 调用selectUser方法,执行MapperProxy增强器invoke方法,封装selectUser为MapperMethod。
- 执行MapperMethod#execute方法,找到selectUser方法对应的KEY (namspace.id )
- 执行session.selectOne(“com.wqd.mapper.UserMapper.selectUser”,“111”)
其背后的调用链:
userMapper#selectUser–>MapperProxy#invoke–>MapperMethod#execute–>sqlsession.selectOne
也就说mapper 绕了这么一大圈子,最终还是回到了以namespace.id定位SQL模板这一操作上。
总结
Mapper通过保存SQL模板与方法之间的映射关系+动态代理技术,变namespace.id 字符串定位SQL模板的形式,为方法调用的形式,完美的切合了开发人员的开发习惯,并减少出错概率。不得不说确实优秀
如果本文任何错误,请批评指教,不胜感激 !
微信公众号:源码行动
享学源码,行动起来,来源码行动