[Spring] Entity를 Dto로 변환(MapStruct)

    [Spring] Entity를 Dto로 변환 하는 방법 알아보기

    MapStruct란?

    MapStruct는 자바 언어로 작성된 객체 매핑 라이브러리입니다. 이를 사용하면 DTO(Data Transfer Object)와 Entity(Entity Class) 객체간의 변환을 쉽게 할수 있습니다. MapStruct의 가장 큰 장점은 컴파일 시점에서 코드를 생성하여 속도가 빠르다.

    1. 의존성 추가

    plugins {
        id 'java'
    }
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        implementation 'org.mapstruct:mapstruct:1.4.2.Final'
        annotationProcessor 'org.mapstruct:mapstruct-processor:1.4.2.Final'
    }

    2. User Entity, UserDto 추가

    public class UserDTO {
        private Long id;
        private String name;
        private String email;
        // getter, setter, constructor
    }
    
    @Entity
    public class User {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
        private String name;
        private String email;
        // getter, setter, constructor
    }

    3. 두 클래스간에 변환을 위한 매핑 인터페이스 추가

    @Mapper(componentModel = "spring")
    public interface UserMapper {
        UserDTO userToUserDTO(User user);
        User userDTOToUser(UserDTO userDTO);
    }

    @Mapper - MapStruct에게 이 인터페이스를 매퍼로 사용한다는 것을 알려주는 역할

    componentModel - Spring Framework와의 연동을 위한 설정값

    4. 예시

    User user = new User();
    user.setId(1L);
    user.setName("John");
    user.setEmail("john@example.com");
    
    UserMapper userMapper = Mappers.getMapper(UserMapper.class);
    
    UserDTO userDTO = userMapper.userToUserDTO(user);
    System.out.println(userDTO.getId());      // 1
    System.out.println(userDTO.getName());    // John
    System.out.println(userDTO.getEmail());   // john@example.com
    
    User newUser = userMapper.userDTOToUser(userDTO);
    System.out.println(newUser.getId());      // 1
    System.out.println(newUser.getName());    // John
    System.out.println(newUser.getEmail());   // john@example.com

    5. Entity Dto 변환 이유

    DTO(Data Transfer Object)는 데이터 전송을 위한 객체이며, 데이터를 단순화하고 필요한 데이터만을 포함하도록 설계되어 있습니다. 보통 DTO는 비즈니스 로직을 처리하기 위해 사용되는 Entity 객체와 별개로 사용됩니다.

    Entity 클래스는 DB의 데이터를 객체로 매핑한 클래스로, 보통 JPA를 사용하여 ORM(Object-Relational Mapping)을 수행할 때 사용됩니다. Entity 클래스는 DB의 테이블과 매핑되기 때문에, 비즈니스 로직과 DB 스키마가 혼재되는 문제가 있습니다.

    따라서, DTO와 Entity 객체간에 변환을 수행하여, 데이터 전송과 비즈니스 로직 처리를 분리할 수 있습니다. 이를 통해 불필요한 데이터를 제거하고, 더욱 간결하고 유연한 코드를 작성할 수 있습니다. 또한, DTO와 Entity 간에 필드명이 다른 경우에도 이를 해결할 수 있습니다. 이를 통해 유지 보수성이 향상되며, 코드의 가독성도 높아집니다.

    댓글

    Designed by JB FACTORY