Servlet/JSP - 데이터베이스를 위한 객체(DTO, DAO, VO)

 

jdbc를 통해 자바에서 데이터베이스에 접근하여 CRUD(Create, Read, Upadate, Delete)과정을 수행할 수 있다.

 

이때 데이터베이스를 이용한 로직을 짤 때, 코드의 유지보수와 확장성을 높이기 위해

 

DTO, DAO, VO라는 객체를 만들어서 사용한다.

 

 

1. DTO(Data Transfer Object)

 

 - DTO란 계층간 데이터 전송을 위해 사용하는 객체이다. 이때 DTO는 수정(setter), 조회(getter)의 기능만 가지기 때문에

오직 setter, getter 메소드만 정의하고 나머지 로직은 쓰지 않는다.

 

이렇게 정의하는 이유는 앞서 말했듯이 의존성을 줄이고 유지 보수관리를 편하게 하기 위해서이다.

 

게시판을 관리하는 테이블의 속성 값이 [ title, writer_id, content, files, regDate]가 있다면 DTO객체를 다음과 같이 만든다.

package com.ko.app.entity;

import java.util.Date;

public class Notice {

	private String title ;
	private String writer_id;
	private String content;
	private String files;
	private Date regDate;
	
	
	public Notice() { 
		
	}
	public Notice(String title, String writer_id, String content, String files, Date regDate) {
		
		this.title = title;
		this.writer_id = writer_id;
		this.content = content;
		this.files = files;
		this.regDate = regDate;
		
	}


	public String getTitle() {
		return title;
	}


	public void setTitle(String title) {
		this.title = title;
	}


	public String getWriter_id() {
		return writer_id;
	}


	public void setWriter_id(String writer_id) {
		this.writer_id = writer_id;
	}


	public String getContent() {
		return content;
	}


	public void setContent(String content) {
		this.content = content;
	}


	public String getFiles() {
		return files;
	}


	public void setFiles(String files) {
		this.files = files;
	}


	public Date getRegDate() {
		return regDate;
	}


	public void setRegDate(Date regDate) {
		this.regDate = regDate;
	}

	
}

 

 

2. DAO(Data Access Object)

-DAO는 데이터베이스 접근을 위한 객체로, 데이터베이스 연결, 쿼리 실행, 결과 처리 등의 역할을 수행합니다. 즉, DTO를 통해서 데이터를 얻고 이를 이용하여 원하는 기능의 로직을 짠다.

 

다음은 DTO객체를 인자로 받아서 게시판을 등록하는 기능을 짠 것이다.

package com.ko.app.service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ko.app.entity.Notice;

public class NoticeService {
	
	String driver = "com.mysql.cj.jdbc.Driver";
	String url = "jdbc:mysql://localhost:3306/jsp";
	String user = "test";
	String password = "1234";
	
	public int insert(Notice notice) throws ClassNotFoundException, SQLException {
		
		String title = notice.getTitle();
		String writer_id =  notice.getWriter_id();
		String content =  notice.getContent();
		String files = notice.getFiles();
		Date regDate = notice.getRegDate();
		
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = simpleDateFormat.format(regDate);
        java.sql.Date sql_regDate = java.sql.Date.valueOf(formattedDate);
		
        String sql = "INSERT INTO NOTICE(TITLE, WRITER_ID, CONTENT,FILES, REGDATE) VALUES(?,?,?,?,?)";
		
		Class.forName(driver);
		
		Connection con = DriverManager.getConnection(url, user,password);
		
		PreparedStatement st = con.prepareStatement(sql);
		
		st.setString(1, title);
		st.setString(2, writer_id);
		st.setString(3, content);
		st.setString(4, files);
		st.setDate(5, sql_regDate);
		
		int result = st.executeUpdate();
		
		st.close();
		con.close();
		
		return result;
	}
	
}

 

 

메인에서 실행한 결과

package ex01;

import java.sql.SQLException;
import java.util.Date;

import com.ko.app.entity.Notice;
import com.ko.app.service.NoticeService;

public class Main {

	
	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		String title = "제목";
		String writer_id = "001";
		String content = "안녕";
		String files = "이미지";
		Date regDate = new Date();
		
		Notice board = new Notice(title, writer_id, content, files, regDate); 
		
		
		NoticeService service = new NoticeService();
		
		int result = service.insert(board);
		}
}

 

기능이 1개이고 단순해서 코드를 굳이 저렇게 써야할까 싶지만 나중에 큰 프로젝트를 하면 체계적인 관리가 필요하기 때문에 서로 역할을 구분하고 관리한다고 생각하면 될 듯 싶다.

 

 

 

3. VO (Value Object)

 

 마지막으로 VO는 데이터 전송을 위한 객체가 아니고 값만을 표시하는 객체로 불변성을 가진다(외부에서 수정 불가능). VO는 외부에서 값을 변경 할 수 없기 때문에 안정성을 보장한다. 사용하는 예로, 임의로 수정이 불가능한 계좌정보를 객체로 만들 때 쓴다고 한다.  

 

 

(참고영상:https://www.youtube.com/@newlec1)

 

뉴렉처

"유료" 온라인 강의 사이트 뉴렉처에서 제공하는 프로그래밍 강의 채널입니다. 교육서비스 : (10월 새롭게 오픈될 예정입니다.) https://www.newlecture.com 교재: https://javaweb.tistory.com https://answeris.tistory.

www.youtube.com