1、概述
Mapper由两部分组成,分别为Mapper接口和通过注解或者XML文件配置的SQL语句。SqlSession执行Mapper过程分为四部分,Mapper接口的注册过程,MappedStatement对象的注册过程,Mapper方法的调用过程,SqlSession执行Mapper的过程。
2、Mapper接口的注册过程
Mapper接口用于定义执行SQL语句相关的方法,方法名一般和Mapper XML配置文件中select|update|insert|delete标签的id属性相同,接口的完全限定名一般对应Mapper XML配置文件的命名空间。
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = factory.openSession();
// 获取一个由Mybatis自动生成的代理对象。
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getUserById(1);
System.out.println(user);
List<User> users = userMapper.listAllUser();
System.out.println(users);
Java语言中比较常用的实现动态代理的方式有两种,即JDK内置动态代理和CGLIB动态代理。MapperProxy使用的是JDK内置的动态代理,实现了InvocationHandler接口,invoke()方法中为通用的拦截逻辑。
使用JDK内置动态代理,通过MapperProxy类实现InvocationHandler接口,定义方法执行拦截逻辑后,还需要调用java.lang.reflect.Proxy类的newProxyInstance()方法创建代理对象。
Mybatis对这一过程做了封装,使用MapperProxyFactory创建Mapper动态代理对象。
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);
}
}
这里MapperProxyFactory方法都是非静态的。也就是说,使用MapperProxyFactory创建Mapper动态代理对象首先需要创建MapperProxyFactory实例。具体的创建时机是在Configuration对象中有个mapperRegistry属性,具体如下:
protected final MapperRegistry mapperRegistry = new MapperRegistry(this);
Mybatis通过mapperRegistry属性注册Mapper接口与MapperProxyFactory对象之间的对应关系。
MapperRegistry代码如下:
public class MapperRegistry {
// Configuration对象引用
private final Configuration config;
// 用于注册Mapper接口对应的Class对象和MapperProxyFactory对象对应的关系
private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();
public MapperRegistry(Configuration config) {
this.config = config;
}
// 根据Mapper接口Class对象获取Mapper动态代理对象。
@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);
}
}
public <T> boolean hasMapper(Class<T> type) {
return knownMappers.containsKey(type);
}
// 根据Mapper接口Class对象创建MapperProxyFactory对象,并注册到knownMappers属性中。
public <T> void addMapper(Class<T> type) {
if (type.isInterface()) {
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));
// It's important that the type is added before the parser is run
// otherwise the binding may automatically be attempted by the
// mapper parser. If the type is already known, it won't try.
MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
parser.parse();
loadCompleted = true;
} finally {
if (!loadCompleted) {
knownMappers.remove(type);
}
}
}
}
/**
* @since 3.2.2
*/
public Collection<Class<?>> getMappers() {
return Collections.unmodifiableCollection(knownMappers.keySet());
}
/**
* @since 3.2.2
*/
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);
}
}
/**
* @since 3.2.2
*/
public void addMappers(String packageName) {
addMappers(packageName, Object.class);
}
}
在MapperRegistry类有一个knownMappers属性,用于注册Mapper接口对应的Class对象和MapperProxyFactory对象之间的关系。另外,MapperRegistry提供了addMapper()方法,用于向knownMappers属性中注册Mapper接口信息。在addMapper()方法中,为每个Mapper接口对应的Class对象创建一个MapperProxyFactory对象,然后添加到knownMappers属性中。
MapperRegistry还提供了getMapper()方法,能够根据Mapper接口的Class对象获取对应的MapperProxyFactory对象,然后就可以使用MapperProxyFactory对象创建Mapper动态代理对象了。
Mybatis框架在应用启动时会解析所有的Mapper接口,然后调用MapperRegistry对象的addMapper()方法将Mapper接口信息和对应的MapperProxyFactory对象注册到MapperRegistry对象。
3、MappedStatement注册过程
Mybatis通过MappedStatement类描述Mapper的SQL配置信息。SQL配置有两种方式:一种是通过XML文件配置;另一种是通过Java注解,而Java注解的本质就是一种轻量级的配置信息。
在Configuration组件中有一个mappedStatements属性,该属性用于注册Mybatis中所有的MappedStatement对象。
protected final Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>("Mapped Statements collection");
mappedStatement属性是一个Map对象,它的key为Mapper SQL配置的ID,如果SQL是通过XML配置的,则ID为命名空间加上select|update|insert|delete标签的ID,如果SQL通过Java注解配置,则ID为Mapper接口的完全限定名(包括包名)加上方法名称。
另外,Configuration类中提供了一个addMappedStatement()方法,用于将MappedStatement对象添加到mappedStatements属性中。
public void addMappedStatement(MappedStatement ms) {
mappedStatements.put(ms.getId(), ms);
}
MappedStatement注册过程如下:
Mybatis主配置文件的解析是通过XMLConfigBuilder对象来完成的。在XMLConfigBuilder类的parseConfiguration()方法中会调用不同的方法解析对应的标签。
private void parseConfiguration(XNode root) {
try {
//issue #117 read properties first
propertiesElement(root.evalNode("properties"));
Properties settings = settingsAsProperties(root.evalNode("settings"));
loadCustomVfs(settings);
typeAliasesElement(root.evalNode("typeAliases"));
pluginElement(root.evalNode("plugins"));
objectFactoryElement(root.evalNode("objectFactory"));
objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
reflectorFactoryElement(root.evalNode("reflectorFactory"));
settingsElement(settings);
// read it after objectFactory and objectWrapperFactory issue #631
environmentsElement(root.evalNode("environments"));
databaseIdProviderElement(root.evalNode("databaseIdProvider"));
typeHandlerElement(root.evalNode("typeHandlers"));
// 解析mappers标签
mapperElement(root.evalNode("mappers"));
} catch (Exception e) {
throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
}
}
在mapperElement()方法中的实现如下:
private void mapperElement(XNode parent) throws Exception {
if (parent != null) {
for (XNode child : parent.getChildren()) {
// 解析package标签指定的包名
if ("package".equals(child.getName())) {
String mapperPackage = child.getStringAttribute("name");
configuration.addMappers(mapperPackage);
} else {
String resource = child.getStringAttribute("resource");
String url = child.getStringAttribute("url");
String mapperClass = child.getStringAttribute("class");
// 通过resource属性指定XML文件路径
if (resource != null && url == null && mapperClass == null) {
ErrorContext.instance().resource(resource);
InputStream inputStream = Resources.getResourceAsStream(resource);
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
mapperParser.parse();
// 通过url属性指定XML文件路径
} else if (resource == null && url != null && mapperClass == null) {
ErrorContext.instance().resource(url);
InputStream inputStream = Resources.getUrlAsStream(url);
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
mapperParser.parse();
// 通过class属性指定接口的完全限定名
} else if (resource == null && url == null && mapperClass != null) {
Class<?> mapperInterface = Resources.classForName(mapperClass);
configuration.addMapper(mapperInterface);
} else {
throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
}
}
}
}
}
在mapperElement()方法中,首先获取mappers所有子标签mapper标签或package标签,然后根据不同的标签做不同的处理。mappers标签配置Mapper信息有以下几种方式。
<mappers>
<!-- 通过resource属性指定Mapper文件的classpath路径 -->
<mapper resource="mapper/UserMapper.xml"/>
<!-- 通过file属性指定Mapper文件的网络路径 -->
<mapper url="file://***.xml"/>
<!-- 通过class属性指定Mapper接口的完全限定名 -->
<mapper class="com.matrix.dao.User"/>
<!-- 通过package标签指定Mapper接口所在的包名 -->
<package name="com.matrix.dao"/>
</mappers>
mapperElement方法中对这几种情形的配置分别做了处理。
以resource为例介绍Mapper SQL配置文件的解析过程。
Mapper SQL配置文件的解析需要借助XMLMapperBuilder对象。在mapperElement()方法中首先创建一个XMLMapperBuilder对象,然后调用XMLMapperBuilder对象的parse()方法完成解析。
该方法内容如下:
public void parse() {
if (!configuration.isResourceLoaded(resource)) {
// 调用XPathParser的evalNode()方法获取根结点对应的XNode对象
configurationElement(parser.evalNode("/mapper"));
// 将资源路径添加到Configuration对象中
configuration.addLoadedResource(resource);
bindMapperForNamespace();
}
// 继续解析之前解析出现异常的ResultMap对象
parsePendingResultMaps();
// 继续解析之前解析出现异常的CacheRef对象
parsePendingCacheRefs();
// 继续解析之前解析出现异常的select|update|delete|insert标签配置
parsePendingStatements();
}
首先调用XpathParser对象的evalNode()方法获取根结点对应的XNode对象,接着调用configurationElement()方法对Mapper配置内容做进一步解析。
private void configurationElement(XNode context) {
try {
// 获取命名空间
String namespace = context.getStringAttribute("namespace");
if (namespace == null || namespace.equals("")) {
throw new BuilderException("Mapper's namespace cannot be empty");
}
// 设置当前正在解析的Mapper配置的命名空间
builderAssistant.setCurrentNamespace(namespace);
// 解析cache-ref标签
cacheRefElement(context.evalNode("cache-ref"));
// 解析cache标签
cacheElement(context.evalNode("cache"));
// 解析所有的parameterMap标签
parameterMapElement(context.evalNodes("/mapper/parameterMap"));
// 解析所有的resultMap标签
resultMapElements(context.evalNodes("/mapper/resultMap"));
// 解析所有的SQL标签
sqlElement(context.evalNodes("/mapper/sql"));
// 解析所有的select|insert|update|delete标签
buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
} catch (Exception e) {
throw new BuilderException("Error parsing Mapper XML. The XML location is '" + resource + "'. Cause: " + e, e);
}
}
在configurationElement()方法中,对Mapper SQL配置文件的所有标签进行解析。主要看下buildStatementFromContext解析所有的select|insert|update|delete标签。
private void buildStatementFromContext(List<XNode> list, String requiredDatabaseId) {
for (XNode context : list) {
// 通过XMLStatementBuilder对象对select|insert|update|delete标签进行解析
final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, context, requiredDatabaseId);
try {
// 调用parseStatementNode解析
statementParser.parseStatementNode();
} catch (IncompleteElementException e) {
configuration.addIncompleteStatement(statementParser);
}
}
}
如上所示,select|insert|update|delete标签的解析需要依赖于XMLStatementBuilder对象,XMLMapperBuilder类的buildStatementFromContext()方法中对所有的XNode对象进行遍历,然后为每个select|insert|update|delete标签对应的XNode对象创建一个XMLStatementBuilder对象,接着调用XMLStatementBuilder对象的parseStatementNode()方法进行解析处理。
public void parseStatementNode() {
String id = context.getStringAttribute("id");
String databaseId = context.getStringAttribute("databaseId");
if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) {
return;
}
// 解析select|insert|update|delete标签属性
Integer fetchSize = context.getIntAttribute("fetchSize");
Integer timeout = context.getIntAttribute("timeout");
String parameterMap = context.getStringAttribute("parameterMap");
String parameterType = context.getStringAttribute("parameterType");
Class<?> parameterTypeClass = resolveClass(parameterType);
String resultMap = context.getStringAttribute("resultMap");
String resultType = context.getStringAttribute("resultType");
// 获取LanguageDriver对象
String lang = context.getStringAttribute("lang");
LanguageDriver langDriver = getLanguageDriver(lang);
// 获取Mapper返回结果类型Class对象
Class<?> resultTypeClass = resolveClass(resultType);
String resultSetType = context.getStringAttribute("resultSetType");
// 默认Statement类型为PREPARED
StatementType statementType = StatementType.valueOf(context.getStringAttribute("statementType", StatementType.PREPARED.toString()));
ResultSetType resultSetTypeEnum = resolveResultSetType(resultSetType);
String nodeName = context.getNode().getNodeName();
SqlCommandType sqlCommandType = SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH));
boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
boolean flushCache = context.getBooleanAttribute("flushCache", !isSelect);
boolean useCache = context.getBooleanAttribute("useCache", isSelect);
boolean resultOrdered = context.getBooleanAttribute("resultOrdered", false);
// 将include标签内容替换为sql标签定义的SQL片段
// Include Fragments before parsing
XMLIncludeTransformer includeParser = new XMLIncludeTransformer(configuration, builderAssistant);
includeParser.applyIncludes(context.getNode());
// 解析selectKey标签
// Parse selectKey after includes and remove them.
processSelectKeyNodes(id, parameterTypeClass, langDriver);
// 通过LanguageDriver解析SQL内容,生成SqlSource对象
// Parse the SQL (pre: <selectKey> and <include> were parsed and removed)
SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);
String resultSets = context.getStringAttribute("resultSets");
String keyProperty = context.getStringAttribute("keyProperty");
String keyColumn = context.getStringAttribute("keyColumn");
KeyGenerator keyGenerator;
String keyStatementId = id + SelectKeyGenerator.SELECT_KEY_SUFFIX;
keyStatementId = builderAssistant.applyCurrentNamespace(keyStatementId, true);
// 获取主键生成策略
if (configuration.hasKeyGenerator(keyStatementId)) {
keyGenerator = configuration.getKeyGenerator(keyStatementId);
} else {
keyGenerator = context.getBooleanAttribute("useGeneratedKeys",
configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType))
? Jdbc3KeyGenerator.INSTANCE : NoKeyGenerator.INSTANCE;
}
builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
resultSetTypeEnum, flushCache, useCache, resultOrdered,
keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
}
parseStatementNode()方法内容较多,主要做了以下几件事情:
(1)、获取select|insert|update|delete标签的所有属性信息。
(2)、将include标签引用的SQL片段替换为对应的sql标签中定义的内容。
(3)、获取lang属性指定的LanguageDriver,通过LanguageDriver创建SqlSource,Mybatis中的SqlSource表示一个SQL资源。
(4)、获取KeyGenerator对象,KeyGenerator的不同实例代表不同的主键生成策略。
(5)、所有解析工作完成后,使用MapperBuilderAssitant对象的addMappedStatement()方法创建MappedStatement对象。创建完成后,调用Configuration对象的addMappedStatement()方法将MappedStatement对象注册到COnfiguration对象中。
4、Mapper方法调用过程详解
为了执行Mapper接口中定义的方法,首先需要调用SqlSession对象的getMapper()方法获取一个动态代理对象,然后通过代理对象调用方法即可。
Mybatis中的MapperProxy实现了InvocationHandler接口,用于实现动态代理相关逻辑。
invoke方法如下:
@Override
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);
}
final MapperMethod mapperMethod = cachedMapperMethod(method);
return mapperMethod.execute(sqlSession, args);
}
如上所示,在MapperProxy类的invoke()方法中,对从Object继承的方法不做任何处理,对Mapper接口中定义的方法,调用cachedMapperMethod方法获取一个MapperMethod对象。cachedMapperMethod方法内容如下:
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类是对Mapper方法相关信息的封装,通过MapperMethod能够很方便的获取SQL语句的类型、方法签名信息等。
MapperMethod类中包含两个字段:
// 用于获取SQL语句的类型、MapperID等信息
private final SqlCommand command;
// 用于获取方法签名信息
private final MethodSignature method;
SqlCommand类代码如下:
public static class SqlCommand {
private final String name;
private final SqlCommandType type;
public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) {
final String methodName = method.getName();
final Class<?> declaringClass = method.getDeclaringClass();
// 根据Mapper接口的完全限定名和方法名获取对应的MappedStatement对象,
// 然后通过MappedStatement对象获取SQL语句的类型和Mapper的ID。
MappedStatement ms = resolveMappedStatement(mapperInterface, methodName, declaringClass,
configuration);
if (ms == null) {
if (method.getAnnotation(Flush.class) != null) {
name = null;
type = SqlCommandType.FLUSH;
} else {
throw new BindingException("Invalid bound statement (not found): "
+ mapperInterface.getName() + "." + methodName);
}
} else {
name = ms.getId();
type = ms.getSqlCommandType();
if (type == SqlCommandType.UNKNOWN) {
throw new BindingException("Unknown execution method for: " + name);
}
}
}
resolveMappedStatement方法如下:
private MappedStatement resolveMappedStatement(Class<?> mapperInterface, String methodName,
Class<?> declaringClass, Configuration configuration) {
// 获取Mapper的id
String statementId = mapperInterface.getName() + "." + methodName;
if (configuration.hasStatement(statementId)) {
// 如果Configuration对象中已经注册了MappedStatement对象,
// 则获取该MappedStatement对象。
return configuration.getMappedStatement(statementId);
} else if (mapperInterface.equals(declaringClass)) {
return null;
}
// 如果方法是在Mapper父接口中定义的,则根据父接口获取对应的MappedStatement对象
for (Class<?> superInterface : mapperInterface.getInterfaces()) {
if (declaringClass.isAssignableFrom(superInterface)) {
MappedStatement ms = resolveMappedStatement(superInterface, methodName,
declaringClass, configuration);
if (ms != null) {
return ms;
}
}
}
return null;
}
在上面的代码中,首先将接口的完全限定名和方法名进行拼接,作为Mapper的ID从Configuration对象中查找对应的MappedStatement对象,如果查找不到,则判断该方法是否是从父接口中继承的,如果是,就以父接口作为参数递归调用resolveMappedStatement,若找到对应的MappedStatement对象,则返回该对象,否则返回null。
SqlCommand对象封装了SQL语句类型和Mapper的ID。
MethodSignatrue类如下所示:
public static class MethodSignature {
private final boolean returnsMany;
private final boolean returnsMap;
private final boolean returnsVoid;
private final boolean returnsCursor;
private final Class<?> returnType;
private final String mapKey;
private final Integer resultHandlerIndex;
private final Integer rowBoundsIndex;
private final ParamNameResolver paramNameResolver;
public MethodSignature(Configuration configuration, Class<?> mapperInterface, Method method) {
// 获取方法返回值类型
Type resolvedReturnType = TypeParameterResolver.resolveReturnType(method, mapperInterface);
if (resolvedReturnType instanceof Class<?>) {
this.returnType = (Class<?>) resolvedReturnType;
} else if (resolvedReturnType instanceof ParameterizedType) {
this.returnType = (Class<?>) ((ParameterizedType) resolvedReturnType).getRawType();
} else {
this.returnType = method.getReturnType();
}
this.returnsVoid = void.class.equals(this.returnType);
this.returnsMany = configuration.getObjectFactory().isCollection(this.returnType) || this.returnType.isArray();
this.returnsCursor = Cursor.class.equals(this.returnType);
this.mapKey = getMapKey(method);
this.returnsMap = this.mapKey != null;
// RowBounds参数位置索引
this.rowBoundsIndex = getUniqueParamIndex(method, RowBounds.class);
// ResultHandler参数位置索引
this.resultHandlerIndex = getUniqueParamIndex(method, ResultHandler.class);
// ParameterNameResolver用于解析Mapper方法参数
this.paramNameResolver = new ParamNameResolver(configuration, method);
}
...
}
如上所示。MethodSignature构造方法中只做了3件事情:
(1)、获取Mapper方法的返回值类型,具体是哪种类型,通过boolean类型的属性进行标记。
(2)、记录RowBounds参数位置,用于处理后续的分页查询,同时记录ResultHandler参数位置,用于处理从数据库中检索的每一行数据。
(3)、创建ParamNameResolver对象。ParamNameResolver对象用于解析Mapper方法中的参数名称及参数注解信息。
ParamNameResolver中解析方法参数名逻辑如下:
public ParamNameResolver(Configuration config, Method method) {
final Class<?>[] paramTypes = method.getParameterTypes();
// 获取所有参数注解
final Annotation[][] paramAnnotations = method.getParameterAnnotations();
final SortedMap<Integer, String> map = new TreeMap<Integer, String>();
int paramCount = paramAnnotations.length;
// 从@Param注解中获取参数名称
// get names from @Param annotations
for (int paramIndex = 0; paramIndex < paramCount; paramIndex++) {
if (isSpecialParameter(paramTypes[paramIndex])) {
// skip special parameters
continue;
}
String name = null;
for (Annotation annotation : paramAnnotations[paramIndex]) {
// 方法参数中是否有Param注解
if (annotation instanceof Param) {
hasParamAnnotation = true;
// 获取注解属性
name = ((Param) annotation).value();
break;
}
}
// 如果没有@Param注解
if (name == null) {
// @Param was not specified.
if (config.isUseActualParamName()) {
// 获取参数名
name = getActualParamName(method, paramIndex);
}
if (name == null) {
// use the parameter index as the name ("0", "1", ...)
// gcode issue #71
name = String.valueOf(map.size());
}
}
map.put(paramIndex, name);
}
将参数信息保存在names属性中
names = Collections.unmodifiableSortedMap(map);
}
到此为止,整个MapperMethod对象的创建过程已经完成。接下来介绍Mapper方法的执行。
MapperMethod对象提供了一个execute()方法,用于执行SQL命令。
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
// 获取SQL语句类型
switch (command.getType()) {
case INSERT: {
// 获取参数信息
Object param = method.convertArgsToSqlCommandParam(args);
// 调用SqlSession的insert()方法,然后调用rowCountResult()方法统计行数
result = rowCountResult(sqlSession.insert(command.getName(), param));
break;
}
case UPDATE: {
Object param = method.convertArgsToSqlCommandParam(args);
// 调用SqlSession的update()方法
result = rowCountResult(sqlSession.update(command.getName(), param));
break;
}
case DELETE: {
Object param = method.convertArgsToSqlCommandParam(args);
// 调用SqlSession的delete()方法
result = rowCountResult(sqlSession.delete(command.getName(), param));
break;
}
case SELECT:
// 后续源码分析中会详细介绍
if (method.returnsVoid() && method.hasResultHandler()) {
executeWithResultHandler(sqlSession, args);
result = null;
} else if (method.returnsMany()) {
result = executeForMany(sqlSession, args);
} else if (method.returnsMap()) {
result = executeForMap(sqlSession, args);
} else if (method.returnsCursor()) {
result = executeForCursor(sqlSession, args);
} else {
Object param = method.convertArgsToSqlCommandParam(args);
result = sqlSession.selectOne(command.getName(), param);
}
break;
case FLUSH:
result = sqlSession.flushStatements();
break;
default:
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;
}
在execute()方法中,首先根据SqlCommand对象获取SQL语句类型,然后根据SQL语句的类型调用SqlSession对象对应的方法。Mybatis通过动态代理将Mapper方法的调用转换成通过SqlSession提供的API方法完成数据库的增删改查操作,即久的iBatis框架调用Mapper的方式。
5、SqlSession执行Mapper过程
举个例子:
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = factory.openSession();
List<User> users = sqlSession.selectList("com.matrix.dao.UserMapper.listAllUser");
System.out.println(users);
以select语句为例介绍SqlSession执行Mapper的过程。SqlSession接口只有一个默认的实现,即DefaultSqlSession。下面是DefaultSqlSession类对SqlSession接口中定义的selectList()方法的实现:
@Override
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
try {
// 通过Mapper的ID获取对应的MappedStatement对象
MappedStatement ms = configuration.getMappedStatement(statement);
// 以MappedStatement对象作为参数,调用Executor的query()方法。
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();
}
}
下面是BaseExecutor类对query()方法的实现:
@Override
public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
// 获取BoundSql对象,BoundSql是对动态SQL解析生成的SQL语句和参数映射信息的封装。
BoundSql boundSql = ms.getBoundSql(parameter);
// 创建CacheKey,用于缓存Key
CacheKey key = createCacheKey(ms, parameter, rowBounds, boundSql);
// 调用重载的query()方法
return query(ms, parameter, rowBounds, resultHandler, key, boundSql);
}
重载的query()方法如下:
@Override
public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
if (closed) {
throw new ExecutorException("Executor was closed.");
}
if (queryStack == 0 && ms.isFlushCacheRequired()) {
clearLocalCache();
}
List<E> list;
try {
queryStack++;
// 从缓存中获取结果
list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
if (list != null) {
handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
} else {
// 若缓存中获取不到,则调用queryFromDatabase()方法从数据库中查询
list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
}
} finally {
queryStack--;
}
if (queryStack == 0) {
for (DeferredLoad deferredLoad : deferredLoads) {
deferredLoad.load();
}
// issue #601
deferredLoads.clear();
if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
// issue #482
clearLocalCache();
}
}
return list;
}
queryFromDatabase()方法代码如下:
private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
List<E> list;
localCache.putObject(key, EXECUTION_PLACEHOLDER);
try {
// 调用doQuery()方法查询
list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
} finally {
localCache.removeObject(key);
}
localCache.putObject(key, list);
if (ms.getStatementType() == StatementType.CALLABLE) {
localOutputParameterCache.putObject(key, parameter);
}
return list;
}
实现类SimpleExecutor类的doQuery方法如下:
@Override
public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
Statement stmt = null;
try {
Configuration configuration = ms.getConfiguration();
// 获取StatementHandler对象
StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
// 调用prepareStatement()方法创建Statement对象,并进行设置参数等操作
stmt = prepareStatement(handler, ms.getStatementLog());
// 调用StatementHandler对象的query()方法执行查询操作
return handler.<E>query(stmt, resultHandler);
} finally {
closeStatement(stmt);
}
}
prepareStatement()方法如下:
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
Statement stmt;
// 获取JDBC中的Connection对象
Connection connection = getConnection(statementLog);
// 调用StatementHandler的prepare()方法创建Statement对象
stmt = handler.prepare(connection, transaction.getTimeout());
// 调用StatementHandler对象的parameterize()方法设置参数
handler.parameterize(stmt);
return stmt;
}
PreparedStatementHandler的query()方法如下:
Override
public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
PreparedStatement ps = (PreparedStatement) statement;
// 调用PreparedStatement对象的execute()方法执行SQL语句
ps.execute();
// 调用ResultSetHandler的handleResultSets()方法处理结果集
return resultSetHandler.<E> handleResultSets(ps);
}
handleResultSets方法如下:
@Override
public List<Object> handleResultSets(Statement stmt) throws SQLException {
ErrorContext.instance().activity("handling results").object(mappedStatement.getId());
final List<Object> multipleResults = new ArrayList<Object>();
int resultSetCount = 0;
ResultSetWrapper rsw = getFirstResultSet(stmt);
List<ResultMap> resultMaps = mappedStatement.getResultMaps();
int resultMapCount = resultMaps.size();
validateResultMapsCount(rsw, resultMapCount);
while (rsw != null && resultMapCount > resultSetCount) {
ResultMap resultMap = resultMaps.get(resultSetCount);
handleResultSet(rsw, resultMap, multipleResults, null);
rsw = getNextResultSet(stmt);
cleanUpAfterHandlingResultSet();
resultSetCount++;
}
String[] resultSets = mappedStatement.getResultSets();
if (resultSets != null) {
while (rsw != null && resultSetCount < resultSets.length) {
ResultMapping parentMapping = nextResultMaps.get(resultSets[resultSetCount]);
if (parentMapping != null) {
String nestedResultMapId = parentMapping.getNestedResultMapId();
ResultMap resultMap = configuration.getResultMap(nestedResultMapId);
handleResultSet(rsw, resultMap, null, parentMapping);
}
rsw = getNextResultSet(stmt);
cleanUpAfterHandlingResultSet();
resultSetCount++;
}
}
return collapseSingleResultList(multipleResults);
}
到此为止,Mybatis如何调用Mapper接口定义的方法执行注解或者XML文件中配置的SQL语句这一整套链路介绍完毕。