java中根据反射获取mapper写通用接口
使用动态代理操作的话先实现InvocationHandler接口
/** * 用于基础资料删除系列的通用接口代理 * @author Crush */ public class BasicCodeDeleteHandler implements InvocationHandler { private Object target; public BasicCodeDeleteHandler(Object target) { this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return method.invoke(target,args); } }
通用接口 :
@Autowired private SqlSession sqlSession; /** * 删除基础代码表 */ @Override public Result deleteBasicCode(String tableName, Long id) throws NoSuchMethodException, ClassNotFoundException, InvocationTargetException, IllegalAccessException { // 获取Mapper地址 Class interfaceImpl = Class.forName("com.system.operation.manager.mapper.".concat(tableName)); Object instance = Proxy.newProxyInstance( interfaceImpl.getClassLoader(), new Class[]{interfaceImpl}, new BasicCodeDeleteHandler(sqlSession.getMapper(interfaceImpl)) ); // 各自的接口中需要定义好对应的方法才能调用 Method method = instance.getClass().getMethod("deleteById", Long.class); method.invoke(instance,id); return Result.ok(); }
对应的mapper层:
/** * 根据id删除记录 * @param id */ @Delete("delete from XXX where id =#{id}") void deleteById(Long id);