본문 바로가기

java/jsp & sevlet

DAO와 DTO

자바의 디자인 패턴에서는 일반적으로 db와의 통신 기능을 별도의 모듈로 분할할 것을 추천한다. 

그래야 기능 간에 의존성이 줄어들어 디버깅 및 유지보수에 유리하기 때문이다.

  • DAO(data access object)는 데이터베이스 접근하여 연산을 수행하는 로직
  • DTO (Data Transfer Object)(VO)는 쿼리 결과로 가져온 데이터를 자바의 collection같은 데이터 타입에 맞게 변환하여 비즈니스 로직이나 view 계증으로 전달하는 로직

 

작성


DTO 생성 및 DTO 생성

일반적으로 dao 클래스 파일은 별도의 com.DAO 같은 패키지로 구분하며 이름은 <연결된 sevlet파일>+DAO 의 형식으로 작성한다.

dto도 마찬가지로 패키지 분할과 네이밍 컨벤션을 지켜주면 유지보수에 편리하다.

이 방식은 초기에 작성하는 코드가 많으나, 점차 앱이 커질수록 확장에 유리하다.

 

import com.DAO.BookDAO;
import com.DTO.BookDTO;

@WebServlet("/book/select/all")
public class Add extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();

		//db에 접근 및 쿼리를 위해 dao 객체 생성
		BookDAO bookDAO= new BookDAO();
		ArrayList<BookDTO> results= bookDAO.selectAll(); 
		
		for(int i=0;i<results.size();i++) {
			int bookId = results.get(i).getBookId();
			String bookName = results.get(i).getBookName();
			out.println(i+"번 // "+"bookId: " + bookId + ", ");
			out.println("bookName: " + bookName + ", ");
			out.println("<br>");
		}
		


	}
	


}

 

package com.DAO;
import com.DTO.BookDTO;

public class BookDAO {
	String url = "jdbc:oracle:thin:@localhost:1521";
	String id = "계정 아이디";
	String password = "계정 비밀번호";
	Connection conn = null;
	PreparedStatement pstmt = null;

	public BookDAO() {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	public ArrayList<BookDTO> selectAll() {
		ArrayList<BookDTO> results = new ArrayList<BookDTO>();

		try {
			this.conn = DriverManager.getConnection(this.url, this.id, this.password);
			String query = "SELECT * FROM book";
			this.pstmt = conn.prepareStatement(query);
			ResultSet result = pstmt.executeQuery();

			while (result.next()) {
				int bookId = result.getInt("book_id");
				String bookName = result.getString("book_name");
				BookDTO bookDTO = new BookDTO(bookId, bookName);
				results.add(bookDTO);

			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				pstmt.close();
				conn.close();

			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return results;
	}
}
package com.DTO;

public class BookDTO {
	public int bookId;
	public String bookName;
	
	public BookDTO(int bookId, String bookName) {
	this.bookId = bookId;
	this.bookName =bookName;
	
	}

	public int getBookId() {
		return bookId;
	}

	public String getBookName() {
		return bookName;
	}
}