Spring 에서 Entity -> Dto 로 변환하는 ModelMapper 사용

반응형
728x90
반응형

1) pom.xml 추가

<dependency>
  <groupId>org.modelmapper</groupId>
  <artifactId>modelmapper</artifactId>
  <version>2.3.8</version>
</dependency>

 

 

2) ModelMapper 사용

  • UserEntity.java
@Setter
@Getter
@Entity
@Table(name = "users")
public class UserEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long idx;

    @Column(nullable = false, length = 50)
    private String userId;

    @Column(nullable = false, length = 50)
    private String userName;
}

 

  • UserDto.java
@Data
public class UserDto {
    private Long idx;
    private String userId;
    private String userName;
}

 

  • UserService.java

UserEntity.java 를 UserDto.java 로 변환을 실행한다.

public ResponseEntity<?> createUser(@RequestBody RequestUser user) {
    ModelMapper mapper = new ModelMapper();
    mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); /* 강력하게 */

    UserDto userDto = mapper.map(userEntity, UserDto.class);
	...
}

 

  • 연결전략
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); /* 강력하게 */

해당 코드를 통해, 변환을 더 강력하게 설정한다. 같은 타입/같은 필드명이 변환의 대상이 된다.

 

 

ModelMapper Bean 등록하여 사용

  • AppConfig.java
package com.login.common;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class AppConfig {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }
}

 

  • xxService.java
package com.front.allset.service;

import com.front.allset.common.ResponseDto;
import com.front.allset.dto.UserDto;
import com.front.allset.form.RegisterForm;
import com.front.allset.restclient.UserRestClient;
import lombok.RequiredArgsConstructor;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class UserService {
    private final ModelMapper modelMapper;
    
    ...
}

 

 

반응형

Designed by JB FACTORY