티스토리 뷰

반응형

1.여러개의 Service를 클래스를 만들어도 하나만 @Service를 정할수있다.

2. @Service라고 정했을 경우 테스트 케이스에서 따로 객체를 만들지 않아도 @Service에 속한 @Component가 자동으로 객체를 만들어서 넣어준다.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {

   /**
    * The value may indicate a suggestion for a logical component name,
    * to be turned into a Spring bean in case of an autodetected component.
    * @return the suggested component name, if any (or empty String otherwise)
    */
   @AliasFor(annotation = Component.class)
   String value() default "";

}
@Autowired
FoodService foodService;

@Test
@DisplayName("save test")
void save() {
    Food food = basicFoodData();
    Food newFood = foodService.save(food);
    assertEquals(food.getId(), newFood.getId());
}

 

3.테스트 404 출력을 위해 ResponseStatusException의 HttpStatus.NOT_FOUND를 사용한다.

public FoodResponseDto findById(Long id) {
    return FoodResponseDto.of(foodRepository.findById(id)
            .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND,"해당 id의 음식이 존재하지 않습니다.")));
}

 

4. FK로 다른 테이블을 가지고있을때 update를 어떻게 해야할까?

Menu 엔티티를 수정할 때는, Store와 Food 엔티티를 함께 업데이트하지 않으면 충돌이 발생할 수 있습니다.
Menu 엔티티와 연관된 Store와 Food 엔티티를 모두 업데이트해야 합니다.
 @Transactional
    public void update(long id, Menu menu) {
        Menu updatedMenu = menuRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("해당 메뉴가 존재하지 않습니다."));
        updatedMenu.changeFood(menu.getFood());
        updatedMenu.changeStore(menu.getStore());
        menuRepository.save(updatedMenu);
    }
반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함