Language/Java

DAO pattern

do-oni 2021. 8. 11. 02:38

08.10 TIL

 

DAO pattern 
- 다오 / 디에이오
- Data Access Object
- SQL + JAVA  -> CRUD 기능의 메소드들로 구현된 클래스
- DB 연동 클래스를 정형화 해서 개발하게 하는 구조
- 권장 클래스명 : table명.DAO.java
- 권장 구조 : table당 1:1 클래스 개발 / 
                       기능에 따라 다수의 table들의 CRUD 기능이 소량인 경우
                       여러 table을 하나의 DAO로 개발 가능

 

Dept table의 DAO class
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import org.junit.Test;

import model.dto.DeptDTO;
import util.DBUtil;

public class DeptDAO {

//	@Test
	public void deleteOne() {
		Connection con = null;
		Statement stmt = null;

		try {
			con = DBUtil.getConnection();
			stmt = con.createStatement();

			int result = stmt.executeUpdate("DELETE FROM dept WHERE deptno=60");

			if (result == 1) {
				System.out.println("삭제 성공");
			} else {
				System.out.println("deptno 삭제 실패");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(con, stmt);
		}
	}

//	@Test	
	public void updateOne() {
		Connection con = null;
		Statement stmt = null;

		try {
			con = DBUtil.getConnection();
			stmt = con.createStatement();

			int result = stmt.executeUpdate("UPDATE dept SET loc='평양' WHERE deptno=60");

			if (result == 1) {
				System.out.println("수정 성공");
			} else {
				System.out.println("deptno 수정 실패");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(con, stmt);
		}
	}

//	@Test
	public void insertOne() {
		Connection con = null;
		Statement stmt = null;

		try {
			con = DBUtil.getConnection();
			stmt = con.createStatement();

			int result = stmt.executeUpdate("insert into dept values (60, '교육부', '남부')");

			if (result == 1) {
				System.out.println("저장 성공");
			} else {
				System.out.println("deptno 중복 저장 불허");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(con, stmt);
		}
	}

// 부서번호(deptno)로 한 부서 정보만 검색
	//@Test
	public static void selectOne() {
		Connection con = null;
		Statement stmt = null;
		ResultSet rset = null;

		try {
			con = DBUtil.getConnection();
			stmt = con.createStatement();
			rset = stmt.executeQuery("select ename from emp where deptno = 10;");

			if (rset.next()) {
				System.out.println(rset.getString("dname"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(con, stmt, rset);
        }
	}

// 모든 검색
//	@Test
	public void selectAll() {
		Connection con = null;
		Statement stmt = null;
		ResultSet rset = null;

		try {
			con = DBUtil.getConnection();
			stmt = con.createStatement();

			rset = stmt.executeQuery("select * from dept");

			while (rset.next()) {
				System.out.println(rset.getInt("deptno") + "/" + rset.getString("dname") + "/" + rset.getString("loc"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(con, stmt, rset);
		}
	}

// sql 문장 처리 : Statement API 활용
	public static void insertOne2(DeptDTO dept) {
		Connection con = null;
		Statement stmt = null;

		try {
			con = DBUtil.getConnection();
			stmt = con.createStatement();

//			int result = stmt.executeUpdate("insert into dept values (60, '교육부', '남부')");
			String sql = "insert into dept values (" + dept.getDeptno() + ", '" + dept.getDname() + "', '"
			+ dept.getLoc() + "')";
			System.out.println(sql);

			int result = stmt.executeUpdate(sql);

			if (result == 1) {
				System.out.println("저장 성공");
			} else {
				System.out.println("deptno 중복 저장 불허");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(con, stmt);
		}
	} // end of insertOne2()

// sql 문장 처리 : PreparedStatement API 활용
	public static void insertOne3(DeptDTO dept) {
		Connection con = null;
		PreparedStatement pstmt = null;

		try {
        	con = DBUtil.getConnection();
            pstmt = con.prepareStatement("insert into dept values (?, ?, ?)");

// ? 위치에 값 대입
			pstmt.setInt(1, dept.getDeptno());
			pstmt.setString(2, dept.getDname());
			pstmt.setString(3, dept.getLoc());

// sql문장 실제 실행
			int result = pstmt.executeUpdate();

			if (result == 1) {
				System.out.println("저장 성공");
			} else {
				System.out.println("deptno 중복 저장 불허");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(con, pstmt);
		}
	} // end of insertOne2()

// 모든 부서의 정보를 검색해서 반환 -> main에서 출력
	public static ArrayList<DeptDTO> selectAll2() throws SQLException {

		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rset = null;
		ArrayList<DeptDTO> all = null;

		try {
			con = DBUtil.getConnection();
			pstmt = con.prepareStatement("select * from dept");
			rset = pstmt.executeQuery();

// 접속 OK/sql문장 실행 OK 후에 객체 생성
			all = new ArrayList<>();

			while (rset.next()) {
// 			public DeptDTO(int deptno, String dname, String loc) {}
				all.add(new DeptDTO(rset.getInt("deptno"), rset.getString("dname"), rset.getString("loc")));
			}

//		} catch (SQLException e) {
//			e.printStackTrace();
//			//문제가 생겼을때 Client에게도 상황 전달을 위해 예외를 호출한 곳으로 위임
//			throw e;
		} finally {
			DBUtil.close(con, pstmt, rset);
		}
		return all;
    }

public static void main(String[] args) {
//		insertOne2(new DeptDTO(70, "a", "b"));
//		insertOne3(new DeptDTO(76, "a", "b"));
selectOne();

//초기화를 안할 경우 예외 발생시 all 변수에 대입이 안되기 때문에 all 변수는 어떠한 값도 없는 상태 따라서 사용 불가
//for문에서 문법 에러 발생했음
//		ArrayList<DeptDTO> all = null;

//controller
//		try {
//			all = selectAll2();
//		} catch (SQLException e) {
//			e.printStackTrace();
//		}

//view
//		for (DeptDTO dept : all) {
//			System.out.println(dept); // dept.toString()
//		}
//
}
}​