헛짓거리를 꽤 오래해서 남겨놓는다.
현상
- @RequestBody를 떼면 Postman에서 에러 발생
- @RequestBody를 붙이면 Swagger, Postman 전체에서 에러 발생
- 에러 발생 이유는 API 호출 시 DTO에 값 매핑이 안되서이며 mybatis에 바인딩 될 때 NULL로 나와 컬럼 속성이 NOT NULL인 컬럼들에 한해 예외 발생
해결 방법
Http 메소드 중 Get 방식은 Query String으로 값을 받는다.
그래서 Controller 단에서 @RequestBody를 쓸 이유가 없다.
근데 그 날 졸린 상태에서 작업했는지 @RequestBody가 붙어있었고 해당 어노테이션을 Post 방식의 날씨 등록 API에 갖다 붙였었는데 그 @RequestBody 어노테이션이 Spring 자체에서 제공하는 게 아니라 Spring Swagger 라이브러리에서 제공하는 걸 갖다붙여서 한시간동안 삽질하고 있었다.
Get 방식에 @RequestBody 떼고 어노테이션 import를 Spring에서 지원해주는 어노테이션으로 변경 후 정상적으로 작동하였다.
package com.project.smartfarmapi.weather;
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.project.smartfarmapi.api.ApiResponse;
import com.project.smartfarmapi.cmmn.ResultVo;
import com.project.smartfarmapi.weather.dto.WeatherGetDto;
import com.project.smartfarmapi.weather.dto.WeatherInsDto;
import com.project.smartfarmapi.weather.vo.WeatherGetVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Tag(name = "날씨 정보 API")
@RequestMapping("/weather")
@RestController
@RequiredArgsConstructor
public class WeatherController {
private final WeatherService service;
@GetMapping
@Operation(summary = "날씨 정보 조회 API")
public ResponseEntity<ApiResponse<List<WeatherGetVo>>> getWeather(WeatherGetDto dto) {
List<WeatherGetVo> vo = service.getWeather(dto);
ApiResponse<List<WeatherGetVo>> apiResponse = ApiResponse.<List<WeatherGetVo>>success(vo);
return ResponseEntity
.ok(apiResponse);
}
@PostMapping
@Operation(summary = "날씨 등록 API")
public ResponseEntity<ApiResponse<ResultVo>> insWeather(@RequestBody WeatherInsDto dto) {
ResultVo vo = service.insWeather(dto);
ApiResponse<ResultVo> apiResponse = ApiResponse.<ResultVo>success(vo);
return ResponseEntity
.ok(apiResponse);
}
}