public class TestMyBais {
public static void main(String[] args) {
MySqlSession mySqlSession = new MySqlSession();
TestMapper mapper = mySqlSession.getMapper(TestMapper.class);
Test test = mapper.selectById(1);
System.out.println(test);
}
}
import java.lang.reflect.Proxy;
import java.sql.SQLException;
public class MySqlSession {
private Executor executor = new SimpleExecutor();
public <T> T getMapper(Class<T> mapperInterface){
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(),new Class[]{mapperInterface},new MapperProxy(this,mapperInterface));
}
public <T> T selectOne(String sql, String paramter) throws SQLException {
return executor.query(sql,paramter);
}
}
import java.sql.SQLException;
public interface Executor {
<T> T query(String sql, String paramter) throws SQLException;
}
import com.wenxin.it.mybatis2.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class SimpleExecutor implements Executor{
@Override
public <T> T query(String sql, String paramter) throws SQLException {
Connection connecion = com.wenxin.it.mybatis2.SimpleExecutor.getConnecion();
PreparedStatement preparedStatement = connecion.prepareStatement(String.format(sql, paramter));
ResultSet resultSet = preparedStatement.executeQuery();
Test test = new Test();
while (resultSet.next()) {
test.setId(resultSet.getInt(1));
test.setName(resultSet.getString(2));
}
return (T) test;
}
}
import com.wenxin.it.mybatis2.Test;
public interface TestMapper {
Test selectById(Integer id);
}
import java.util.HashMap;
import java.util.Map;
public class TestMapperXml {
public static final String nameSpace = "com.wenxin.it.mybatis3.TestMapper";
public static final Map<String,String> methodMapperSql = new HashMap<>();
static {
methodMapperSql.put("selectById","select * from test where id = %s");
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class MapperProxy<T> implements InvocationHandler {
private MySqlSession sqlSession;
private Class<T> mapperInterfact;
public MapperProxy(MySqlSession sqlSession, Class<T> mapperInterfact) {
this.sqlSession = sqlSession;
this.mapperInterfact = mapperInterfact;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getDeclaringClass().getName().equals(TestMapperXml.nameSpace)) {
String sql = TestMapperXml.methodMapperSql.get(method.getName());
System.out.printf("the sql is "+ sql,args[0]);
System.out.println();
return sqlSession.selectOne(sql, args[0].toString());
}
return null;
}
}