zoukankan      html  css  js  c++  java
  • mybatis 基础1(动态代理)

    我目前使用的是mybatis 3.3.0版本。

    可使用

    1.xml文本,

    2.dao类,

    3.sqlSession.getMapper(Class<T> type),

    生成sql类,

    原理:动态代理。

    动态代理展示:

    @1:接口:ProxyInterface

    public interface ProxyInterface {

        public void sayHA();

    }
    @2:接口实现类ProxyImp
    public class ProxyImp implements ProxyInterface {
    @Override
    public void sayHA() {
    System.out.println("继承类继承类继承类继承类继承类!");
    }
    }
    @3:代理类:ProxyService
    public class ProxyService implements InvocationHandler{
    Object target;
    Object proxyLei;
    ProxyService(Object target,Class[] interfaces){
    this.target=target;
    this.proxyLei= Proxy.newProxyInstance(target.getClass().getClassLoader(),interfaces,this);
    }
    ProxyService(){}

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    System.out.println("invokeinvokeinvokeinvokeinvokeinvoke");
    return "111";
    }
    }

    @4:测试类:Test
    public class Test {
    public static void main(String []args){
    ProxyInterface proxyImp=new ProxyImp();
        System.out.println(proxyImp.getClass());
            proxyImp.sayHA();
    ProxyService proxy=new ProxyService(proxyImp,proxyImp.getClass().getInterfaces());
    System.out.println(proxy.proxyLei);

    proxyImp=(ProxyInterface)proxy.proxyLei;
        System.out.println(proxyImp.getClass());
            proxyImp.sayHA();
    }
    }
    输出值:

    class com.proxy1.ProxyImp
    继承类继承类继承类继承类继承类!

    invokeinvokeinvokeinvokeinvokeinvoke
    111
    class com.sun.proxy.$Proxy0

    解析:

    第一个System.out.println(proxyImp.getClass());输出的是:class com.proxy1.ProxyImp,这是一个类;

    第二个System.out.println(proxyImp.getClass());输出的是:class com.sun.proxy.$Proxy0,这是一个代理类;

    第一个proxyImp.sayHA();输出的是:继承类继承类继承类继承类继承类!,这是原方法的正确输出;

    第一个proxyImp.sayHA();输出的是:

    invokeinvokeinvokeinvokeinvokeinvoke
    111

    这是代理类ProxyService的invoke方法的正确输出。

    
    
    以上是一个简单的完整的代理类示例。
    小结:

    点1:动态代理的代理类(ProxyService)需要继承类InvocationHandler,根据jdk的英文解释,当调用代理类的方法时,ProxyService的invoke方法将会被调用。而
    ProxyService所代理的类的方法将不会被调用,但可在ProxyService的invoke方法中被调用。使用方法:method.invoke(target,args);
    点2:方法:
    Proxy.newProxyInstance(target.getClass().getClassLoader(),interfaces,this);返回一个动态代理类。
    参数解析:
    1. //得到代理对象..注意这里的第一个参数 要和Dao是同一个类加载器  
    2.   //第二个参数是实现哪个接口,要和被代理实现同样的接口  
    3.   //第三个参数是织入的类,该类实现了InvocationHandle接口  
     
    以上,为mybatis的基础之一:动态代理。



  • 相关阅读:
    Why Choose Jetty?
    Jetty 的工作原理以及与 Tomcat 的比较
    Tomcat设计模式
    Servlet 工作原理解析
    Tomcat 系统架构
    spring boot 打包方式 spring boot 整合mybaits REST services
    wireshark udp 序列号 User Datagram Protocol UDP
    Maven 的聚合(多模块)和 Parent 继承
    缓存策略 半自动化就是mybaitis只支持数据库查出的数据映射到pojo类上,而实体到数据库的映射需要自己编写sql语句实现,相较于hibernate这种完全自动化的框架我更喜欢mybatis
    Mybatis解决sql中like通配符模糊匹配 构造方法覆盖 mybits 增删改
  • 原文地址:https://www.cnblogs.com/zqsky/p/6015967.html
Copyright © 2011-2022 走看看