SqlSession 是Mybatis提供给用户与数据库交互的重要接口,我们一般调用其getMapper方法获取mapper接口的代理类,由代理类来与数据库交互,那么我们先来看看SqlSession的getMapper方法
public <T> T getMapper(Class<T> type) {
return configuration.<T>getMapper(type, this);
}
好吧,调用的是configuration的泛型方法getMapper,我们再进入Configuration.getMapper中
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
return mapperRegistry.getMapper(type, sqlSession);
}
又调用的是mapperRegistry(映射注册类)的gtMapper方法,mapperRegistry是咋来的?我们把源码往上翻可以看到
protected MapperRegistry mapperRegistry = new MapperRegistry(this);
直接new出来的并把我们的Configuration传入进去了,那我们再看看MapperRegistry是怎么实现的
private Configuration config;
//这个hashMap存储的是接口类型和其对应的MapperproxyFactory
private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();
public MapperRegistry(Configuration config) {
this.config = config;
}
/**
* 从knownMappers中取出接口类型对应的MapperProxyFactory,如果不存在则报错这个类型并没有注册,
* 如果存在则返回一个实例
*/
@SuppressWarnings("unchecked")
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);
}
}
/**
* 注册Mapper接口,把接口对应的mapper.xml加载到Configuration中
* */
public <T> void addMapper(Class<T> type) {
// 必须是接口
if (type.isInterface()) {
//如果接口已经注册,抛出异常,从这可以看出一个mapper接口只能对应一个mapper.xml文件
if (hasMapper(type)) {
throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
}
boolean loadCompleted = false;
try {
//加入容器中
knownMappers.put(type, new MapperProxyFactory<T>(type));
//把映射的Mapper.xml文件加载到Configuration中
MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
parser.parse();
//加载结束
loadCompleted = true;
} finally {
//如果加载异常从注册容器中删除
if (!loadCompleted) {
knownMappers.remove(type);
}
}
}
}
public void addMappers(String packageName, Class<?> superType) {
ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<Class<?>>();
resolverUtil.find(new ResolverUtil.IsA(superType), packageName);
Set<Class<? extends Class<?>>> mapperSet = resolverUtil.getClasses();
for (Class<?> mapperClass : mapperSet) {
addMapper(mapperClass);
}
}
MapperRegistry 是一个映射注册器,当XmlConfigBuild读取核心配置文件的< mappers > 节点时就调用addMappers方法(配置读取包时)或者addMapper方法把所有配置的mapper接口注册到MapperRegistry的knownMappers 当中,并加载所有的mapper.xml文件把各个节点<select|insert|update|update>等封装到Configuration。
而当我们获取代理对象的时候直接从knownMappers 取出mapperProxyFactory返回实例
public class MapperProxyFactory<T> {
private final Class<T> mapperInterface;
private 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")
//用的是jdk的动态代理,根据接口的类加载器,接口的所有父接口,InvocationHandler实例,返回mapper接口实例
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
//MapperProxy实现了InvocationHandler接口,定义了代理类的行为
public T newInstance(SqlSession sqlSession) {
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
}
我们可以看到最终使用了JDK的动态代理返回了mapper接口的代理实例,而mapperProxy实现了InvocationHandler接口,其定义了代理类的行为
/**
* 用于增强mapper接口的代理类
*/
public class MapperProxy<T> implements InvocationHandler, Serializable {
private static final long serialVersionUID = -6424540398559729838L;
private final SqlSession sqlSession;
private final Class<T> mapperInterface;
private final Map<Method, MapperMethod> methodCache;
public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
this.sqlSession = sqlSession;
this.mapperInterface = mapperInterface;
this.methodCache = methodCache;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 判断是否是一个类
if (Object.class.equals(method.getDeclaringClass())) {
try {
return method.invoke(this, args);
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
}
// 如果不是一个类,取得mapperMethod,调用execute方法
final MapperMethod mapperMethod = cachedMapperMethod(method);
return mapperMethod.execute(sqlSession, args);
}
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;
}
}
代理类的主要执行逻辑定义在invoke方法里面,我们所有的mapper接口代理类都执行的是这个逻辑,这也可以理解,mapper接口所定义的功能无非就是增删改查执行的是Mapper.xml里面的Sql。
我们需要注意的是MapperMethod这个对象,在注册mapper接口的时候会把接口的所有方法以及其对应的<select|insert|update|delete>节点封装成对象存入ConcurrentHashMap中,再invoke方法中根据方法名从ConcurrentHashMap取出
public class MapperMethod {
/**
* 根据mapper接口的方法对应的节点回调SqlSession中的方法,
* */
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
//如果执行增删改的操作,用rowCountResult这个方法处理返回值
if (SqlCommandType.INSERT == command.getType()) {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.insert(command.getName(), param));
} else if (SqlCommandType.UPDATE == command.getType()) {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.update(command.getName(), param));
} else if (SqlCommandType.DELETE == command.getType()) {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.delete(command.getName(), param));
} else if (SqlCommandType.SELECT == command.getType()) {
//如果代理方法返回值为void,并且设置了ResultHandle,结果集封装到ResultHandle中
if (method.returnsVoid() && method.hasResultHandler()) {
executeWithResultHandler(sqlSession, args);
result = null;
} else if (method.returnsMany()) {
//returnsMany是这样定义的 this.returnsMany = (configuration.getObjectFactory().isCollection(this.returnType) || this.returnType.isArray());
//无论你方法返回值写的是Collection类型,还是arry,executeForMany都给你返回list
result = executeForMany(sqlSession, args);
} else if (method.returnsMap()) {
result = executeForMap(sqlSession, args);
} else {
Object param = method.convertArgsToSqlCommandParam(args);
result = sqlSession.selectOne(command.getName(), param);
}
} else {
throw new BindingException("Unknown execution method for: " + command.getName());
}
if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
throw new BindingException("Mapper method '" + command.getName()
+ " attempted to return null from a method with a primitive return type (" + method.getReturnType()
+ ").");
}
return result;
}
/**
* 根据方法返回类型取得具体的值
* 如果未void,返回null,
* 是Integr或者int 不变
* 是long 向上转型
* 是Boolean : 判断是否大于0,这也说明了可以直接设置返回值类型为boolean来判断是否修改了数据
* */
private Object rowCountResult(int rowCount) {
final Object result;
if (method.returnsVoid()) {
result = null;
} else if (Integer.class.equals(method.getReturnType()) || Integer.TYPE.equals(method.getReturnType())) {
result = rowCount;
} else if (Long.class.equals(method.getReturnType()) || Long.TYPE.equals(method.getReturnType())) {
result = (long) rowCount;
} else if (Boolean.class.equals(method.getReturnType()) || Boolean.TYPE.equals(method.getReturnType())) {
result = (rowCount > 0);
} else {
throw new BindingException("Mapper method '" + command.getName() + "' has an unsupported return type: "
+ method.getReturnType());
}
return result;
}
}
mapperMethod根据返回值类型以及Mapper接口所对应的节点的不同 回调了SqlSession中的方法,兜兜转转我们又回到了DefaultSqlSession,我们先来看看查询时怎样执行的,其实无论时查询多条还是单条都时调用的selectList方法,查询单条只是取第一条罢了
public class DefaultSqlSession implements SqlSession {
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
try {
MappedStatement ms = configuration.getMappedStatement(statement);
List<E> result = executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
return result;
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
}
public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds) {
final List<?> list = selectList(statement, parameter, rowBounds);
final DefaultMapResultHandler<K, V> mapResultHandler = new DefaultMapResultHandler<K, V>(mapKey,
configuration.getObjectFactory(), configuration.getObjectWrapperFactory());
final DefaultResultContext context = new DefaultResultContext();
for (Object o : list) {
context.nextResultObject(o);
mapResultHandler.handleResult(context);
}
Map<K, V> selectedMap = mapResultHandler.getMappedResults();
return selectedMap;
}
如果返回类型是Map,MapperMethod调用selectMap,这里有两个参数mapKey,rowBounds分别是mapper接口上的注解@MapKey和mybatis自带的分页功能,这些我们以后会专门拎出来分析。我们现在可以看到selectMap方法第一句就调用了selectList方法,selectLisl执行sql委托给了executor,传入了xml中的id(方法名)所对应的节点对象,好了,SqlSession先到这里,我们下一章看看Executor是怎样执行sql放回结果集的
[上一篇]: Mybatis 源码分析一 SqlSessionFactory
[下一篇]: Mybais 源码分析三 Executor
本文深入剖析MyBatis框架中Mapper接口的工作原理,包括如何通过SqlSession获取Mapper实例、Mapper注册过程及代理对象创建机制。揭示了MyBatis如何利用JDK动态代理和Mapper接口定义,高效执行SQL语句。
1万+

被折叠的 条评论
为什么被折叠?



