1.前言
Mybatis是目前最流行的持久層架構之一,其官方使用手冊詳見:http://www.mybatis.org/mybatis-3/zh/index.html。
使用Mybatis主要分為以下幾個步驟:
1) 添加mybatis依賴到pom檔案(maven項目)或jar包到項目中;
2) 添加mybatis-config.xml配置檔案,包含的配置資訊與配置方式詳見使用手冊;
3) 解析配置檔案并建立Configuration對象configuration;
4) 使用configuration建立SqlSessionFactory對象;
5) 通過sqlSession擷取mapper執行個體,并調用mapper接口中方法與DB互動。
下面就對上述步驟涉及到的主要源碼進行分析講解,源碼版本mybatis-3.4.4。
2.構造SqlSessionFactory執行個體
通過SqlSessionFactoryBuilder構造應用級别SqlSessionFactory執行個體,核心代碼如下:
// inputStream,mybatis-config.xml配置檔案的輸入流
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
try {
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
return build(parser.parse());
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try {
inputStream.close();
} catch (IOException e) {
// Intentionally ignore. Prefer previous error.
}
}
}
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
構造過程如下:
1)建立XMLConfigBuilder對象parser,同時建立了Configuration對象configuration;
2)調用parser.parser()解析mybatis配置檔案,保持配置資訊到configuration中;
3)建立SqlSessionFactory執行個體,即DefaultSqlSessionFactory對象。
3.解析mybatis配置檔案
解析mybatis配置檔案核心代碼如下:
public Configuration parse() {
if (parsed) {
throw new BuilderException("Each XMLConfigBuilder can only be used once.");
}
parsed = true;
// 解析mybatis配置檔案
parseConfiguration(parser.evalNode("/configuration"));
return configuration;
}
// 依次解析mybatis配置檔案中各元素
private void parseConfiguration(XNode root) {
try {
// 解析元素properties,儲存在variables中
propertiesElement(root.evalNode("properties"));
Properties settings = settingsAsProperties(root.evalNode("settings"));
loadCustomVfs(settings);
// 解析元素typeAliases,儲存在typeAliasRegistry中
typeAliasesElement(root.evalNode("typeAliases"));
// 解析插元素plugins,儲存在interceptorChain中
pluginElement(root.evalNode("plugins"));
// 解析元素objectFactory,儲存在objectFactory中
objectFactoryElement(root.evalNode("objectFactory"));
// 解析元素objectWrapperFactory,儲存在objectWrapperFactory中
objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
// 解析元素reflectorFactory,儲存在reflectorFactory中
reflectorFactoryElement(root.evalNode("reflectorFactory"));
// 解析元素settings,儲存在configuration的屬性中
settingsElement(settings);
// read it after objectFactory and objectWrapperFactory issue #631
// 解析元素environments,儲存在environment中
environmentsElement(root.evalNode("environments"));
// 解析元素databaseIdProvider,儲存在databaseId中
databaseIdProviderElement(root.evalNode("databaseIdProvider"));
// 解析元素typeHandlers,儲存在typeHandlerRegistry中
typeHandlerElement(root.evalNode("typeHandlers"));
// 解析元素mappers,儲存在mapperRegistry中,下面會詳細分析
mapperElement(root.evalNode("mappers"));
} catch (Exception e) {
throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
}
}
4.解析mappers元素
4.1 mappers配置方式
mappers有四種配置方式,如下所示:
(1) <mapper resource=”org/mybatis/builder/AuthorMapper.xml”/>
(2) <mapper url=”file:///var/mappers/AuthorMapper.xml”/>
(3) <mapper class=”org.mybatis.builder.AuthorMapper”/>
(4) <package name=”org.mybatis.builder”/>
詳細配置詳見:http://www.mybatis.org/mybatis-3/configuration.html#mappers.
4.2解析mappers核心代碼
private void mapperElement(XNode parent) throws Exception {
if (parent != null) {
for (XNode child : parent.getChildren()) {
if ("package".equals(child.getName())) {
// 對應配置方式(4),查找屬性name指定包下所有的接口類型,注冊到mapperRegistry
String mapperPackage = child.getStringAttribute("name");
configuration.addMappers(mapperPackage);
} else {
String resource = child.getStringAttribute("resource");
String url = child.getStringAttribute("url");
String mapperClass = child.getStringAttribute("class");
if (resource != null && url == null && mapperClass == null) {
// 對應配置方式(1),解析resource屬性指定的mapper配置檔案并添加配置到mapperRegistry
ErrorContext.instance().resource(resource);
InputStream inputStream =Resources.getResourceAsStream(resource);
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
mapperParser.parse();
} else if (resource == null && url != null && mapperClass == null) {
// 對應配置方式(2),解析url屬性指定的mapper配置檔案并添加配置到mapperRegistry
ErrorContext.instance().resource(url);
InputStream inputStream = Resources.getUrlAsStream(url);
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
mapperParser.parse();
} else if (resource == null && url == null && mapperClass != null) {
// 對應配置方式(3),添加class屬性指定的mapper配置到mapperRegistry
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.");
}
}
}
}
}
mappers的前兩種配置解析步驟:
1) 建立XMLMapperBuilder對象mapperParser,調用mapperParser.parse()解析*mapper.xml檔案;
2) 以mapper配置檔案的namespace屬性值為type,建立type對應的MapperProxyFactory,并注冊mapperd到mapperRegistry中。
mappers的後兩種配置解析步驟:
1) 以mapper接口類型為type,建立type對應的MapperProxyFactory,并注冊mapper到mapperRegistry中;
2) 建立XMLMapperBuilder對象mapperParser,調用mapperParser.parse()解析*mapper.xml檔案。
4.3 MapperRegistry源碼分析
MapperRegistry是mybatis中用于注冊mapper到configuration的核心類,其源碼如下:
public class MapperRegistry {
private final Configuration config;
private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();
public MapperRegistry(Configuration config) {
this.config = config;
}
/**
* 當執行sqlSession.getMapper(Class<T> type)方法時會調用該方法,
* 取出type對應的MapperProxyFactory對象,傳回mapper的代理對象mapperProxy
*/
@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> 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 {
// 以mapper類型為參數建立mapper的代理工廠對象,并将其儲存,
knownMappers.put(type, new MapperProxyFactory<T>(type));
MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
parser.parse();
loadCompleted = true;
} finally {
if (!loadCompleted) {
knownMappers.remove(type);
}
}
}
}
......
}
5.MapperProxyFactory源碼分析
MapperProxyFactory是MapperProxy的工廠類,其核心源碼如下:
public class MapperProxyFactory<T> {
private final Class<T> mapperInterface;
// 構造函數接收mapper接口類型,用于建立mapper的代理對象mapperProxy
public MapperProxyFactory(Class<T> mapperInterface) {
this.mapperInterface = mapperInterface;
}
@SuppressWarnings("unchecked")
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
// 該方法實際上就是建立mapperProxy的工廠方法
public T newInstance(SqlSession sqlSession) {
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
......
}
6.MapperProxy源碼分析
Mapper接口的jdk動态代理調用處理類,調用mapper接口方法會執行代理類invoke方法。核心代碼如下:
public class MapperProxy<T> implements InvocationHandler, Serializable {
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;
}
@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);
/*
* 執行下面的方法,會調用sqlSession的insert、update、delete、select等方法,進而調用executor執行sql等操作
*/
return mapperMethod.execute(sqlSession, args);
}
......
}
7.執行mapper接口方法
SqlSession session = sqlSessionFactory.openSession(true);
try {
// mapper實際上是BlogMapper接口的代理對象mapperProxy
BlogMapper mapper = session.getMapper(BlogMapper.class);
// 實際上執行的時MapperProxy的invoke方法
Blog blog = mapper.selectBlog();
} finally {
session.close();
}