mybatis动态代理

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);//执行映射成的方法
  }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • mybatis 1. what is mybatis 2. how to use mybatis 1. 编程...
    天外云卷阅读 2,755评论 0 1
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 33,411评论 18 399
  • [盛开之旅D55]重温历史。盘古开天地、女娲造人、北京人、大禹治水、秦始皇兵统六国、楚汉之争……鸦片战争……好多的...
    小猪芬蒂克阅读 3,203评论 0 1
  • 今天特别冷,晚上赶到教室已经有一位家长在了,赶紧布置起来,孩子们打气球,我们挂灯笼,不一会别的家长也来了,人多力量...
    天宇嘛嘛阅读 1,175评论 0 2
  • “扫楼”找实习,这个方法看似简单直接,看似只需要勇气和体力,但如果你事先不动脑筋想清楚就贸然行动,最终也很可能铩羽...
    朱若霞阅读 4,572评论 0 1

友情链接更多精彩内容