1. MapStruct란?
이전 JPA프로젝트를 할때에는 MapStruct 라이브러리를 사용하지 않고 직접 매핑해주었다

그런데 이번 JPA프로젝트를 하면서 MapStruct를 알게 되어서 편리하게 사용했다
MapStruct란 무엇일까?
MapStruct – Java bean mappings, the easy way!
Java bean mappings, the easy way! Get started Download
mapstruct.org
MapStruct의 document를 정리해보면
↓↓ 더보기 클릭
MapStruct는 유형이 안전한 빈 매핑 클래스 생성을 위한 Java 주석 프로세서 입니다.
필요한 매핑 방법을 선언하는 매퍼 인터페이스를 정의하기만 하면 됩니다. 컴파일하는 동안 MapStruct는 이 인터페이스의 구현을 생성합니다.
직접 매핑 코드를 작성하는 것에 비해 MapStruct는 작성하기 지루하고 오류가 발생하기 쉬운 코드를 생성하여 시간을 절약합니다.
간단히 말해서 "매핑 구현을 단순화하는 코드 생성기"라고 할 수 있다.
<MapStruct의 장점>
1. 리플렉션 대신 일반 메서드 호출을 사용하여 빠른 실행
2. 컴파일 시간 유형 안전성: 서로 매핑되는 개체와 속성만 매핑할 수 있으며 주문 엔터티를 고객 DTO에 실수로 매핑하는 일이 없다
그럼 이제 MapStruct를 프로젝트에 적용해보자
2. MapStruct 사용법
1) gradle에 아래 두줄을 입력하고 build한다
// mapstruct
implementation "org.mapstruct:mapstruct:1.5.5.Final"
annotationProcessor "org.mapstruct:mapstruct-processor:1.5.5.Final"
test를 사용한다면 아래 코드를 추가하면 된다
testAnnotationProcessor "org.mapstruct:mapstruct-processor:1.5.5.Final"
2) boardEntity와 BoardDto 파일 생성
3) util폴더에 interface로 EntityMapStruct 생성
public interface EntityMapStruct<D, E> {
E toEntity(D dto);
D toDto(E entity);
}
4) @Mapper 어노테이션이 있는 BoardMapStruct 파일 생성한다
BoardMapStruct INSTANCE = Mappers.getMapper(BoardMapStruct.class) 는 매퍼 클래스에서 MessageMapper 를 찾을 수 있도록 하는 방법이다. 매퍼 interface에서 위와 같이 Instance를 선언해주면 매퍼에 대한 접근이 가능하다
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;
@Mapper
public interface BoardMapStruct extends EntityMapStruct<BoardDto, BoardEntity> {
BoardMapStruct INSTANCE = Mappers.getMapper(BoardMapStruct.class);
@Mapping(target = "boardEntity.attachedFileList", ignore = true)
BoardDto toDto(BoardEntity boardEntity);
@Mapping(target = "boardDto.attachedFileList", ignore = true)
BoardEntity toEntity(BoardDto boardDto);
}
+ Mapper에 대해 좀 더 자세히알아보자 (주체의 이름이 target의 이름과 다르면?)
↓↓ 더보기 클릭
이제 자동으로 파일을 생성해준다
import javax.annotation.processing.Generated;
@Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2023-09-08T09:40:07+0900",
comments = "version: 1.5.5.Final, compiler: IncrementalProcessingEnvironment from gradle-language-java-8.2.1.jar, environment: Java 17.0.8 (Oracle Corporation)"
)
public class BoardListMapStructImpl implements BoardListMapStruct {
@Override
public BoardListDto toDto(BoardListEntity boardListEntity) {
if ( boardListEntity == null ) {
return null;
}
BoardListDto boardListDto = new BoardListDto();
boardListDto.setCompanyCode( boardListEntity.getCompanyCode() );
boardListDto.setBoardId( boardListEntity.getBoardId() );
boardListDto.setTitle( boardListEntity.getTitle() );
boardListDto.setDescription( boardListEntity.getDescription() );
boardListDto.setMenuId( boardListEntity.getMenuId() );
boardListDto.setIsSubject( boardListEntity.getIsSubject() );
boardListDto.setBoardType( boardListEntity.getBoardType() );
.... 생략
반복적으로 작성했던 코드를 자동화할 수 있어 꽤 유용하게 될것같다.

'Java, Spring' 카테고리의 다른 글
| [Java] 순차 스트림 (Sequential Stream)과 병렬 스트림 (Parallel Stream) & 스레드로 처리하기 (0) | 2023.11.14 |
|---|---|
| [JPA] Spring 3.0에서 queryDSL q파일 재생성하기(gradle) (0) | 2023.09.15 |
| [JPA] 동시성 문제 해결 / 비관적 락(Pessimistic Locking) / 인텔리제이에서 동시성 테스트하기 (0) | 2023.08.01 |
| [Java] 상속이란? 상속이란 기능은 어떻게 생겨났을까 (0) | 2022.03.03 |
| [Java] 생성자(Constructor)란? 생성자의 특징 (0) | 2022.03.03 |
