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

}
}

}
posted @ 2020-05-12 16:08  葵儿啊  阅读(224)  评论(0编辑  收藏  举报
/*粒子线条,鼠标移动会以鼠标为中心吸附的特效*/