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);
  • 相关阅读:
    Vue 页面权限控制和登陆验证
    Vue 动态添加路由及生成菜单
    开发一个简单的 Vue 弹窗组件
    VS使用和错误收集
    ARP欺骗的实现
    虚拟机安装64位系统(Windows Server 2008R2 Datacenter版本)
    Kali安装问题
    HTML5学习之四:多媒体播放
    HTML5学习之三:文件与拖放
    HTML5学习之二:HTML5中的表单2
  • 原文地址:https://www.cnblogs.com/Crush123/p/14872008.html
Copyright © 2011-2022 走看看