iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > JAVA >MyBatis源码剖析之Mapper代理方式细节
  • 660
分享到

MyBatis源码剖析之Mapper代理方式细节

mybatisjava开发语言原力计划 2023-08-16 16:08:36 660人浏览 八月长安
摘要

mybatis是一个流行的Java持久层框架,它提供了多种方式来执行数据库操作,其中之一就是通过Mapper代理方式。通过Mapper代理方式,开发者可以编写接口,然后MyBatis会动态地生成接口的实现类,从而避免了繁琐的sql映射配置。

mybatis是一个流行的Java持久层框架,它提供了多种方式来执行数据库操作,其中之一就是通过Mapper代理方式。通过Mapper代理方式,开发者可以编写接口,然后MyBatis会动态地生成接口的实现类,从而避免了繁琐的sql映射配置。

具体代码如下:
*在这里插入图片描述*

思考⼀个问题,通常的Mapper接⼝我们都没有实现的⽅法却可以使⽤,是为什么呢?

答案很简单:动态代理

public class Configuration {      protected final MapperReGIStry mapperRegistry = new MapperRegistry(this);}public class MapperRegistry {  private final Map, MapperProxyFactory> knownMappers = new HashMap, MapperProxyFactory>();}

开始之前介绍⼀下MyBatis初始化时对接⼝的处理:MapperRegistryConfiguration中的⼀个属性,它内部维护⼀个HashMap⽤于存放mapper接⼝的⼯⼚类,每个接⼝对应⼀个⼯⼚类。mappers中可以配置接⼝的包路径,或者某个具体的接⼝类。
在这里插入图片描述

当解析mappers标签时,它会判断解析到的是mapper配置⽂件时,会再将对应配置⽂件中的增删改查标签 封装成MappedStatement对象,存⼊mappedStatements中。当判断解析到接⼝时,会建此接⼝对应的MapperProxyFactory对象,存⼊HashMap中,key =接⼝的字节码对象,value =此接⼝对应MapperProxyFactory对象。

源码剖析-getmapper()

进⼊ sqlSession.getMapper(UserMapper.class )中

public interface SqlSession extends Closeable {      //调用configuration中的getMapper       T getMapper(Class type);}public class DefaultSqlSession implements SqlSession {  @Override  public  T getMapper(Class type) {    //调用configuration 中的getMapper    return configuration.getMapper(type, this);  }}public class Configuration {  public  T getMapper(Class type, SqlSession sqlSession) {    //调用MapperRegistry 中的getMapper    return mapperRegistry.getMapper(type, sqlSession);  }}public class MapperRegistry {  @SuppressWarnings("unchecked")  public  T getMapper(Class type, SqlSession sqlSession) {    //从 MapperRegistry 中的 HashMap 中拿 MapperProxyFactory    final MapperProxyFactory mapperProxyFactory = (MapperProxyFactory) knownMappers.get(type);    if (mapperProxyFactory == null) {      throw new BindingException("Type " + type + " is not known to the MapperRegistry.");    }    try {      //调用MapperProxyFactory的newInstance通过动态代理⼯⼚⽣成实例      return mapperProxyFactory.newInstance(sqlSession);    } catch (Exception e) {      throw new BindingException("Error getting mapper instance. Cause: " + e, e);    }  }}public class MapperProxyFactory {  public T newInstance(SqlSession sqlSession) {    //创建了 jdk动态代理的Handler类    final MapperProxy mapperProxy = new MapperProxy(sqlSession, mapperInterface, methodCache);    //调⽤了重载⽅法    return newInstance(mapperProxy);  }     @SuppressWarnings("unchecked")  protected T newInstance(MapperProxy mapperProxy) {    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);  }}//MapperProxy 类,实现了 InvocationHandler 接⼝public class MapperProxy implements InvocationHandler, Serializable {  //省略部分源码  private final SqlSession sqlSession;  private final Class mapperInterface;  private final Map methodCache;      //构造,传⼊了 SqlSession,说明每个session中的代理对象的不同的!    public MapperProxy(SqlSession sqlSession, Class mapperInterface, Map methodCache) {    this.sqlSession = sqlSession;    this.mapperInterface = mapperInterface;    this.methodCache = methodCache;  }     //省略部分源码}

源码剖析-invoke()

在动态代理返回了示例后,我们就可以直接调⽤mapper类中的⽅法了,但代理对象调⽤⽅法,执⾏是在MapperProxy中的invoke⽅法中。

public class MapperProxy implements InvocationHandler, Serializable {   @Override  public 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);    //重点在这:最终调⽤了MapperMethod执⾏的⽅法    return mapperMethod.execute(sqlSession, args);  }}

进⼊execute⽅法:

public class MapperMethod {   public Object execute(SqlSession sqlSession, Object[] args) {    Object result;    //判断mapper中的⽅法类型,最终调⽤的还是SqlSession中的⽅法 switch(command.getType())     switch (command.getType()) {      case INSERT: {        //转换参数        Object param = method.convertArgsToSqlCommandParam(args);        //执⾏INSERT操作        //转换rowCount        result = rowCountResult(sqlSession.insert(command.getName(), param));        break;      }      case UPDATE: {        //转换参数        Object param = method.convertArgsToSqlCommandParam(args);        // 转换 rowCount        result = rowCountResult(sqlSession.update(command.getName(), param));        break;      }      case DELETE: {        //转换参数        Object param = method.convertArgsToSqlCommandParam(args);        // 转换 rowCount        result = rowCountResult(sqlSession.delete(command.getName(), param));        break;      }      case SELECT:        //⽆返回,并且有ResultHandler⽅法参数,则将查询的结果,提交给 ResultHandler 进⾏处理        if (method.returnsVoid() && method.hasResultHandler()) {          executeWithResultHandler(sqlSession, args);          result = null;        //执⾏查询,返回列表        } else if (method.returnsMany()) {          result = executeFORMany(sqlSession, args);        //执⾏查询,返回Map        } else if (method.returnsMap()) {          result = executeForMap(sqlSession, args);        //执⾏查询,返回Cursor        } else if (method.returnsCursor()) {          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());    }    //返回结果为null,并且返回类型为基本类型,则抛出BindingException异常    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;  }}

总的来说,MyBatis的Mapper代理方式通过动态代理机制,将接口方法与SQL语句进行映射,使得开发者能够更加方便地进行数据库操作,同时避免了繁琐的SQL映射配置。这种方式使得代码更加清晰简洁,并且提供了良好的可扩展性和可维护性。

相关文章:
MyBatis插件原理探究和自定义插件实现

MyBatis源码剖析之Configuration、SqlSession、Executor、StatementHandler细节

MyBatis源码剖析之二级缓存细节

MyBatis源码剖析之延迟加载源码细节

本文内容到此结束了,
如有收获欢迎点赞👍收藏💖关注✔️,您的鼓励是我最大的动力。
如有错误❌疑问💬欢迎各位指出。
主页共饮一杯无的博客汇总👨‍💻

保持热爱,奔赴下一场山海。🏃🏃🏃

来源地址:https://blog.csdn.net/qq_35427589/article/details/132139755

--结束END--

本文标题: MyBatis源码剖析之Mapper代理方式细节

本文链接: https://www.lsjlt.com/news/371682.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作