오늘 구현한 기능(Account)

Youngseon Kim·2023년 8월 4일
0

계좌 확인

  @GetMapping("/account")
    public List<AccountInfo> getAccountByUserId(
        @RequestParam("user_id") Long userId
    )
    {

        return accountService.getAccountByUserId(userId)
                .stream().map(accountDto ->
                        AccountInfo.builder()
                                .accountNumber(accountDto.getAccountNumber())
                                .balance(accountDto.getBalance())
                                .build())
                .collect(Collectors.toList());

    }

accountService.getAccountByUserId(userId): accountService에서 제공하는 getAccountByUserId(userId) 메서드를 호출한다. 이 메서드는 해당 사용자 ID에 해당하는 모든 계좌 정보를 조회하여 AccountDto 객체들을 List로 반환한다.

.stream(): accountService.getAccountByUserId(userId) 메서드가 반환한 List를 스트림으로 변환한다. 스트림은 데이터의 연속적인 흐름을 나타내며, 여기서는 AccountDto 객체들을 하나씩 처리하게 된다.

.map(accountDto -> AccountInfo.builder() ... .build()): map은 스트림의 요소를 하나씩 다른 형태로 변환하는 메서드이다. 여기서는 AccountDto 객체를 AccountInfo 객체로 변환하는 작업을 수행한다. accountDto는 스트림의 각 요소인 AccountDto 객체를 가리키는 변수이다.

AccountInfo.builder(): AccountInfo 클래스에 정의된 builder() 메서드를 호출하여 AccountInfo.Builder 객체를 생성한다. AccountInfo.Builder는 AccountInfo 객체를 생성하기 위한 빌더 패턴을 구현한 클래스이다.

.accountNumber(accountDto.getAccountNumber()): AccountInfo.Builder 객체에 accountDto에서 가져온 계좌 번호를 설정한다.

.balance(accountDto.getBalance()): AccountInfo.Builder 객체에 accountDto에서 가져온 잔액 정보를 설정한다.

.build(): AccountInfo.Builder 객체를 이용하여 최종적으로 AccountInfo 객체를 생성한다.

.collect(Collectors.toList()): collect 메서드는 스트림의 요소들을 수집하여 새로운 컬렉션으로 만드는 역할을 한다. Collectors.toList()는 스트림의 요소들을 List로 수집하여 반환한다. 따라서 최종적으로 AccountInfo 객체들을 담고 있는 List가 반환된다.

@Transactional
    public List<AccountDto> getAccountByUserId(Long userId) {
      

        AccountUser accountUser = accountUserRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User Not Found") );

        List<Account> accounts = accountRepository
                .findByAccountUser(accountUser);

        
        return accounts.stream()
                .map(AccountDto:: fromEntity)
                .collect(Collectors.toList());

        
    }

AccountUser accountUser = accountUserRepository.findById(userId): accountUserRepository에서 findById(userId) 메서드를 호출하여 주어진 userId에 해당하는 AccountUser 객체를 조회한다. 만약 해당 ID에 해당하는 데이터가 없을 경우 orElseThrow(() -> new RuntimeException("User Not Found") ); 부분에서 예외를 발생시킨다.

List accounts = accountRepository.findByAccountUser(accountUser);: accountRepository에서 findByAccountUser(accountUser) 메서드를 호출하여 주어진 accountUser에 해당하는 모든 Account 객체들을 조회하여 List에 저장한다.

return accounts.stream() ... .collect(Collectors.toList());: 위에서 조회한 accounts List를 스트림으로 변환한 다음, map 메서드를 사용하여 Account 객체들을 AccountDto 객체로 변환한다. 그리고 collect 메서드를 사용하여 AccountDto 객체들을 담고 있는 새로운 List로 반환한다. AccountDto::fromEntity는 AccountDto 클래스에 정의된 정적 메서드 fromEntity를 참조하여 사용하는 메서드 레퍼런스이다. 이를 통해 Account 객체를 AccountDto 객체로 변환하는 과정을 간편하게 처리할 수 있다.

0개의 댓글