在用mybatis的时候,我们只需要写一个接口,然后服务层就能调用,在我们的认知中,是不能直接调接口的方法的,这个其中的原理是什么呢?由于自己比较好奇,就取翻了一下mybatis的源码,一下是做的一些记录。
通过一个最简单的例子来揭开它的面目。
@Test
public void testDogSelect() throws IOException {
String resource = "allconfig.xml";// ①
InputStream inputStream = Resources.getResourceAsStream(resource);// ②
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);// ③
SqlSession session = sqlSessionFactory.openSession();// ④
DogMapper dogMapper = session.getMapper(DogMapper.class);// ⑤
List<Dog> dogs = dogMapper.selectDog();//⑥
System.out.println(dogs.size());// ⑦
}
首先就是①②两行是没什么要解释的,就从第三行开始,我们追踪代码,进入SqlSessionFactoryBuilder的build(InputStream)的方法
public SqlSessionFactory build(InputStream inputStream) {
return build(inputStream, null, null);
}
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.
}
}
}
重要代码就两行,其中XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);是构建破解器用的,主要看下一行build(parser.parse()),其中parser.parse()主要就是把我们的mybatis的配置文件进行解析,并把解析的大部分内容保存到Configuration中。然后看build的代码
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
返回了一个DefaultSqlSessionFactory
继续看④这一句,我们知道sqlSessionFactory实际上是DefaultSqlSessionFactory的一个实例,进入DefaultSqlSessionFactory的openSession()方法
@Override
public SqlSession openSession() {
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
try {
final Environment environment = configuration.getEnvironment();
final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
final Executor executor = configuration.newExecutor(tx, execType);
return new DefaultSqlSession(configuration, executor, autoCommit);
} catch (Exception e) {
closeTransaction(tx); // may have fetched a connection so lets call close()
throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
其他我们都先不管,我们只要看到这个方法返回的是一个DefaultSqlSession的实例就好
我们继续看⑤这一行,session是DefaultSqlSession的一个实例。我们进入DefaultSqlSession的getMapper(Class type)方法,
@Override
public <T> T getMapper(Class<T> type) {
return configuration.<T>getMapper(type, this);
}
其中configuration是Configuration的实例,在解析mybatis的配置文件的时候进行的初始化。继续追进去
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
return mapperRegistry.getMapper(type, sqlSession);
}
继续进到MapperRegistry的getMapper(Class type, SqlSession sqlSession)方法
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);
}
}
此方法根据传进来的type生成对应的代理,我们进入看看MapperProxyFactory
public T newInstance(SqlSession sqlSession) {
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
到这里已经看到已经完成代理的生成,MapperProxyFactory是个工厂。再继续看MapperProxy这个类
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;
}
@Override
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);
}
}
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方法方法,我看看到如果调用的是我们自定的方法,直接就是调用的mybatis的实现,通过接口找到配置信息,然后根据我们的配置去操作数据库。
最后总结一下,mybatis之所以配置接口以后就能执行是因为在生产mapper的时候实质上是生成的一个代理,然后通过mapper调用接口方法的时候直接被MapperProxy的invoke截断了,直接去调用了mybatis为我们制定的实现,而没有去回调。