package mybatis.ext; import org.springframework.stereotype.Indexed; import java.lang.annotation.*; @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented @Indexed //定义注解方法 public @interface myInsert { String value(); } package mybatis; import mybatis.ext.myInsert; import org.springframework.stereotype.Component; @Component public interface UserMapper { @myInsert("insert into mysqltest(name,age) values('test',20)") int addUser(); } package mybatis; import mybatis.ext.myInsert; import utils.JdbcUtils; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.sql.Connection; import java.sql.PreparedStatement; //mybatis代理 public class mybatisInvocationHandler implements InvocationHandler { private Class myClass; public mybatisInvocationHandler(Class myClass){ this.myClass=myClass; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { myInsert insert=method.getDeclaredAnnotation(myInsert.class); String insertSql=insert.value(); Connection connection= JdbcUtils.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(insertSql); preparedStatement.execute(); return "ok"; } public <T> T getProxy(){ return (T) Proxy.newProxyInstance(myClass.getClassLoader(), new Class[]{myClass},this); } } package mybatis; public class mybatisProxy { public static UserMapper getMapper(Class mapperClass) { return new mybatisInvocationHandler(mapperClass).getProxy(); } public static void main(String[] args) { UserMapper userMapper = mybatisProxy.getMapper(UserMapper.class); userMapper.addUser(); } } |
|