package dao;
//DAO-Data Access Object//srp - 단일책임의 원칙import db.DBConnection;
import model.Account;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
publicclassBankDAO {
publicintdeleteByNumber(int number){
Connectionconn= DBConnection.getInstance();
try {
Stringsql="delete from account_tb where number = ?";
PreparedStatementpstmt= conn.prepareStatement(sql);
pstmt.setInt(1,number);
intnum= pstmt.executeUpdate();
return num;
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
publicintinsert(String password, int balance){
Connectionconn= DBConnection.getInstance();
try {//쿼리라서 소문자로 씀. 카멜 말고Stringsql="insert into account_tb(password,balance,created_at) values(?,?, now())";
PreparedStatementpstmt= conn.prepareStatement(sql);
pstmt.setString(1,password);
pstmt.setInt(2,balance);
//intnum= pstmt.executeUpdate();
return num;
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
publicintupdateByNumber(int balance, int number){
Connectionconn= DBConnection.getInstance();
try {//쿼리라서 소문자로 씀. 카멜 말고Stringsql="update account_tb set balance = ? where number = ?";
PreparedStatementpstmt= conn.prepareStatement(sql);
pstmt.setInt(1,balance);
pstmt.setInt(2,number);
intnum= pstmt.executeUpdate();
return num;
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
public Account selectByNumber(int number){
Connectionconn= DBConnection.getInstance(); // 꼭 있기try {
Stringsql="select * from account_tb where number = ?";
PreparedStatementpstmt= conn.prepareStatement(sql);
pstmt.setInt(1,number);
ResultSetrs= pstmt.executeQuery();
if(rs.next()){
Accountaccount=newAccount(
rs.getInt("number"),
rs.getString("password"),
rs.getInt("balance"),
rs.getTimestamp("created_at")
);
return account;
}
}catch (Exception e){
e.printStackTrace();
} returnnull;
}
public List<Account> selectAll(){
Connectionconn= DBConnection.getInstance(); // 꼭 있기//java >> db bytestream 생김try {
Stringsql="select * from account_tb order by number desc";
PreparedStatementpstmt= conn.prepareStatement(sql);
//쿼리sql을 버퍼에 담음(""꺼)ResultSetrs= pstmt.executeQuery();
//sql flush(exe)하고 db가 응답해줌. / 그래서 br에 table이 옴.
List<Account> accountList = newArrayList<>(); // 스택 이야기 account 없어진다고?while(rs.next()){
Accountaccount=newAccount(
rs.getInt("number"),
rs.getString("password"),
rs.getInt("balance"),
rs.getTimestamp("created_at")
);
accountList.add(account);
}
return accountList;
}catch (Exception e){
e.printStackTrace();
} returnnull;
}
}
추상화_그림그리기(코드로 보면 안돼)
클래스(다른 타입) > collection(연속) >
하나씩 하면 안되니까 하나 model account만듦
>false나오면 종료. account list 반환되니까 분홍색을 줌.
lombok 다운
이건 유명하니까 lombok > download해도 됨. 혹은 방법 2
혹은 아래 코드 복사하여 intellij 코끼리 넣는 부분에 넣기
lombok 다운
MVN REPOSITORY
-같은 게 많으면 이런 식으로 usages가 많은 거 사용하면 됨.
아래와 같이 있어도 디폴트 생성자 있는 것임
아무것도 안 만들었으니 기본으로 만들어짐.
crud : 이거 함.
create - insert
read -select
update
delete
number = x-1하면 안 됨.
이런 식으로 파라미트가 있어야 재사용 가능-v
try catch가 더 편함. 근데 return값이 -1,0,1인 경우도 알아야 해서 지금 이렇게 씀
여기서 set balance = balance +1000 이런 식으로 안 적는다.
이유는 증/감 모두 해야 되서 ‘?’로 함.
여러가지 테스트 방식이 있지만 우리는 이런 테스트 방식 씀
(given/when/then)
rs가 통으로 가지고 있음
rs- (git의 header처럼)커서를 들고 있음.
그 커서가 처음에는 coloumn (number줄)을 가르키고 있음
so,우리는 자료를 가져올 때 커서를 한 칸 밑으로 내려야 됨.
커서를 내리면서 읽어야 함.
projectiuon 4번(number, pw,balance, created_at 해서 총 4번)
result set하는 순간 또 정렬 >> 커서 내리고 projection 같은 거
-> so class에 담아야 함.
모든 계좌조회의 경우 arraylist 가능은 함.
이렇게 만들면 오류 뜸. 왜냐면 생성자가 없어서
💡
모든 파라미터의 생성자 만들어 주는 것.
so, 우리가 하나하나 하지 않아도 됨. lombok이 알아서 해줌.
즉, 이 경우 생성자를 하면 됨. 오류 사라짐.
(초기화시킬 때에는) 생성자 만들어서 하는 게 편함
setter도 가능하지만 동료가 싫어할 것임.
setter는 정보를 변경할 때하는 것. ex) balance값을 변경한다든지.
HELLO로 할지 account1로 만들지 어떻게 알아?(변수, 클래스 명이 다를 수 있으니까 resultset 로 함)
그래서 resutset rs = pstmt.executeQuery();식으로 함.
result 해서 하면 또 ~해야 되서 이걸로(account로-v)
부모라서. DIP
추상적인 것에 의존
내림차순해 줘야 (10~1 이런 순)
기본-오름차순
so, 전체조회는 거꾸로 (최근부터 해야 함.)
댓글 2000개 , insta -order by 최근 순. (descending) 아니면 나의 글 못 찾음. (왜냐하면 제일 오래된 글이 제일 위에 떠 있을 테니까)
이렇게 되면 박스를 계속 담고 버리고 다시 박스 만들고 버리고 의미 없어서 collection에 담아야 하미.
그리고 Account account를 while 문 앞에 배치. (박스 계속 만들 필요 없으니까)
여기서 자바부분을 좀 더 자세히 보면,
메인에서 키보드를 가지고 메인에서 요청 받으면 controler를 만들어줌 그것이 dao 호출 그것은 db호출 하나하나는 레이어라고 함.
keyboard(요청-v)→ main(실행시키는 것) > controller(클라이언트의 요청을 받는 애. (요청을 분기시키는 아이), 그 요청을 받아서 dao에 필요한 메서드를 호출하는 애. ) > dao (database와 상호작용하는 거.책임 안에 5개의 매서드 가지고 있음. ssidu)> db
자원명 대신 (파일명이 아니라) 식별자를 넣음.
op.gg?
//http://bank.com/account ~ 이렇게 주소만 적으면 생성/조회인지 몰라. 그래서 http매서드가 필요. 그게 get