mybatis如何通过接口查找对应的mapper.xml及方法执行详解
发布时间 - 2026-01-11 01:55:11 点击率:次本文主要介绍的是关于mybatis通过接口查找对应mapper.xml及方法执行的相关内容,下面话不多说,来看看详细的介绍:

在使用mybatis的时候,有一种方式是
BookMapper bookMapper = SqlSession().getMapper(BookMapper.class)
获取接口,然后调用接口的方法。只要方法名和对应的mapper.xml中的id名字相同,就可以执行sql。
那么接口是如何与mapper.xml对应的呢?
首先看下,在getMapper()方法是如何操作的。
在DefaultSqlSession.Java中调用了configuration.getMapper()
public <T> T getMapper(Class<T> type) {
return configuration.<T>getMapper(type, this);
}
在Configuration.java中调用了mapperRegistry.getMapper(type, sqlSession);
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
return mapperRegistry.getMapper(type, sqlSession);
}
下面重点来了,在MapperRegistry.java中实现了动态代理
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);
}
}
这个函数分两部分来看,首先是从map集合中获取接口代理,map集合的来源,第二部分获取代理后实例化,获取接口的方法,执行sql。
对于第一部分:集合的来源。
这个MapperRegistry.java中有个方法是addMappers();共有两个重载。
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);
}
}
//解析包名下的接口
public void addMappers(String packageName) {
addMappers(packageName, Object.class);
}
往上追溯该方法的调用是在SqlSessionFactory.build();时对配置文件的解析,其中对节点mappers的解析,这里先不赘述,
mapperElement(root.evalNode("mappers"));
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 {
//使用mapper节点
String resource = child.getStringAttribute("resource");
String url = child.getStringAttribute("url");
String mapperClass = child.getStringAttribute("class");
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();
} 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();
} 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.");
}
}
}
}
}
这是调用addMapper()的顺序。
同时在改方法中还有一个方法很重要
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));
//根据接口名寻找同包下同名的xml或者mapper的namespace是该接口的xml
//找到对用的xml后进行解析mapper节点里面的节点
MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
parser.parse();
loadCompleted = true;
} finally {
if (!loadCompleted) {
knownMappers.remove(type);
}
}
}
}
这是通过接口的全路径来查找对应的xml。这里有两种方式解析,也就是我们平常xml文件放置位置的两种写法。
第一种是不加namespace,把xml文件放在和接口相同的路径下,同时xml的名字与接口名字相同,如接口名为Student.java,xml文件为Student.xml。在相同的包下。这种当时可以不加namespace.
第二种是加namespace,通过namespace来查找对应的xml.
到这就是接口名和xml的全部注册流程。
下面再说下第二部分就是通过动态代理获取接口名字来对应xml中的id。
主要有两个类MapperProxyFactory.java和MapperProxy.java
对于MapperProxyFactory.java
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")
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.java中进行方法的执行
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;
}
至此,就是mybatis所有接口和xml的加载,以及通过动态代理来进行接口的执行的过程。
总结
以上就是这篇文章的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对的支持。
# mybatis
# mapper.xml
# mapper接口
# mybatis的mapper.xml
# 详解Mybatis通用Mapper介绍与使用
# Java的MyBatis框架中对数据库进行动态SQL查询的教程
# MyBatis 执行动态 SQL语句详解
# mybatis mapper.xml中如何根据数据库类型选择对应SQL语句
# 这是
# 不加
# 第二部分
# 的是
# 是在
# 来了
# 放在
# 有个
# 相关内容
# 这就是
# 两种
# 有一种
# 遍历
# 是从
# 很重要
# 还有一个
# 来看看
# 这篇文章
# 有两种
# 谢谢大家
相关栏目:
【
网站优化151355 】
【
网络推广146373 】
【
网络技术251813 】
【
AI营销90571 】
相关推荐:
如何快速配置高效服务器建站软件?
JS碰撞运动实现方法详解
BootStrap整体框架之基础布局组件
Laravel怎么定时执行任务_Laravel任务调度器Schedule配置与Cron设置【教程】
如何快速搭建高效服务器建站系统?
成都网站制作公司哪家好,四川省职工服务网是做什么用?
Laravel Asset编译怎么配置_Laravel Vite前端构建工具使用
零基础网站服务器架设实战:轻量应用与域名解析配置指南
悟空识字怎么关闭自动续费_悟空识字取消会员自动扣费步骤
如何在阿里云完成域名注册与建站?
深圳防火门网站制作公司,深圳中天明防火门怎么编码?
Python制作简易注册登录系统
jQuery 常见小例汇总
Java类加载基本过程详细介绍
Linux系统命令中tree命令详解
bing浏览器学术搜索入口_bing学术文献检索地址
百度浏览器如何管理插件 百度浏览器插件管理方法
Laravel如何使用Spatie Media Library_Laravel图片上传管理与缩略图生成【步骤】
购物网站制作费用多少,开办网上购物网站,需要办理哪些手续?
android nfc常用标签读取总结
高防服务器:AI智能防御DDoS攻击与数据安全保障
Android利用动画实现背景逐渐变暗
jQuery validate插件功能与用法详解
JavaScript模板引擎Template.js使用详解
javascript基本数据类型及类型检测常用方法小结
大学网站设计制作软件有哪些,如何将网站制作成自己app?
Android仿QQ列表左滑删除操作
Laravel怎么设置路由分组Prefix_Laravel多级路由嵌套与命名空间隔离【步骤】
简单实现jsp分页
JS中对数组元素进行增删改移的方法总结
品牌网站制作公司有哪些,买正品品牌一般去哪个网站买?
Laravel表单请求验证类怎么用_Laravel Form Request分离验证逻辑教程
LinuxShell函数封装方法_脚本复用设计思路【教程】
,南京靠谱的征婚网站?
用yum安装MySQLdb模块的步骤方法
Laravel怎么实现支付功能_Laravel集成支付宝微信支付
怎么制作一个起泡网,水泡粪全漏粪育肥舍冬季氨气超过25ppm,可以有哪些措施降低舍内氨气水平?
HTML5建模怎么导出为FBX格式_FBX格式兼容性及导出步骤【指南】
大同网页,大同瑞慈医院官网?
如何在搬瓦工VPS快速搭建网站?
电视网站制作tvbox接口,云海电视怎样自定义添加电视源?
Laravel中间件起什么作用_Laravel Middleware请求生命周期与自定义详解
Laravel如何实现模型的全局作用域?(Global Scope示例)
如何在阿里云虚拟机上搭建网站?步骤解析与避坑指南
Laravel如何处理异常和错误?(Handler示例)
大连企业网站制作公司,大连2025企业社保缴费网上缴费流程?
网页制作模板网站推荐,网页设计海报之类的素材哪里好?
Laravel怎么返回JSON格式数据_Laravel API资源Response响应格式化【技巧】
Laravel如何实现一对一模型关联?(Eloquent示例)
php json中文编码为null的解决办法

