[Spring Boot] DAO - Service - Controller 구조 예시

2023. 4. 20. 19:52·Java/Spring Boot
728x90
728x90

#  DAO interface

더보기
1
2
3
4
5
6
7
@Mapper
public interface AccountRepository {
 
    // 계좌번호로 계좌 조회
    public Account findByNumber(String number);
    
}
Colored by Color Scripter
cs

 

#  DAO 쿼리문 xml

더보기
1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 
<mapper namespace="com.tenco.bank.repository.interfaces.AccountRepository">
    
    <select id="findByNumber" resultType="com.tenco.bank.repository.model.Account">
        SELECT * FROM account_tb WHERE number = #{number}
    </select>
    
</mapper>
Colored by Color Scripter
cs

 

#  Service

더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
@Service // IoC 대상
public class AccountService {
 
    @Autowired
    private AccountRepository accountRepository;
    
    @Autowired
    private HistoryRepository historyRepository;
 
 
    // 이체 처리
    @Transactional
    public void updateAccountTransfer(TransferFormDto transferFormDto, Integer principalId) {
        // 출금 계좌 존재 여부 확인 (select)
        Account withdrawAccountEntity = accountRepository.findByNumber(transferFormDto.getWAccountNumber());
        if (withdrawAccountEntity == null) {
            throw new CustomRestfullException("출금 계좌가 존재하지 않습니다.", HttpStatus.INTERNAL_SERVER_ERROR);
        }
        
        // 입금 계좌 존재 여부 확인 (select)
        Account depositAccountEntity = accountRepository.findByNumber(transferFormDto.getDAccountNumber());
        if (depositAccountEntity == null) {
            throw new CustomRestfullException("입금 계좌가 존재하지 않습니다.", HttpStatus.INTERNAL_SERVER_ERROR);
        }
        
        // 출금 계좌의 본인 소유 여부 확인
        withdrawAccountEntity.checkOwner(principalId);
        
        // 출금 계좌 비밀번호 확인 
        withdrawAccountEntity.checkPassword(transferFormDto.getWAccountPassword());
        
        // 출금 계좌 잔액 여부 확인
        withdrawAccountEntity.checkBalance(transferFormDto.getAmount());
        
        // 출금 계좌 잔액 변경 (update)
        withdrawAccountEntity.withdraw(transferFormDto.getAmount());
        accountRepository.updateById(withdrawAccountEntity);
        
        // 입금 계좌 잔액 변경 (update)
        depositAccountEntity.deposit(transferFormDto.getAmount());
        accountRepository.updateById(depositAccountEntity);
        
        // 거래 내역 저장 (insert)
        History history = new History();
        history.setAmount(transferFormDto.getAmount());
        history.setWAccountId(withdrawAccountEntity.getId());
        history.setDAccountId(depositAccountEntity.getId());
        history.setWBalance(withdrawAccountEntity.getBalance());
        history.setDBalance(depositAccountEntity.getBalance());
        int resultRowCount = historyRepository.insert(history);
        
        if (resultRowCount != 1) {
            throw new CustomRestfullException("정상 처리되지 않았습니다.", HttpStatus.INTERNAL_SERVER_ERROR);
        }
        
    }
}
Colored by Color Scripter
cs

 

#  Controller

더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
@Controller
@RequestMapping("/account")
public class AccountController {
 
    @Autowired
    private HttpSession session;
    
