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);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM