zoukankan      html  css  js  c++  java
  • Mapper代理类实现

    package org.simple.proxy;

    import org.apache.ibatis.session.SqlSession;

    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.util.List;

    //Java 动态代理方式一个代理类
    public class MyMapperProxy<T> implements InvocationHandler {
    private Class<T> mapperInterface;
    private SqlSession sqlSession;

    public MyMapperProxy(Class<T> mapperInterface,SqlSession sqlSession)
    {
    this.mapperInterface=mapperInterface;
    this.sqlSession=sqlSession;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    //针对不同的sql类型,需要调用sqlSession不同的方法
    //接口方法中的参数也有很多情况,这里只考虑有没有参数的情况
    List<T> list = sqlSession.selectList(mapperInterface.getCanonicalName() + "." + method.getName());
    //返回值也有很多情况, 这里不做处理直接返回
    return list;
    }
    }







    //测试类
    package org.simple.test;

    import org.apache.ibatis.session.SqlSession;
    import org.junit.Assert;
    import org.junit.Test;
    import org.simple.mapper.SysUserMapper;
    import org.simple.model.SysUser;
    import org.simple.proxy.MyMapperProxy;
    import org.simple.utils.BaseMapper;

    import java.lang.reflect.Proxy;
    import java.util.List;

    public class ProxyTest extends BaseMapper
    {

    @Test
    public void testProxy(){
    //获取sqlSession
    SqlSession sqlSession=getSqlSession();
    try {
    //获取UserMapper接口
    MyMapperProxy userMapperProxy=new MyMapperProxy(SysUserMapper.class,sqlSession);
    SysUserMapper userMapper = (SysUserMapper) Proxy.newProxyInstance(
    Thread.currentThread().getContextClassLoader(),
    new Class[]{SysUserMapper.class},
    userMapperProxy
    );
    //调用selectAll方法
    List<SysUser> sysUsers = userMapper.selectAll();
    Assert.assertNotNull(sysUsers);
    }finally {
            sqlSession.close();

    }
    }

    }
  • 相关阅读:
    一个开源库:720全景显示
    如何查看mac系统是32位还是64位的操作系统
    iOS ASIHTTPRequest 使用指南
    iOS block里的self
    苹果公司给出的检测 advertisingIdentifier 的方法
    App Store idfa被拒检查办法
    iOS苹果开发者客服电话地址
    iOS项目的目录结构和开发流程(Cocoa China)
    CFBundleVersion与CFBundleShortVersionString
    In App Purchase Statuses
  • 原文地址:https://www.cnblogs.com/LQ970811/p/12876861.html
Copyright © 2011-2022 走看看