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);
  • 相关阅读:
    Checked Exception & Unchecked Exception
    Spring事务:调用同一个类中的方法
    SpringMVC接收checkbox传值
    Java String 学习
    写给大忙人的JavaSE 8
    Spring in Action 4th 学习笔记 之 AOP
    Spring in Action 4th 学习笔记
    spring只是一个框架
    lambda小结
    电感的Q值
  • 原文地址:https://www.cnblogs.com/Crush123/p/14872008.html
Copyright © 2011-2022 走看看