๋ฐ์ํ
[Mapstruct] LocalDateTime <-> Date
- mapstruct ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ด์ฉํด LocalDateTime์ Date๋ฅผ ๋ฐ๊ฟ๋ ๊ธฐ๋ณธ์ ์ผ๋ก Timezone์ UTC๋ฅผ ์ฌ์ฉํ๊ธฐ ๋๋ฌธ์, ํ์ฌ ์๋ฒ๊ฐ ์กด์ฌํ๋ ๋๋ผ์ ์๊ฐ๊ณผ ๋ค๋ฅด๊ฒ ๋ณํ ๋๋ค. (์ฐ๋ฆฌ๋๋ผ์ ๊ฒฝ์ฐ -9์๊ฐ ๋ ์๊ฐ์ผ๋ก ๋ณด์ฌ์ง)
- ๊ทธ๋์ ํ์ฌ ์์คํ ์ timezone์ ์ด์ฉํด ๋ณํํด์ผ ํ๋๋ฐ ๋ฑํ timezone์ ๋ณ์๋ก ์ฌ์ฉํด ๋ฐ๊ฟ ์ ์๋ ๋ฐฉ๋ฒ์ ์์ด๋ณด์ฌ์, expression์ ์ด์ฉํด ๋ณํํ๋ ๋ฐฉ๋ฒ์ ์ ํํ๋ค.
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import java.time.ZoneId;
import java.util.List;
@Mapper(imports = ZoneId.class)
public interface Mapper {
@Mapping(target = "userBirthDay", expression = "java(user.getUserBirthday().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime())")
UserDto toUserDto(User user);
}
@Getter
@Setter
class User {
private Date userBirthday;
}
@Getter
@Setter
class UserDto {
private LocalDateTime userBirthDay;
}
- ์ฐธ๊ณ : imports๋ฅผ ์ด์ฉํ๋ฉด mapstruct๊ฐ ๋ด๋ถ ๋ก์ง์ ๊ตฌํํ ๋ importํ ํด๋์ค๋ค์ ์ ์ธํ ์ ์๋ค.
expression
- target ๋ณ์๋ฅผ ๋งคํํ ๋ ์ฌ์ฉํ๊ณ ์ถ์ ์๋ฐ ์ฝ๋๋ฅผ ์ง์ ์์ฑํ ์ ์๋ค.
- ๋ฐ์ ์ฝ๋๋, ์์ mapper interface๊ฐ mapstruct์ ์ํด ์๋์ผ๋ก ๊ตฌํ ๋ ์ฝ๋๊ฐ ์์ฑ๋์์ ๋ ๋ด๋ถ ๋ก์ง์ด๋ค.
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.processing.Generated;
import org.springframework.stereotype.Component;
@Generated(
value = "org.mapstruct.ap.MappingProcessor",
comments = "version: 1.5.3.Final, compiler: javac, environment: Java 11.0.7 (Azul Systems, Inc.)"
)
@Component
public class MapperImpl implements Mapper {
@Override
public UserDto toUserDto (User user) {
if ( user == null ) {
return null;
}
// ์๋ต
userDto.setUserBirthday( user.getUserBirthday().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime() );
return userDto;
}
}
์ฐธ๊ณ
๐ Reference
๋ฐ์ํ