zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    [nginx&php]相关的Q&A
    [C++] 类中的虚函数
    [Linux] 从外网访问内网硬盘
    官网上下载Python安装包的选择
    计数排序的优化版
    插入排序
    Python一些坑
    Linux 一些冷门实用的命令
    分布式爬虫中的在ubuntu镜像里面安装redis的一些细节(-)
    vscode快捷键
  • 原文地址:https://www.cnblogs.com/Crush123/p/14872008.html
Copyright © 2011-2022 走看看