mybatis源码阅读(四):mapper(dao)实例化

转载自   mybatis源码阅读(四):mapper(dao)实例化

在开始分析之前,先来了解一下这个模块中的核心组件之间的关系,如图:

1.MapperRegistry&MapperProxyFactory

MapperRegistry是Mapper接口及其对应的代理对象工程的注册中心,Configuration是Mybatis全局性的配置对象,在初始化的过程中,所有配置信息会被解析成相应的对象并记录到Configuration对象中,这在之前也详细介绍了。Configuration.mapperRegistry字段记录当前使用的MapperRegistry对象,

public class MapperRegistry {// 全局唯一的配置对象,其中包含了所有的配置信息private final Configuration config;// 记录Mapper接口与对应MapperProxyFactory之间的关系private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();
}private void bindMapperForNamespace() {String namespace = builderAssistant.getCurrentNamespace();if (namespace != null) {Class<?> boundType = null;try {boundType = Resources.classForName(namespace);} catch (ClassNotFoundException e) {//ignore, bound type is not required}if (boundType != null) {if (!configuration.hasMapper(boundType)) {// Spring may not know the real resource name so we set a flag// to prevent loading again this resource from the mapper interface// look at MapperAnnotationBuilder#loadXmlResourceconfiguration.addLoadedResource("namespace:" + namespace);configuration.addMapper(boundType);}}}
}
public <T> void addMapper(Class<T> type) {mapperRegistry.addMapper(type);
}
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));// 注解处理MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);parser.parse();loadCompleted = true;} finally {if (!loadCompleted) {knownMappers.remove(type);}}}
}

在需要执行SQL语句时,会先获取mapper借口的代理对象,例如:

@Test
public void findUserById() {SqlSession sqlSession = getSessionFactory().openSession();UserDao userMapper = sqlSession.getMapper(UserDao.class);User user = userMapper.findUserById(1);Assert.assertNotNull("没找到数据", user);
}

DefaultSqlSession类中方法如下,实际上是通过JDK动态代理生成的代理对象

public <T> T getMapper(Class<T> type) {return this.configuration.getMapper(type, this);
}

Configuration类方法如下:

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {return mapperRegistry.getMapper(type, sqlSession);
}

MapperRegistry类中方法如下:

@SuppressWarnings("unchecked")
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {//查找指定type对象的MapperProxyFactory对象final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);if (mapperProxyFactory == null) {//如果为空抛出异常throw new BindingException("Type " + type + " is not known to the MapperRegistry.");}try {// 创建实现了type接口的代理对象return mapperProxyFactory.newInstance(sqlSession);} catch (Exception e) {throw new BindingException("Error getting mapper instance. Cause: " + e, e);}
}

MapperProxyFactory主要负责创建代理对象

@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);
}

2.MapperProxy

MapperProxy实现了InvocationHandler接口,对动态代理的可以先去了解这篇文章https://my.oschina.net/u/3737136/blog/1786175

