ㅅㅇ

[Spring Boot, Java] Entity ↔ DTO 변환 : 자바 코드 매핑 & ModelMapper 본문

SW_STUDY/SpringBoot

[Spring Boot, Java] Entity ↔ DTO 변환 : 자바 코드 매핑 & ModelMapper

SO__OS 2023. 3. 8. 19:57

첫 번째 방법 - 자바 코드 매핑

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Builder
public class AccountDTO {
	
	private int accountId;
	private String accountEmail;
	private String accountPassword;
	private String accountName;
	
    public static AccountDTO toDTO(AccountEntity account) {
    	
        return new AccountDTO(
                account.getAccountId(),
                account.getAccountEmail(),
                account.getAccountPassword(),
                account.getAccountName(),
    }
}
@Entity
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor
@Getter
@Setter
@Builder
@Table(name="account_privacy")
public class AccountEntity {
	
	@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "account_id")
	private int accountId;
	
  @Column(name = "account_email")
	private String accountEmail;
	
  @Column(name = "account_password")
	private String accountPassword;
	
  @Column(name = "account_name")
	private String accountName;

}
@Transactional
	public AccountDTO signUp(SignUpDTO signUpRequest) throws Exception {

		String encodedPassword = passwordEncoder.encode(signUpRequest.getAccountPassword());

		// DTO -> Entity
		AccountEntity account = AccountEntity.builder().accountEmail(signUpRequest.getAccountEmail())
				.accountPassword(encodedPassword).accountName(signUpRequest.getAccountName()).build();

		account = accountRepository.save(account);

		return AccountDTO.toDTO(account); //Entity -> DTO

	}

 

두 번째 방법 - ModelMapper

  • Maven dependency 추가 - pom.xml 파일에 아래 코드 추가
<!-- Model Mapper : DTO와 Entity 호환 API -->
		<dependency>
			<groupId>org.modelmapper</groupId>
			<artifactId>modelmapper</artifactId>
			<version>2.4.0</version>
		</dependency>
@Autowired
private AccountRepository accountRepository;

static ModelMapper modelMapper = new ModelMapper();

@Transactional
public AccountDTO findAccount(int accountId) throws Exception {

	Optional<AccountEntity> account = accountRepository.findById(accountId); // entity
	
	if(accountEntity.isPresent()) {
	
		// entity -> DTO
		AccountDTO accountDTO = modelMapper.map(account.get(), AccountDTO.class);

		// DTO -> entity
		AccountEntity accountEntity = modelMapper.map(accountDTO, AccountEntity.class);
	
	}
	return accountDTO
}
@Autowired
private AccountRepository accountRepository;

static ModelMapper modelMapper = new ModelMapper();

@Transactional
public List<AccountDTO> findAccountList() throws Exception {

	List<AccountEntity> accountListEntity = (List<AccountEntity>) accountRepository.findAll();
	
	// entity -> DTO
	List<AccountDTO> accountListDTO = accountListEntity.stream().map(a -> modelMapper.map(a, AccountDTO.class)).collect(Collectors.toList());
	
	return accountDTO;
}