
최주호 강사님의 인프런 강좌 정리 및 실습한 기록
백엔드에서 프론트로 넘어가려면 JSON 형태로 직렬화를 거쳐야한다. 스프링부트는 JsonConverter 를 사용하는데 엔티티를 그대로 사용하면 어떤 문제가 발생할까?
MappingJackson2HttpMessageConverter 가 회원 비밀번호, 회원 주민번호 등 민감해서 프론트로 내보내지 않을 정보까지 모두 getter 로 긁어오면서 원치않는 LazyLoading 을 발생시킬 수 있다.
reflection 으로 동작하기 때문에 모든 field 에 대해서 getter, setter 를 적용시켜버린다. 즉, 내가 통제권을 잃는 것이다.
그래서 DTO 를 만들어서 꼭 필요한 필드만을 전달하는 것이다.
DB 에서 userId 를 이용해서 account 정보를 찾는다.
아직 AccountResponseDTO, AccountDTO 을 만들지 않았기 때문에 생성해야한다.
public AccountListResponseDTO selectAccountByAppUserId(Long appUserId) {
AppUser appUserPS = appUserRepository.findById(appUserId).orElseThrow(
() -> new CustomApiException("해당 유저를 찾을 수 없습니다.")
);
// 1명의 유저가 가지고 있는 모든 계좌 목록
// DTO 를 리턴하기 위해서 DTO 를 생성한다.
List<Account> accountListPS = accountRepository.findByAppUser_id(appUserId);
return new AccountListResponseDTO(appUserPS, accountListPS);
}
stream api 를 사용해서 account 를 accountDTO 로 변환한다.
@Getter
@Setter
public static class AccountListResponseDTO {
private String fullname;
private List<AccountDTO> accounts = new ArrayList<>();
public AccountListResponseDTO(AppUser appUser, List<Account> accounts) {
this.fullname = appUser.getFullname();
this.accounts = accounts.stream().map(AccountDTO::new).collect(Collectors.toList());
}
@Getter
@Setter
public class AccountDTO {
private Long id;
private Long number;
private Long balance;
public AccountDTO(Account account) {
this.id = account.getId();
this.number = account.getNumber();
this.balance = account.getBalance();
}
}
}