본문 바로가기
Language/Java

[Java] ObjectMapping을 위한 MapStruct 알아보기 - 2

by 별토끼. 2021. 8. 12.
반응형

Intro

이전 포스팅에서는 MapStruct의 기본 개념과 가장 기본적인 적용에 대해서 알아보았다. 이번 포스팅에서는 실제 구현 시 유연하게 적용할 수 있는 방법들을 알아보도록 하자.

서로 다른 속성 매핑

이전에 사용했던 예제 코드를 활용해보자.

StudentDto

public class StudentDto {
    private String name;
    private String age;
    private String level;
}

StudentEntity

public class StrudentEntity {
    private String seq;
    private String name;
    private String age;
    private String grade;
    private String status = "Attending";
    private OffsetDateTime createdDateTime = OffsetDateTime.now();
}

level을 age로 변환하려면 '@Mapping' annotation을 활용한다.

@Mapper
public interface StudentMapper {
    @Mapping(source = "level", target="grade")
    StudentEntity toStudentEntity(StudentDto studentDto);
}

객체 합치기

객체 두개를 하나의 엔티티에 합쳐야한다면 좀 더 복잡해진다. (실제로 고민을 많이 했던 부분이기도 하다)

위와 같은 학생 도메인으로, 학생들의 성적에 대한 객체를 매핑해야 한다면 어떻게 해야할까? 아래 코드는 StudentDto, TestInfo, 그리고 이 둘을 합쳐 생성해야 하는 StudentEntity가 있다.

StudentDto

public class StudentDto {
    private String name;
    private String age;
    private String level;
}

ScoreEntity

public class TestInfo {
    private String scoreAvg;
    private Map<String, int> scoreParameter;  
}

StudentEntity

    private String seq;
    private String name;
    private String age;
    private String grade;
    private String status = "Attending";
    private TestInfo testEntity;
    private OffsetDateTime createdDateTime = OffsetDateTime.now();

그렇다면 아래와 같이 맵핑할 수 있다. (+ 도큐멘트를 참고해서 추가 설명이 필요할 것 같다)

@Mapper
public interface StudentMapper {
    @Mapping(source = "TestInfo", target = "score")
    StudentEntity toStudentEntity(ScoreEntity socreEntity, StudentDto studentDto);
}

참고
Object Mapping 어디까지 해봤니?
MapStruct 공식 문서

반응형

댓글