简单创建代理工厂
一般对于JDBC来说,无非就是连接数据库、查询数据库、封装实体、返回实体,如果要设计一个ORM框架的话也就是要考虑怎么把用户自定义的数据库操作接口、XML中的SQL语句、数据库三者给联系起来,其实最适合的操作就是代理,使用代理的方式来进行处理,因为代理可以封装一个复杂的流程为借口对象的实现类。
这张图描述了一个使用代理模式的流程,主要涉及IUserDao接口及其代理对象的创建和调用。以下是详细解释:
这个流程图展示了如何通过代理工厂和代理模式,动态创建 IUserDao 接口的代理对象,并通过代理对象来处理接口方法的调用,从而实现接口的具体操作。
首先是IUserDao
package com.hayaizo.test.dao;
public interface IUserDao {
String queryUserName(String uid);
String queryUserAge(String uid);
}
映射器代理类
package com.hayaizo.binding;
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;
public class MapperProxy<T> implements InvocationHandler, Serializable {
private static final long serialVersionUID = -23413872L;
private Map<String, String> sqlSession;
private final Class<T> mapperInterface;
public MapperProxy(Map<String, String> sqlSession, Class<T> mapperInterface) {
this.mapperInterface = mapperInterface;
this.sqlSession = sqlSession;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (Object.class.equals(method.getDeclaringClass())) {
return method.invoke(this, args);
} else {
return "你被代理了!" + sqlSession.get(mapperInterface.getName() + "." + method.getName());
}
}
}
映射器工厂
package com.hayaizo.binding;
import java.lang.reflect.Proxy;
import java.util.Map;
public class MapperProxyFactory<T> {
private final Class<T> mapperInterface;
public MapperProxyFactory(Class<T> mapperInterface) {
this.mapperInterface = mapperInterface;
}
public T newInstance(Map<String,String> sqlSession) {
MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession,mapperInterface);
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[]{mapperInterface}, mapperProxy);
}
}
测试方法
package com.hayaizo.test.dao;
import com.hayaizo.binding.MapperProxyFactory;
import org.junit.Test;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
public class ApiTest {
@Test
public void test_proxy_class(){
IUserDao userDao = (IUserDao) Proxy.newProxyInstance(
Thread.currentThread().getContextClassLoader(),
new Class[]{IUserDao.class},
(proxy, method, args) -> {
if ("queryUserName".equals(method.getName())) {
return "你被代理了"+" args= "+args[0];
} else if ("queryUserAge".equals(method.getName())) {
return "18";
}
return method.invoke(this,args);
}
);
String res = userDao.queryUserName("1");
String res1 = userDao.queryUserAge("1");
System.out.println(res);
System.out.println(res1);
}
@Test
public void test_MapperProxyFactory(){
MapperProxyFactory<IUserDao> mapperProxyFactory = new MapperProxyFactory<>(IUserDao.class);
Map<String,String> sqlSession = new HashMap<>();
sqlSession.put("com.hayaizo.test.dao.IUserDao.queryUserName","模拟执行Mapper.xml中的SQL语句,操作:查询用户名称");
IUserDao userDao = mapperProxyFactory.newInstance(sqlSession);
String string = userDao.queryUserName("1");
System.out.println(string);
}
}
运行结果: