본문 바로가기
Language/Java

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

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

Intro

Spring Framework에서 개발할 때, 비즈니스 로직, 객체와 객체 간의 Mapping 등을 할 때 get, set을 일일이 넣어주는 것은 굉장히 피곤한 일이다. 생산성을 떨어뜨리고, 실수하기 쉽다. 코드도 지저분하다. 이를 대신 해주는 것이 Object Mapping 라이브러리이다.

Object Mapping에는 여러 종류가 있는데, mapstruct, modelMapper, jmapper, orika 등이 있다고 한다. 그 중 전 세계에서 가장 많이 사용하고 있는 MapStruct를 공부해보려 한다.

MapStruct 란

MapStruct는 자바에서 객체 간 매핑에 대한 코드를 자동으로 생성해주는 매핑 라이브러리이다. Annotation을 사용하여 컴파일 시 매핑 코드를 생성한다.

  1. 컴파일 시 오류 확인이 가능하다.
  2. 리플렉션을 사용하지 않아 매핑 속도가 빠르다.
  3. 디버깅이 쉽다.
  4. 생성된 매핑 코드를 눈으로 확인할 수 있다.

예제

학생 Dto

API를 호출하면 StudentDto 객체로 받는다.

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

학생 Entity

StudentDto 객체를 DB에 넣기 위해 학생Entity(DB엔티티) 객체로 옮겨야 한다.

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

StudentDto에서 StudentEntity로 어떻게 옮길까?

아까 말한 MapStruct로 쉽게 옮길 수 있다. (ObjectMapping할 수 있다)

  1. @Mapper 와 인터페이스를 정의한다.
  2. 메서드 파라미터에는 Source 객체(=StudentDto)를 정의한다.
  3. 리턴 타입엔 Target 객체(StudentEntity)를 정의한다.
@Mapper
public interface StudentMapper {
    StudentEntity toStudentEntity(StudentDto studentDto);
}

그럼 컴파일 시에 MapStruct가 아래와 같은 코드를 생성한다.

@Generated(
    value = "org.mapstruct.ap.MappingProcessor", // MapStruct의 Annotation Processor
    date = "2021-08-11T01:39:59+0900",
    comments = "version: 1.3.0.Final, compiler: javac, environment: Java 1.8.0_202 (AdoptOpenJdk)"
)
@Component
public class StudentMapperImpl implements StudentMapper {

    @Override
    public StudentEntity toStudentEntity(StudentDto studentDto) {
        if ( studentDto == null ) {
            return null;
        }

        StudentEntity studentEntity = new StudentEntity();

        studentEntity.setName( studentDto.getName() );
        studentEntity.setAge( studentDto.getAge() );

        return studentEntity;
    }
}

다음 포스팅에서는 여러 상황을 고려한 ObjectMapping에 대해 공부해보겠다!

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

반응형

댓글