![[Tistory] 카테고리 생성](https://image.inblog.dev?url=https%3A%2F%2Finblog.ai%2Fapi%2Fog%3Ftitle%3D%255BTistory%255D%2520%25EC%25B9%25B4%25ED%2585%258C%25EA%25B3%25A0%25EB%25A6%25AC%2520%25EC%2583%259D%25EC%2584%25B1%2520%26logoUrl%3Dhttps%253A%252F%252Finblog.ai%252Finblog_logo.png%26blogTitle%3DCoding_study&w=2048&q=75)
1. 카테고리 생성 (사용자가 하는 것)
PK, 카테고리 이름, 유저ID (같은 유저가 동일한 카테고리가 있는 것은 안됨)
2. CategoryController
@PostMapping("/s/category/save") public String save(String categoryName) { System.out.println("categoryName = " + categoryName); User user = (User) session.getAttribute("sessionUser"); categoryService.save(categoryName, user.getId()); return "redirect:/s/category/write-form"; }
3. CategoryService
@Transactional public void save(String categoryName, Integer sessionUserId) { User sessionUser = userJPARepo.findById(sessionUserId) .orElseThrow(() -> new RuntimeException("회원 정보가 존재하지 않습니다.")); Optional<Category> categoryOP = categoryJPARepo.findByCategoryNameAndUserId(categoryName, sessionUserId); if (categoryOP.isPresent()) { throw new RuntimeException("이미 존재하는 카테고리입니다.");} categoryJPARepo.save(Category.builder() .categoryName(categoryName) .user(sessionUser) .build()); }
4. CategoryJPARepository
@Query("select c from Category c where c.categoryName = :categoryName and c.user.id = :sessionUserId") Optional<Category> findByCategoryNameAndUserId (String categoryName, Integer sessionUserId);
5. 화면


[ 동일한 값을 넣었을 때 ]

Share article