    @Autowired
    private AccountService accountService;
 
 
    // 이체 기능
    @PostMapping("/transfer-proc")
    public String transferProc(TransferFormDto transferFormDto) {
        
        // 인증 검사
        User principal = (User) session.getAttribute(Define.PRINCIPAL);
        
        if (principal == null) {
            throw new UnAuthorizedException("로그인 후 이용해주세요.", HttpStatus.UNAUTHORIZED); // 인증되지 않음 (401)
        }
        
        // 유효성 검사
        // 출금 계좌번호 입력 여부
        if (transferFormDto.getWAccountNumber() == null || transferFormDto.getWAccountNumber().isEmpty()) {
            throw new CustomRestfullException("출금 계좌번호를 입력하세요.", HttpStatus.BAD_REQUEST);
        }
 
        // 입력 계좌번호 입력 여부
        if (transferFormDto.getDAccountNumber() == null || transferFormDto.getDAccountNumber().isEmpty()) {
            throw new CustomRestfullException("입금 계좌번호를 입력하세요.", HttpStatus.BAD_REQUEST);
        }
        
        // 출금 계좌 비밀번호 입력 여부
        if (transferFormDto.getWAccountPassword() == null || transferFormDto.getWAccountPassword().isEmpty()) {
            throw new CustomRestfullException("출금 계좌 비밀번호를 입력하세요.", HttpStatus.BAD_REQUEST);
        }
        
        // 이체 금액 확인
        if (transferFormDto.getAmount() == null) {
            throw new CustomRestfullException("이체 금액을 입력하세요.", HttpStatus.BAD_REQUEST);
        }
        
        if (transferFormDto.getAmount() <= 0) {
            throw new CustomRestfullException("이체 금액을 1원 이상 입력하세요.", HttpStatus.BAD_REQUEST);
        }
        
        // 출금 계좌번호와 입금 계좌번호가 동일하지 않은지 확인
        if (transferFormDto.getWAccountNumber().equals(transferFormDto.getDAccountNumber())) {
            throw new CustomRestfullException("출금 계좌번호와 입금 계좌번호가 동일합니다.", HttpStatus.BAD_REQUEST);
        }
        
        // 서비스 호출
        accountService.updateAccountTransfer(transferFormDto, principal.getId());
        
        return "redirect:/account/list";
    }
 
}
Colored by Color Scripter
cs

 

  - 인증 검사는 반복되므로 인터셉터로 하기

 

320x100
반응형
저작자표시 비영리 변경금지 (새창열림)

'Java > Spring Boot' 카테고리의 다른 글

[Spring Boot] 파비콘 설정 방법  (0) 2023.04.21
[Spring Boot] Controller에서 jsp 파일로 데이터 전달  (0) 2023.04.21
[Spring Boot] 트랜잭션 어노테이션  (0) 2023.04.19
[Spring Boot] Model 클래스 (Entity)와 DTO 클래스  (0) 2023.04.19
[Spring Code] 사용자 정의 예외 클래스와 에러 페이지  (0) 2023.04.19
'Java/Spring Boot' 카테고리의 다른 글
  • [Spring Boot] 파비콘 설정 방법
  • [Spring Boot] Controller에서 jsp 파일로 데이터 전달
  • [Spring Boot] 트랜잭션 어노테이션
  • [Spring Boot] Model 클래스 (Entity)와 DTO 클래스
스응
스응
    반응형
    250x250
  • 스응
    이서영의 개발 블로그
    스응
  • 전체
    오늘
    어제
  • 글쓰기 관리
    • 분류 전체보기 (385)
      • Java (134)
        • Base (54)
        • Spring Boot (37)
        • JSP (16)
        • Swing (GUI) (20)
        • Design Pattern (7)
      • C# (13)
      • PHP (18)
      • SQL (27)
      • Vue.js (9)
      • Tailwind CSS (4)
      • TypeScript (7)
      • HTML & CSS (27)
      • JavaScript (26)
      • jQuery (10)
      • Android (3)
      • - - - - - - - - - - - - - - (0)
      • Hotkeys (5)
      • CS (30)
      • IT Notes (13)
      • Error Notes (17)
      • Team Project (24)
        • Airlines Web Project (12)
        • University Web Project (6)
        • Strikers 1945 GUI Project (6)
      • My Project (18)
        • Library Web Project (8)
        • Pet Shopping Mall GUI Project (10)
      • etc. (0)
  • 블로그 메뉴

    • Home
    • Write
  • 링크

    • 깃허브
  • 공지사항

  • 인기 글

  • 태그

    Codeigniter
    Android
    SpringBoot
    Hotkeys
    개발일지
    git
    jQuery
    java
    면접
    js
    errorNote
    tailwindcss
    CSS
    오블완
    http
    C#
    SWAGGER
    SEO
    HTML
    Wordpress
    cs
    SQL
    typeScript
    vuejs
    티스토리챌린지
    php
    jsp
    zapier
    Swing
  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.0
스응
[Spring Boot] DAO - Service - Controller 구조 예시
상단으로

티스토리툴바