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();

    }
    }

    }
  • 相关阅读:
    依赖注入(DI)和Ninject
    Dapper.NET——轻量ORM
    优化SQL查询:如何写出高性能SQL语句
    Razor语法
    sublime Text 3 官方版 3114 注册码
    数据库索引,存储过程,视图,事务
    Action向视图传值的6种方式
    C#知识点提要
    算法总结
    c++ 构造函数,拷贝构造函数,析构函数与赋值操作符
  • 原文地址:https://www.cnblogs.com/LQ970811/p/12876861.html
Copyright © 2011-2022 走看看