Hefeng · 3: the backend receives the frontend parameters, and the return value is generic review;

1 Breeze One: The List collection of the Controller layer in MyBatis receives data, whether to add generics

1.1 Reintroduction of the problem

Introduction: We discussed the issues we discussed in the previous article , Breeze OneMyBatis中Controller层List集合接收数据,泛型添加与否? , and we have concluded after discussion:不能,理由:因为实体类只能生成唯一的对象。

Experimented at the same time, when the generic type is not added, an error will occur
insert image description here

1.2 Reanalysis of the problem

1.2.1 Interface document of list interface

Generally, adding, deleting, and modifying do not require a return value, but checking requires a return value.

Note: the data return value in the interface is required
insert image description here

1.2.2 The backend uniformly returns the result class

private Integer code; //编码:1成功,0和其它数字为失败
    private String msg; //错误信息
    private T data; //数据

    public static <T> Result<T> success() {
    
    
        Result<T> result = new Result<T>();
        result.code = 1;
        return result;
    }

    public static <T> Result<T> success(T object) {
    
    
        Result<T> result = new Result<T>();
        result.data = object;
        result.code = 1;
        return result;
    }

    public static <T> Result<T> error(String msg) {
    
    
        Result result = new Result();
        result.msg = msg;
        result.code = 0;
        return result;
    }

Note: The marked code, in the unified result return class,success(T object)方法,当data必须返回时,此时需要加上泛型。
insert image description here

1.2.3 Code in the controller

Comparing with the results we got in 1.2.2, list接口中,data必须返回,而统一结果返回类中,定义我们在成功返回data时,必须使用泛型,therefore, based on the fact that we can get an error without adding generics, we get this proof again.

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    public Result<List<Dish>> list(Long categoryId) {
    
    
        log.info("分类id:{}", categoryId);
        List<Dish> dish=  dishService.list(categoryId);
        return Result.success(dish);
    }
}

1.3 Conclusion

list接口中,data必须返回,而统一结果返回类中,定义我们在成功返回data时,必须使用泛型,Therefore, on the basis of our conclusion that an error will be reported without adding generics, we get this evidence.

1.4 Extended conclusion

So, when we define a unified result return class, what points can we get?

  • ① First of all, when defining the unified result return class, if there is data to return and it is successful, we must consider adding generics to receive with a reasonable threshold to reduce program memory usage.
  • ②Secondly, when only the response status is returned (success || failure), we consider not adding generics.
  • ③ Finally, when returning the wrong response result, that is, information, we consider not adding generics.

Guess you like

Origin blog.csdn.net/stange1/article/details/129503857