public class MapperProxyFactory <T> { private final Class<T> mapperInterface;
public MapperProxyFactory(Class<T> mapperInterface) { this.mapperInterface = mapperInterface; }
public T newInstance(Map<String, Object> sqlSession) { MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface); return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[]{mapperInterface}, mapperProxy); } }
最后,我们先创建一个IUserMapper类
1 2 3 4 5 6 7 8
package com.yang.mybatis.test;
public interface IUserMapper { String queryUserName(Integer id);
Integer queryUserAge(Integer id); }
然后创建对应的测试方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
package com.yang.mybatis.test;
import com.yang.mybatis.proxy.MapperProxyFactory;
import java.util.HashMap; import java.util.Map;
public class Main { public static void main(String[] args) { MapperProxyFactory<IUserMapper> userDaoMapperProxyFactory = new MapperProxyFactory<>(IUserMapper.class); Map<String, Object> sqlSession = new HashMap<>(); sqlSession.put("com.yang.mybatis.test.IUserMapper.queryUserName","模拟查询用户名"); sqlSession.put("com.yang.mybatis.test.IUserMapper.queryUserAge",1); IUserMapper iUserMapper = userDaoMapperProxyFactory.newInstance(sqlSession); System.out.println(iUserMapper.queryUserAge(1)); System.out.println(iUserMapper.queryUserName(1)); } }