美文网首页
mybatis动态代理

mybatis动态代理

作者: sarafina527 | 来源:发表于2018-08-17 12:03 被阅读0次

1.用户使用

1.提供 xxMapper接口

public interface UserMapper {
    @Select(value = "select * from user where id=#{id}")//(1)注解方式
    public User getUser(Long id);
}

2.在xml里配置(可选配置)(2)

<mapper namespace="org.wangying.dao.UserDao">
    <select id="getUser" resultType="org.wangying.entity.User" parameterType="Long">
        select * from user where id=#{id}
    </select>
</mapper>

2.mybatis实现

在调用sqlSession.getMapper(Class)发生了一些神奇的事情

DefaultSqlSession.getMapper(type)
    Configuration.getMapper(type,sqlSession)
        MapperRegistry.getMapper(type,sqlSession) //存放键值对type(接口)-MapperProxyFactory
            MapperProxyFactory.newInstance(sqlSession)
                mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);//代理对象
                MapperProxyFactory.newInstance(mapperProxy)
                    Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy)//生成了一个代理实例,返回

1.实现了对应的接口
mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
2.使用Proxy生成了一个代理实例
Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy)

动态代理实现

MapperProxy 实现InvocationHandler
在invoke方法中从sqlSession的configuration中获取sql语句,
根据sql语句生成方法(jdbc的prepareStatement)

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      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);
    }
    final MapperMethod mapperMethod = cachedMapperMethod(method);//从sqlSession的configuration中获取sql语句,根据sql语句生成方法(jdbc的prepareStatement)
    return mapperMethod.execute(sqlSession, args);//执行映射成的方法
  }

相关文章

  • mybatis 源码解析之如何实现 mapper 动态代理

    从源码解析 mybatis 是如何实现 mapper 动态代理的。 mybatis 底层是基于 JDK 动态代理来...

  • MyBatis动态代理(二)

    接着上一篇MyBatis动态代理(一),这一篇我们来追踪下MyBatis的动态代理 0. 通过SqlSession...

  • Mybatis动态代理

    Mybatis动态代理 实现 MapperProxy实现InvocationHandler接口,重写...

  • MyBatis-Mapper动态代理

    MyBatis官方教程MyBatis二级缓存设计Mybatis中Mapper动态代理的实现原理制作Mybatis插...

  • 设计模式之动态代理

    动态代理模式,在当前流行框架(如:Spring、Mybatis、Dubbo)中应用非常广泛,掌握动态代理模式是理...

  • MyBatis之Mapper动态代理开发

    title: MyBatis之Mapper动态代理开发tags: MyBatiscategories: MyBat...

  • 动态代理

    动态代理理论及Mybatis实战动态代理在我们平时编程并不常用,但因为Spring AOP以及大量框架均使用动态代...

  • Mybatis插件

    Mybatis插件 Mybatis插件又称拦截器。 Mybatis采用责任链模式,通过动态代理组织多个插件(拦截器...

  • mybatis动态代理

    1.用户使用 1.提供 xxMapper接口 2.在xml里配置(可选配置)(2) 2.mybatis实现 在调用...

  • javassist动态代理与cglib动态代理

    mybatis的懒加载是用到了javassist的动态代理,所以想先简单说一下这个,顺便带上cglib动态代理。 ...

网友评论

      本文标题:mybatis动态代理

      本文链接:https://www.haomeiwen.com/subject/pkmzbftx.html