使用動態代理操作的話先實現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);