inblog logo
|
Coding_study
    Spring

    [Tistory] 카테고리 생성

    yuzu sim's avatar
    yuzu sim
    Sep 30, 2024
    [Tistory] 카테고리 생성
    Contents
    1. 카테고리 생성 (사용자가 하는 것) 2. CategoryController3. CategoryService4. CategoryJPARepository 5. 화면

    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. 화면

    notion image
    notion image
     

    [ 동일한 값을 넣었을 때 ]

    notion image
     
    Share article

    Coding_study

    RSS·Powered by Inblog