Spring boot

[Spring boot] Bank App 만들어 보기 - 19. 계좌 목록 만들기(1단계)

ekkkang 2025. 3. 5. 15:48

 

💡 작업 순서
1. AccountRepository, account.xml 코드 수정하기
2. 계좌 목록 기능 만들기
3. account/list.jsp 파일을 생성(코드 복사 후 수정)

 

1. AccountRepository, account.xml 코드 수정하기

package com.tenco.bank.repository.interfaces;

import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import com.tenco.bank.repository.model.Account;

@Mapper  
public interface AccountRepository {
	
	// 코드 확인 (계좌 생성) 
	public int insert(Account account);
	public int updateById(Account account);
	public int deleteById(Integer id);
	
	// 계좌 조회 - 1 유저 , N 계좌 
	public List<Account> findAllByUserId();
	public Account findByNumber(Integer id);
	
}

 

<select id="findAllByUserId" resultType="com.tenco.bank.repository.model.Account">
    select * from account_tb 
</select>

해당 코드에서 계좌 목록 기능과 관련된 부분을 확인하고 어떤 부분이 잘못되었는지 확인해 봅시다.

 

 

코드 수정

 

account.xml 쿼리 수정

<select id="findAllByUserId" resultType="com.tenco.bank.repository.model.Account">
    select * from account_tb where user_id = #{userId} 
</select>

 

AccountRepository.java 자바 코드 수정

// 계좌 조회 - 1 유저 , N 계좌
// interface 파라미터명과 xml에 사용할 변수명을 다르게 해야 된다면 @Param 
// 어노테이션을 활용할 수 있습니다. 
// 2개 이상에 파라미터을 설계한다면 반드시 @Param 어노테이션을 지정해 주세요 
public List<Account> findAllByUserId(@Param("userId") Integer principalId);

: 우리 서비스에서는 모임 통장 개념은 사용하지 않습니다. 한 명에 유저는 여러개의 계좌를 가질 수 있다 정도로 정의 하겠습니다. 만약 N:N 관계, 한 학생이 여러 개의 강좌를 수강할 수 있고, 한 강좌가 여러 학생에 의해 수강될 수 있는 경우 데이터베이스에 모델링하는 것은 불가능하기 때문에, 일반적으로 중간 테이블(또는 연결 테이블, 조인 테이블이라고도 함)을 사용하여 N:N 관계를 두 개의 1:N(일대다) 관계로 분리합니다.

 

간단한 예시

CREATE TABLE 학생 (
    학생ID INT PRIMARY KEY,
    이름 VARCHAR(100)
);

CREATE TABLE 강좌 (
    강좌ID INT PRIMARY KEY,
    강좌명 VARCHAR(100)
);

CREATE TABLE 수강 (
    학생ID INT,
    강좌ID INT,
    PRIMARY KEY (학생ID, 강좌ID),
    FOREIGN KEY (학생ID) REFERENCES 학생(학생ID),
    FOREIGN KEY (강좌ID) REFERENCES 강좌(강좌ID)
);

 

 

2. 계좌 목록 기능 만들기

AccountService 코드 추가

/**
 * 복잡한 Select 쿼리문일 경우 트랜잭션 처리를 해주 것이 좋습니다.  
 * 여기서는 단순한 Select 구문이라 바로 진행 합니다. 
 * @param principalId
 * @return
 */
public List<Account> readAccountListByUserId(Integer principalId) {
    List<Account> accountListEntity = null;
    try {
        accountListEntity = accountRepository.findAllByUserId(principalId);
    } catch (DataAccessException e) {
        throw new DataDeliveryException("잘못된 처리 입니다", HttpStatus.INTERNAL_SERVER_ERROR);
    } catch (Exception e) {
        // 예외 처리 - 에러 페이지로 이동
        throw new RedirectException("알 수 없는 오류", HttpStatus.SERVICE_UNAVAILABLE);
    }
    return accountListEntity;
}

 

엔티티는 일반적으로 데이터베이스와 관련된 컨텍스트에서 사용되는 용어로, 실제 세계의 객체나 사물을 데이터베이스에서 표현한 것을 의미합니다. 일반적으로 데이터베이스의 테이블로 매핑되며, 각 엔티티의 인스턴스는 테이블의 레코드(또는 행)에 해당합니다.

 

AccountController 코드 추가

	/**
	 * 계좌 목록 페이지
	 * 
	 * @param model - accountList
	 * @return list.jsp
	 */
	@GetMapping({ "/list", "/" })
	public String listPage(Model model) {
		
		// 1.인증 검사가 필요(account 전체 필요)
		User principal = (User) session.getAttribute("principal");
		if (principal == null) {
			throw new UnAuthorizedException("인증된 사용자가 아닙니다", HttpStatus.UNAUTHORIZED);
		}

		// 경우의 수 -> 유, 무
		List<Account> accountList = accountService.readAccountListByUserId(principal.getId());

		if (accountList.isEmpty()) {
			model.addAttribute("accountList", null);
		} else {
			model.addAttribute("accountList", accountList);
		}

		return "account/list";
	}

 

 

3. account/list.jsp 파일을 생성(코드 복사 후 수정)

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!-- header.jsp -->
<%@ include file="/WEB-INF/view/layout/header.jsp"%>

<!-- start of content.jsp(메인 영역)   -->
<div class="col-sm-8">
	<h2>계좌 목록(인증)</h2>
	<h5>Bank App 오신 걸 환영합니다.</h5>
		<c:choose>
		<c:when test="${accountList != null }">
			<table class="table">
				<thead>
					<tr>
						<th>계좌 번호</th>
						<th>잔액</th>
					</tr>
				</thead>
				<tbody>
					<c:forEach var="account" items="${accountList}">
						<tr>
							<td>${account.number}</td>
							<td>${account.balance}</td>
						</tr>
					</c:forEach>

				</tbody>
			</table>
		</c:when>
		<c:otherwise>
		<div class="jumbotron display-4">
			<h5><small>아직 생성된 계좌가 없습니다</small></h5>
		</div>
		</c:otherwise>
	</c:choose>
</div>
</div>
</div>

<!-- end of content.jsp(메인 영역)   -->

<!-- footer.jsp -->
<%@ include file="/WEB-INF/view/layout/footer.jsp"%>

 

 

결과 화면 확인 - 계좌 생성 기능을 통해서 동작을 확인해 주세요

 

 

계좌가 없을 경우 화면