public class MapperProxy<T> implements InvocationHandler, Serializable {private static final long serialVersionUID = -6424540398559729838L;// 记录关联的SQLSession对象private final SqlSession sqlSession;// mapper接口对应的class对象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;}@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {try {// 如果目标方法是Object类继承来的,直接调用目标方法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);}// 从缓存中获取MapperMethod 对象,如果没有就创建新的并添加final MapperMethod mapperMethod = cachedMapperMethod(method);// 执行sql 语句return mapperMethod.execute(sqlSession, args);}}

3.MapperMethod

MapperMethod中封装了Mapper接口中对应方法的信息,以及对应SQL语句的信息,

public class MapperMethod {// 记录SQL语句的名称和类型private final SqlCommand command;// mapper接口中对应方法的相关信息private final MethodSignature method;public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {this.command = new SqlCommand(config, mapperInterface, method);this.method = new MethodSignature(config, mapperInterface, method);}public Object execute(SqlSession sqlSession, Object[] args) {Object result;switch (command.getType()) {case INSERT: {Object param = method.convertArgsToSqlCommandParam(args);result = rowCountResult(sqlSession.insert(command.getName(), param));break;}case UPDATE: {Object param = method.convertArgsToSqlCommandParam(args);result = rowCountResult(sqlSession.update(command.getName(), param));break;}case DELETE: {Object param = method.convertArgsToSqlCommandParam(args);result = rowCountResult(sqlSession.delete(command.getName(), param));break;}case SELECT:if (method.returnsVoid() && method.hasResultHandler()) {// 处理返回值为void ,ResultSet 通过ResultHand处理的方法executeWithResultHandler(sqlSession, args);result = null;} else if (method.returnsMany()) {// 处理返回值为集合或者数组的方法result = executeForMany(sqlSession, args);} else if (method.returnsMap()) {// 处理返回值为map的方法result = executeForMap(sqlSession, args);} else if (method.returnsCursor()) {// 处理返回值为cursor的方法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;}
}

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/322749.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

ajax的封装使用

面试的时候有人问到我ajax的使用&#xff0c;当时回答的不算好&#xff0c;这里想重新总结下&#xff1a; 1、如何将配置等信息传到ajax函数里面去 这个采用的是在参数里加一个对象&#xff0c;对象里面放入字段&#xff0c;然后在ajax里设置一个option&#xff0c;通过option…

P3385-[模板]负环【SPFA】

正题 题目大意 求点1可不可以走到负环。 解题思路 用cnticnt_icnti​表示到iii的最短路经过了多少个点&#xff0c;然后求若cnti≥ncnt_i\geq ncnti​≥n且这条路是负数那么就有负环。 codecodecode #include<cstdio> #include<queue> #include<cstring> …

自定义路由匹配和生成

前言 前两篇文章主要总结了CMS系统两个技术点在ASP.NET Core中的应用&#xff1a; 《ASP.NET Core 中的SEO优化&#xff08;1&#xff09;&#xff1a;中间件实现服务端静态化缓存》 《ASP.NET Core 中的SEO优化&#xff08;2&#xff09;&#xff1a;中间件中渲染Razor视图》…

mybatis多个参数(不使用@param注解情况下),sql参数占位符正确写法

转载自 mybatis多个参数(不使用param注解情况下)&#xff0c;sql参数占位符正确写法 useActualParamName配置 useActualParamName允许使用方法签名中的名称作为语句参数名称。 为了使用该特性&#xff0c;你的工程必须采用Java 8编译&#xff0c;并且加上-parameters选项。&…

如何封装并发布一个属于自己的ui组件库

以前就一直有个想法自己能不能封装一个类似于elementui一样的组件库&#xff0c;然后发布到npm上去&#xff0c;毕竟前端说白了&#xff0c;将组件v上去&#xff0c;然后进行数据交互。借助这次端午&#xff0c;终于有机会&#xff0c;尝试自己去封装发布组件库了 我这里了只做…

P1768-天路【负环,SPFA,01分数规划,二分答案】

正题 题目链接:https://www.luogu.org/problemnew/show/P1768 题目大意 求一条回路使得路上∑vi∑pi\frac{\sum v_i}{\sum p_i}∑pi​∑vi​​最大。 解题思路 考虑01分数规划 ∑vi∑pians\frac{\sum v_i}{\sum p_i}ans∑pi​∑vi​​ans ∑vians∗∑pi\sum v_ians*\sum p_i…

听云支持.NET Core的应用性能监控

随着微软于2017年8月正式发布.NET Core 2.0&#xff0c; .NET Core 社区开始活跃&#xff0c;众多.NET开发者开始向跨平台转变。 听云于2017年11月推出了.NET Core应用监控工具&#xff0c;和听云其他语言的监控工具一样&#xff0c;.NET Core应用监控工具具有以下特征&#xf…

mybatis源码阅读(五) ---执行器Executor

转载自 mybatis源码阅读(五) ---执行器Executor 1. Executor接口设计与类结构图 public interface Executor {ResultHandler NO_RESULT_HANDLER null;// 执行update&#xff0c;delete&#xff0c;insert三种类型的sql语句int update(MappedStatement ms, Object parameter…

.sync的一个用法

面试时&#xff0c;有人问了我修饰符是什么&#xff0c;就是一个点后面加一个单词&#xff0c;我当时还以为是什么文件夹后缀呢。很是尴尬 这里主要学习下.sync的一个用法 假设下场景&#xff1a; 这里有一个父组件&#xff0c;父组件中有个money&#xff0c;需要传到子组件中…

nssl1296-猫咪的进化【dp】

正题 题目大意 nnn次&#xff0c;每次有3种选择&#xff1a; 休息获得viv_ivi​点价值获得vi2v_i^2vi2​点价值且下一回合要休息 解题思路 定义fi,0/1/2f_{i,0/1/2}fi,0/1/2​表示第iii次为休息/叫一声/叫两声时的最大价值。 fi,0f_{i,0}fi,0​可以由前面任何状态转移过来。 …

[52ABP实战系列] .NET CORE实战入门第三章更新了

早安 各位道友好&#xff0c;.NET CORE入门视频的第三章也算录制完毕了。欢迎大家上传课网进行学习。 更新速度 大家也知道最近的社会新闻比较多。频繁发生404、关键字打不出来&#xff0c;我个人也在关注这些事件。导致精力分散&#xff0c;没有做到稳定更新&#xff0c;现在呢…

如何安装nuxt

因为vue是单页面应用&#xff0c;所以不被Seo&#xff0c;如百度和Google抓取到&#xff0c;在Vue中如果想要爬虫爬到就必须使用nuxt 那么如何安装使用呢&#xff1f; yarn create nuxt-app <project-name> cd <project-name> yarn build yarn start必须先build&a…

mybatis源码阅读(六) ---StatementHandler了解一下

转载自 mybatis源码阅读(六) ---StatementHandler了解一下 StatementHandler类结构图与接口设计 BaseStatementHandler&#xff1a;一个抽象类&#xff0c;只是实现了一些不涉及具体操作的方法 RoutingStatementHandler&#xff1a;类似路由器&#xff0c;根据配置文件来路由…

nssl1298-网站计划【线段树】

正题 题目大意 若干个区间操作l,rl,rl,r 让答案增加(lr)∗max{ai}(i∈[l..r])(lr)*max\{a_i\}(i\in[l..r])(lr)∗max{ai​}(i∈[l..r]) 并把最大的数变为0 解题思路 线段树&#xff0c;上传最大值时多上传一个位置&#xff0c;然后单点修改。 codecodecode #include<cstd…

输入框限定保留三位小数点

这里用到正则表达式&#xff0c;没输入一个数字会对输入框进行一次事件的触发&#xff0c;检查是否超过三位小数点&#xff0c;超过则进行删除。 你可以3改成2&#xff0c;这样就是保留两位小数点了 <el-input placeholder"请输入商品重量" v-model"baseInfo…

基于OIDC(OpenID Connect)的SSO(纯JS客户端)

在上一篇基于OIDC的SSO的中涉及到了4个Web站点&#xff1a; oidc-server.dev&#xff1a;利用oidc实现的统一认证和授权中心&#xff0c;SSO站点。 oidc-client-hybrid.dev&#xff1a;oidc的一个客户端&#xff0c;采用hybrid模式。 oidc-client-implicit.dev&#xff1a;od…

mybatis源码阅读(七) ---ResultSetHandler了解一下

转载自 mybatis源码阅读(七) ---ResultSetHandler了解一下 1、MetaObject MetaObject用于反射创建对象、反射从对象中获取属性值、反射给对象设置属性值&#xff0c;参数设置和结果封装&#xff0c;用的都是这个MetaObject提供的功能。 public static MetaObject forObject…

nssl1299-选做作业【最大流,最小割,最大子权闭合图】

正题 题目大意 有nnn个任务&#xff0c;完成需要先决条件&#xff0c;然后有完成价值。选择一些任务完成&#xff0c;求最大价值。 解题思路 首先&#xff0c;如果有环&#xff0c;那么这些环是不可能完成的。所以先用拓扑排序找环。 然后考虑最大子权闭合图&#xff0c;对于…

IIS中的 Asp.Net Core 和 dotnet watch

在基于传统的.NET Framework的Asp.Net Mvc的时候&#xff0c;本地开发环境中可以在IIS中建立一个站点&#xff0c;可以直接把站点的目录指向asp.net mvc的项目的根目录。然后build一下就可以在浏览器里面刷新到最新的修改了&#xff0c;也可以附加到w3wp的进程进行调试。但是在…

mybatis源码阅读(八) ---Interceptor了解一下

转载自 mybatis源码阅读(八) ---Interceptor了解一下 1 Intercetor MyBatis 允许你在已映射语句执行过程中的某一点进行拦截调用。默认情况下&#xff0c;MyBatis允许使用插件来拦截的方法调用包括&#xff1a; Executor (update, query, flushStatements, commit, rollba…