[TIL] 23/8/18 Category 테이블 View 추가 + 뷰 생성법, 사용법, Spring boot entity 작성
문제점 처음 서비스를 기획하며 데이터베이스를 설계했을 때 생각치 못했던 문제점들이 프로젝트가 진행되며 드러나기 시작했다. 카테고리를 관리하는 category 테이블이 있다. 이 테이블은 메뉴
foliageit.tistory.com
위 글에서 얘기했던 것과 같이 현재 카테고리 테이블엔 메뉴를 위한 카테고리와 옵션을 위한 카테고리가 혼재되어 있다.
기존 코드에서는 하드 코딩하여 카테고리 아이디가 8이거나, 10보다 크거나 같을 경우에 에러를 던졌다.
// Categories 8, 10, and 11 are not in use due to menu consolidation.
// Starting from ID 12, they are not used for menu retrieval.
// Exception is thrown if the category ID is 8 or greater than or equal to 10.
if (categoryId >= 10 || categoryId == 8) {
throw new InvalidCategoryIdException("Invalid Category");
}
유연성이 떨어졌던 기존 코드.
하지만 이제는 뷰가 있으니 하드코딩할 필요가 없다~
@Override
public List<Integer> getAllMenuCategoryIds() {
List<Integer> categoryIds = new ArrayList<>();
List<MenuCategoryView> menuCategoryViews = menuCategoryViewRepository.findAll();
for (MenuCategoryView menuCategoryView : menuCategoryViews) {
categoryIds.add(menuCategoryView.getCategoryId());
}
return categoryIds;
}
먼저 메뉴 카테고리 뷰를 가져와서 리스트에 메뉴 카테고리의 아이디만 리스트에 담았다.
@GetMapping("/{categoryId}")
public String getMenusInCategory(@PathVariable int categoryId, Model model){
List<Integer> allMenuCategoryIds = categoryService.getAllMenuCategoryIds();
Category category;
List<MenuDTO> menuDTOList;
if (allMenuCategoryIds.contains(categoryId)) {
category = categoryService.findCategory(categoryId);
menuDTOList = menuService.getMenusInCategory(category);
} else {
category = null;
menuDTOList = Collections.emptyList();
}
model.addAttribute("category", category);
model.addAttribute("menus", menuDTOList);
return "menu-list";
}
먼저 파라미터로 받은 카테고리 아이디가 allMenuCategoryIds 리스트에 들어있는 항목인지 검증한다.
메뉴에 속한 카테고리가 맞다면, 카테고리 객체를 가져오고 해당 카테고리에 속한 메뉴를 전부 가져온다.
아닌 경우에는 category는 null, menuDTOList는 emptyList로 넘겨준다.
이 경우, 프론트에서 NP가 발생하지 않도록 NP 체크가 필수다.
Java ArrayList contains 메서드 👇
/**
* Returns {@code true} if this list contains the specified element.
* More formally, returns {@code true} if and only if this list contains
* at least one element {@code e} such that
* {@code Objects.equals(o, e)}.
*
* @param o element whose presence in this list is to be tested
* @return {@code true} if this list contains the specified element
*/
public boolean contains(Object o) {
return indexOf(o) >= 0;
}