728x90

 

문제 상황

 

문제 코드

    @PostMapping
    public GlobalResponse<MultimediaDto.Response> uploadMultimedia(
            @RequestParam("file") MultipartFile file,
            @ModelAttribute MultimediaDto.Request requestDto
    ){
        MultimediaDto.Response responseDto = multimediaService.uploadMultimedia(file,requestDto);
        return ApiUtils.success(ResponseMessage.MULTIMEDIA_UPLOAD_SUCCESS.getMessage(),responseDto);

    }

 

API 요청에서 @ModelAttribute로 받아오는 DTO(MultimediaDto.Request) 내부의 UUID 타입 필드인 postId가 null 값으로 들어가서, 해당 postId로 PostService.getPostById()를 호출할 때 "The given id must not be null" 오류가 발생했습니다.

 

2024-10-04T16:10:52.582+09:00  INFO 13959 --- [post-service] [io-19095-exec-5] [66ff94fc6e3bcfaaf7f985d2ea17d136-f7f985d2ea17d136] CommonLogging                            : 메서드 실행 시작 - 클래스명: com.tk.gg.post.application.service.MultimediaService, 메서드명: uploadMultimedia
2024-10-04T16:10:52.583+09:00  INFO 13959 --- [post-service] [io-19095-exec-5] [66ff94fc6e3bcfaaf7f985d2ea17d136-f7f985d2ea17d136] CommonLogging                            : 메서드 실행 시작 - 클래스명: com.tk.gg.post.application.service.PostService, 메서드명: getPostById
2024-10-04T16:10:52.583+09:00 ERROR 13959 --- [post-service] [io-19095-exec-5] [66ff94fc6e3bcfaaf7f985d2ea17d136-f7f985d2ea17d136] CommonLogging                            : 예외 발생 - 클래스명: com.tk.gg.post.application.service.PostService, 메서드명: getPostById, 예외 메시지: The given id must not be null
2024-10-04T16:10:52.583+09:00 ERROR 13959 --- [post-service] [io-19095-exec-5] [66ff94fc6e3bcfaaf7f985d2ea17d136-f7f985d2ea17d136] CommonLogging                            : 예외 발생 - 클래스명: com.tk.gg.post.application.service.MultimediaService, 메서드명: uploadMultimedia, 예외 메시지: The given id must not be null

 

문제 원인

 

  • @ModelAttribute는 기본적으로 단순 타입(예: String, int, boolean)을 매핑하는 데 사용됩니다. 그러나 UUID와 같은 복잡한 타입은 기본적으로 자동 변환되지 않습니다.
  • 이로 인해, 쿼리 파라미터에서 넘어오는 postId가 제대로 UUID 타입으로 변환되지 않고, 바인딩에 실패하여 null 값이 전달되었습니다.
  • postId가 null로 처리되면서, PostService.getPostById() 메서드 호출 시 null을 ID로 전달하게 되어, "The given id must not be null" 예외가 발생한 것입니다.

 

 

문제 해결

    @PostMapping
    public GlobalResponse<MultimediaDto.Response> uploadMultimedia(
            @RequestParam("file") MultipartFile file,
            @RequestParam("postId") UUID postId,
            @RequestParam("fileType") FileType fileType
    ){
        MultimediaDto.Response responseDto = multimediaService.uploadMultimedia(file,postId,fileType);
        return ApiUtils.success(ResponseMessage.MULTIMEDIA_UPLOAD_SUCCESS.getMessage(),responseDto);

    }

 

  • @ModelAttribute 대신 @RequestParam을 사용하여 UUID 필드를 직접 받아오도록 수정합니다.
  • @RequestParam은 복잡한 타입에 대해서도 자동 변환을 지원하므로, 쿼리 파라미터에서 넘어온 String 값을 UUID로 자동 변환해줍니다.

 

 

결론 & 배운점

 

  • UUID와 같은 복잡한 타입의 데이터를 @ModelAttribute로 바인딩하려면 별도의 변환 로직이 필요하지만, @RequestParam은 Spring이 내부적으로 자동 변환을 처리하므로 이 문제를 쉽게 해결할 수 있습니다.
  • 해당 코드를 @RequestParam으로 변경하여 문제를 해결하고, UUID 타입 필드도 정상적으로 처리되도록 수정되었습니다.