【Mapper代理类实现】恢弘志士之气,不宜妄自菲薄。这篇文章主要讲述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();
}
}
}
推荐阅读
- hashmapput和get值的时候是怎么确定key在数组中的位子的
- "FedStart Failed" message appears in db2diag.log periodically
- xcode 嵌入flutter_module后编译报错 This app could not be installed at this time.
- H5活动全屏滚动页面在安卓智能电视TV调试
- SwiftUI - 一起来仿写微信APP之一首页列表视图
- ESA2GJK1DH1K基础篇: APP使用SmartConfig绑定Wi-Fi 设备并通过MQTT控制设备(V1.0)(AT+TCP非透传指令)
- 踩坑之uni打包APP后全局注册组件 的样式未生效
- NETAPP 基本操作
- Power Apps课件写作历程