[Spring] DTO <-> Entity 변환
https://www.amitph.com/spring-entity-to-dto/
Convert Entity To DTO In Spring REST API
A tutorial on How to Entity to DTO Conversion and DTO to Entity Conversion in a Spring REST API manually as well as by using Model Mapper.
www.amitph.com
변환하는 방법을 소개하는 좋은 글이 있어서 남긴다.
- 생성자를 사용하는 방법
- 메서드를 사용하는 방법
- ModelMapper를 사용하는 방법
- MapStruct를 사용하는 방법
메서드를 사용하는 방법이 직관적
만약 변경해야할 필드가 많다면 ModelMapper, MapStruct를 사용하는 것이 용이할 것 같다.
MapStruct 사용
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
implementation 'org.mapstruct:mapstruct:1.4.2.Final'
annotationProcessor 'org.mapstruct:mapstruct-processor:1.4.2.Final'
gradle에서 mapstruct가 lombok과 이슈를 일으킨다.
lombok이 mapstruct보다 위에 있으면 해결된다.
@Mapper
public interface UserMapper {
UserMapper mapper = Mappers.getMapper(UserMapper.class);
// dto -> entity
@Mapping(target = "userAge", source = "age")
@Mapping(target = "name" , source = "name", defaultValue = "Park")
UserEntity userDtoToEntity(UserDto userDto);
@Mapping(target = "age", source = "userAge")
UserDto userEntityToDto(UserEntity userEntity);
}
@Mapper
구현체는 mapstruct가 만들어준다.
import할 때 Mybatis의 @Mapper와 구분
@Mapping
필드명 불일치를 해결할 수 있다.
defaultValue도 설정할 수 있다.
@Test
void UserDtoToEntity(){
UserDto userDto = new UserDto(1, "cha", "email", 30);
UserEntity userEntity = UserMapper.mapper.userDtoToEntity(userDto);
System.out.println(userEntity);
}
참고
https://mapstruct.org/documentation/stable/reference/html/
MapStruct 1.5.2.Final Reference Guide
If set to true, MapStruct in which MapStruct logs its major decisions. Note, at the moment of writing in Maven, also showWarnings needs to be added due to a problem in the maven-compiler-plugin configuration.
mapstruct.org
http://modelmapper.org/getting-started/
ModelMapper - Getting Started
Getting Started This section will guide you through the setup and basic usage of ModelMapper. Setting Up If you’re a Maven user just add the modelmapper library as a dependency: org.modelmapper modelmapper 3.0.0 Otherwise you can download the latest Mode
modelmapper.org
https://blog.naver.com/PostView.nhn?isHttpsRedirect=true&blogId=kbh3983&logNo=220988245343
[JAVA] ModelMapper Customizing
주의!! 일부 버전에서 Custom Mapping 이 됬다 안됬다하는 버그가 있음 아오....하루종일을 날렸네........
blog.naver.com