0前言
mybatis有一个很好的特性.在写mapper的时候,我们只需要在代码中写出mapper的interface,具体的实现由mybatis根据xml帮助我们实现.今天我们可以详细了解这其中的奥秘.
总的来说,使用的基本原理就是java的动态代理.当Mapper 对象其实是一个java代理.代理的处理类型为MapperProxy<T>
其中T就是我们的接口类型.怎么样有模板函数出现了
当一个查询出现的时候由MapperProxy进行数据库查询.下面我可以分别来看看实现细节.
1代理的构建.
下面的代码是获取mapper的代码
studentMapper = session.getMapper(StudentMapper.class);
session的类型为DefaultSqlSession
最终处理地方为org.apache.ibatis.binding.MapperRegistry#getMapper
mapperProxyFactory存储了Mapper的Interface(我们自己写的Interface).
1.1处理
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.然后使用动态代理创建了代理.
MyBatis动态代理揭秘
本文深入探讨MyBatis框架如何利用Java动态代理机制来实现Mapper接口的具体操作。通过解析核心代码,展示从构建代理到执行数据库查询的全过程。
3271

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



