REST API LocalDateTime 사용할 때 문제점 해결해보기

728x90

발생한 문제

생긴 문제는 MyBatis를 사용하여 Json 데이터를 insert하고 user 객체를 반환합니다.

이 때, id는 기본키이며, auto increment이고 det는 datetime, Current_timestamp로 현재 날짜와 시간을 자동으로 생성해줍니다.


User class

//User
@Data
public class User{
	private long id;
    private String email;
    private String password;
    private String name;
    private LocalDateTime det;
}

User Controller

//컨트롤러
 @PostMapping
    public Object postUser(@RequestBody @Validated User user){
        
        userService.save(user);
        
        return user;
    }

컨트롤러에서 user 객체를 그대로 반환하게 됩니다.

 

UserMapper

@Mapper
public interface UserMapper {

    @Insert("INSERT INTO user (email, password, name) VALUES(#{email}, #{password}, #{name})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insert(User user);

}

etc-image-0

email과 password , name 으로 post 전송해 insert를 요청했습니다.

etc-image-1

UserMapper에서는 keyProperty 가 "id" 이기 때문에 데이터를 저장하게 되면 id 값은 반환이 되지만 det는 null 인 것을 확인 할 수 있습니다. 데이터베이스에서 자동생성되고 우리는 사용자가 요청한 데이터를 반환하기 때문에 데이터 베이스에 저장된 det를 얻어 올 수 없었습니다.


첫 번째 해결 시도 방법 

setDet를 통해 현재 시간을 세팅 해주고 save 요청을 보냅니다.

//컨트롤러
 @PostMapping
    public Object postUser(@RequestBody @Validated User user){
        
        user.setDet(LocalDateTime.now());
        userService.save(user);
        
        return user;
    }

etc-image-2

det를 보내주는데 성공했습니다.

etc-image-3

데이터 베이스에는 2021-07-18 01:39:18 로 값이 저장되었지만 우리가 보낸 det는 날짜와 시간 사이 공백에 'T'가 있고, 초도 . 단위로 상세하게 나오는 것을 볼 수 있습니다.

 


두 번째 해결 시도 방법

저번에 강의들으며 공부 하면서 배운 @DateTimeFormat을 사용해보겠습니다.

//User
@Data
public class User{
	private long id;
    private String email;
    private String password;
    private String name;
    
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime det;
}

etc-image-4

여전히 format이 바뀌지 않고 똑같은 것을 확인 할 수 있습니다...


세 번째 해결 시도 방법

문제 해결을 위해 계속 검색을 시도해보다가 문특 JSON 데이터니 JSON데이터를 format하는 것도 있지 않을까? 싶어서 JsonFormat을 검색해보니 @JsonFormat을 통해 json 데이터를 format하는 것을 발견했습니다.

//User
@Data
public class User{
	private long id;
    private String email;
    private String password;
    private String name;
    
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime det;
}

etc-image-5

문제가... 해결되었습니다!!!

 

get으로 list를 받아오는 것도 확인해 보겠습니다.

etc-image-6

 

원하는 대로 포맷이 되어 데이터를 반환해주는 것을 확인했습니다.

 

반응형