객체의 필드 값을 다른 객체의 필드 값으로 자동으로 맵핑
DTO -> Entity
변환 과정이 필요하며, DB에서 데이터를 조회하여 form 형태로 보여주는 경우 Entity -> DTO
변환 과정이 필요Entity (Member.java)
@Entity
@Getter @Setter
public class Member {
@Id
private Long id;
private String name;
private String email;
private String password;
private String address;
private Role role;
}
DTO (MemberFormDto.java)
@Getter @Setter
public class MemberFormDto {
private String name;
private String email;
private String password;
private String address;
}
DTO -> Entity
Member createMember(MemberFormDto memberFormDto) {
Member member = new Member();
member.setName(memberFormDto.getName());
member.setEmail(memberFormDto.getEmail());
member.setPassword(memberFormDto.getPassword());
member.setAddress(memberFormDto.getAddress());
member.setRole(Role.USER);
return member;
}
get
set
을 이용하여 직접 필드 값을 채우는 과정을 반복적으로 수행ModelMapper
사용Dependency
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>3.1.0</version>
</dependency>
DTO -> Entity
Member createMember(MemberFormDto memberFormDto) {
ModelMapper modelMapper = new ModelMapper();
Member member = modelMapper.map(memberFormDto, Member.class);
member.setRole(Role.USER);
return member;
}
ModelMapper
객체 생성map
메서드에 변경할 객체와 변경하고 싶은 클래스를 인자로 전달