码迷,mamicode.com
首页 > 移动开发 > 详细

Mapper代理类实现

时间:2020-05-12 16:34:23      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:imp   nic   extend   ace   class   java   his   contex   sim   

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

}
}

}

Mapper代理类实现

标签:imp   nic   extend   ace   class   java   his   contex   sim   

原文地址:https://www.cnblogs.com/LQ970811/p/12876861.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!