콘텐츠로 이동

2022 07 23

2022-07-23

MapStruct

  • 참고: https://www.baeldung.com/mapstruct
  • 개요
    • 자동적으로 두개의 자바 빈을 매핑해줌
    • 인터페이스만 정의한다면, 라이브러리가 구체 구현을 컴파일 타임에 뚝딱 내놓을 것
  • MapStruct and Transfer Object Pattern
    • POJO <--> POJO
    • Persistence Backed Entity <--> DTO
    • 수동으로 빈 Mapper를 만드는것이 time-consuming 하니, 자동으로 만들자
  • 기본 예시

    • 인터페이스만 다음과 같이 구현해두면 됨
      public class SimpleSource {
          private String name;
          private String description;
      }
      
      public class SimpleDestination {
          private String name;
          private String description;
      }
      
      @Mapper
      public interface SimpleSourceDestinationMapper {
          SimpleDestination sourceToDestination(SimpleSource source);
          SimpleSource destinationToSource(SimpleDestination destination);
      }
      
    • 빌드를 하게되면 /target/generated-sources/annotations/ 에 다음과 같은 클래스 생성
      public class SimpleSourceDestinationMapperImpl implements SimpleSourceDestinationMapper {
      
          @Override
          public SimpleDestination sourceToDestination(SimpleSource source) {
              if ( source == null ) {
                  return null;
              }
              SimpleDestination simpleDestination = new SimpleDestination();
              simpleDestination.setName( source.getName() );
              simpleDestination.setDescription( source.getDescription() );
              return simpleDestination;
          }
      
          @Override
          public SimpleSource destinationToSource(SimpleDestination destination){
              if ( destination == null ) {
                  return null;
              }
              SimpleSource simpleSource = new SimpleSource();
              simpleSource.setName( destination.getName() );
              simpleSource.setDescription( destination.getDescription() );
              return simpleSource;
          }
      }
      
  • 필드 이름이 다른 필드 매핑
    public class EmployeeDTO {
        private int employeeId;
        private String employeeName;
    }
    
    public class Employee {
        private int id;
        private String name;
    }
    
    @Mapper
    public interface EmployeeMapper {
        @Mappings({
            @Mapping(target="employeeId", source="entity.id")
            @Mapping(target="employeeName", source="entity.name")
        })
        EmployeeDTO employeeToEmployeeDTO(Employee entity);
    
        @Mappings({
            @Mapping(target="id", source="dto.employeeId"),
            @Mapping(target="name", osurce="dto.employeeName")
        })
        Employee employeeDTOtoEmployee(EmployeeDTO dto);
    }