반응형
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;
...
}
반응형
'Coding > Spring' 카테고리의 다른 글
Spring Cloud Bus 적용하기 (0) | 2021.06.11 |
---|---|
SpringBoot + Microservice 프로젝트에서 Spring Cloud Config 적용하기 (0) | 2021.06.10 |
CommonException 으로 @Valid 어노테이션 BindingException, MethodArgumentNotValidException 처리하기 (0) | 2021.02.18 |
SpringBoot + PasswordEncoder 사용하여 패스워드 암/복호화 실행하기 (0) | 2021.02.18 |
SpringBoot에서 Redis로 Session 구현하기 (0) | 2021.02.14 |