야나도 프로젝트

나도 개발자 될수있어

JAVA

JDBC Programming - DAO (Data Access Object)

jmeen 2021. 8. 11. 16:07
728x90

DAO (Data Access Object)

개념

DAO (Data Access Object)

- DB를 사용하여 데이터를 조회하거나 조작하는 기능을 전담하도록 만든 오브젝트(트랜잭션 객체)

- 주요 로직에서 Database를 접속, 질의를 수행하고 결과를 반환하는 로직을 DAO에 위임하도록 구현

- Domain Logic으로부터 Persistence Machanism을 숨기기 위해 사용

  - 적절히 디자인을 하면 모든 Domain Logic을 바꾸는 대신 DAO를 바꾸기만 하면 된다.

  - 사용자는 자신이 필요한 Interface를 DAO에 던지고 DAO는 이 인터페이스를 구현한 객체를 사용자에게 반환 

DTO(Data Transfer Object)

- 계층간 데이터 교환을 위한 자바빈즈
- 컨트롤러, 뷰, 비즈니스 계층, 퍼시스턴스 계층간 데이터 교환
- VO(Value Object) 패턴이라고도 함
- 일반적으로 DTO는 로직을 갖고 있지 않은 순수 데이터 객체이며 속성과 그 속성에 접근하기 위한 getter, setter 메서드만 가진다.
- 추가적으로 toString(), equals() 등의 Object 클래스 메서드를 작성하기도 한다

 

 

예제

다음의 book, author 테이블에서 DAO 패턴을 연습하는 예제입니다

 

1. 먼저 VO 객체를 생성한다. 일종의 생성자 역할을 한다.

package com.javaex.jdbc.oracle.dao;
// VO객체

// - 처리 로직을 갖지 않느나.
// - 순수 데이터를 가지는 객체
// - 기본 생성자가 있어야 한다.
// - tostring, equals등은 오버라이드 하기도 한다.

public class AuthorVO {
	// 필드 만들기
	// VO객체에서는 기본타입대신 Wrapper 사용
	private long authorId;
	private String authorName;
	private String authorDesc;

	// 생성자 - 기본 생성자가 필요
	public AuthorVO() {

	}

	public AuthorVO(String name, String desc) {
		this.authorName = name;
		this.authorDesc = desc;
	}

	public AuthorVO(long id, String name, String desc) {
		this.authorId = id;
		this.authorName = name;
		this.authorDesc = desc;
	}

	// getter & setter
	public long getAuthorId() {
		return authorId;
	}

	public void setAuthorId(long authorId) {
		this.authorId = authorId;
	}

	public String getAuthorName() {
		return authorName;
	}

	public void setAuthorName(String authorName) {
		this.authorName = authorName;
	}

	public String getAuthorDesc() {
		return authorDesc==null? "" : authorDesc;
	}

	public void setAuthorDesc(String authorDesc) {
		this.authorDesc = authorDesc;
	}
	
	//tostirng
	@Override
	public String toString() {
		return "AuthorVO [authorId=" + authorId + ", authorName=" + authorName + ", authorDesc=" + authorDesc + "]";
	}

}

2. DAO 인터페이스를 생성한다.

package com.javaex.jdbc.oracle.dao;

import java.util.List;

public interface AuthorDAO {
	public List<AuthorVO> getlist(); // 전체 목록

	public List<AuthorVO> serch(String Keyword); // 검색 목록

	public AuthorVO get(long id); // 저자 정보 확인

	public boolean insert(AuthorVO vo); // 삽입

	public boolean update(AuthorVO vo); // 갱신

	public boolean delete(long id); // 삭제

}

4. 인터페이스를 상속받아 실제 수행되는 코드를 적은 클래스를 생성한다.

package com.javaex.jdbc.oracle.dao;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class AuthorDAOimpleOracle implements AuthorDAO {
	// 접속 코드(커넥션)
	private Connection getConnection() throws SQLException {
		Connection conn = null;
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			String dburl = "jdbc:oracle:thin:@127.0.0.1:1521:xe";
			conn = DriverManager.getConnection(dburl, "C##BITUSER", "bituser");

		} catch (ClassNotFoundException e) {
			System.err.println("드라이버 실패");
		}
		return conn;
	}

	@Override
	public List<AuthorVO> getlist() {
		// 전체 목록 불러오기
		List<AuthorVO> list = new ArrayList<>();
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;

		try {
			conn = getConnection();
			stmt = conn.createStatement();

			String sql = "SELECT author_id, author_name, author_desc " + " FROM author ORDER BY author_id";

			rs = stmt.executeQuery(sql);

			while (rs.next()) {
				long authorId = rs.getLong(1);
				String name = rs.getString(2);
				String desc = rs.getString(3);
				AuthorVO vo = new AuthorVO(authorId, name, desc);
				System.out.printf("%d%S%S%n", authorId, name, desc);
				list.add(vo);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				rs.close();
				stmt.close();
				conn.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return list;
	}

	@Override
	public List<AuthorVO> serch(String Keyword) {
		List<AuthorVO> list = new ArrayList<>();
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		try {
			conn = getConnection();
			String sql = "SELECT author_id, author_name, author_desc FROM author WHERE author_name LIKE ?";

			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, "%" + Keyword + "%");
			rs = pstmt.executeQuery();
			// resultset -=> list 변환
			while (rs.next()) {
				Long id = rs.getLong(1);
				String name = rs.getString(2);
				String desc = rs.getString(3);

				AuthorVO vo = new AuthorVO(id, name, desc);
				list.add(vo);

			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				rs.close();
				pstmt.close();
				conn.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return list;
	}

	@Override
	public AuthorVO get(long id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean insert(AuthorVO vo) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		int insertCount = 0;

		try {
			conn = getConnection();
			// 실행계획
			String sql = "INSERT INTO author " + " VALUES(seq_author_id.NEXTVAL,?,?)";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, vo.getAuthorName());
			pstmt.setString(2, vo.getAuthorDesc());

			insertCount = pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return 1 == insertCount;

	}

	@Override
	public boolean update(AuthorVO vo) {

		Connection conn = null;
		PreparedStatement pstmt = null;
		int updatecount = 0;
		try {
			conn = getConnection();
			String sql = "UPDATE author SET author_name = ?,author_desc = ? WHERE author_id = ?";
			
			pstmt=conn.prepareStatement(sql);
			pstmt.setString(1, vo.getAuthorName());
			pstmt.setString(2, vo.getAuthorDesc());
			pstmt.setLong(3, vo.getAuthorId());
			updatecount = pstmt.executeUpdate();

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

		return 1 == updatecount;
	}

	@Override
	public boolean delete(long id) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		int deleteCount = 0;

		try {
			conn = getConnection();
			String sql = "DELETE FROM author WHERE author_id=?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setLong(1, id);
			deleteCount = pstmt.executeUpdate();

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				pstmt.close();
				conn.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return 1 == deleteCount;
	}

}

4. 실행할 main 코드를 작성한다.

package com.javaex.jdbc.oracle.dao;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

public class DAOApp {

	public static void main(String[] args) {

		listAuthors();
//		insertAuthor();
		updateauthor();
//		deleteauthor();
//		searchauthor();
		listAuthors();

	}

	private static void listAuthors() {
		AuthorDAO dao = new AuthorDAOimpleOracle();
//		List<AuthorVO> list = dao.getlist();
//		Iterator<AuthorVO> it = list.iterator();

		List<AuthorVO> list = dao.getlist();
		Iterator<AuthorVO> it = list.iterator();

		while (it.hasNext()) {
			AuthorVO vo = it.next();
			System.out.printf("%d\t%s\t%s%n", vo.getAuthorId(), vo.getAuthorName(), vo.getAuthorDesc());
		}

		System.out.println("----------------------");

	}

	private static void insertAuthor() {
		Scanner sc = new Scanner(System.in);
		System.out.print("이름 >>> ");
		String name = sc.next();
		System.out.print("경력 >>> ");
		String desc = sc.next();
		AuthorVO vo = new AuthorVO(name, desc);
		AuthorDAO dao = new AuthorDAOimpleOracle();

		boolean success = dao.insert(vo);

		System.out.println("Author Insert : " + (success ? "성공" : "실패"));
	}

	private static void updateauthor() {
		Scanner sc = new Scanner(System.in);

		System.out.print("저자번호 >>> ");
		long authorid = sc.nextLong();
		System.out.print("이름 >>> ");
		String name = sc.next();
		System.out.print("경력 >>> ");
		String desc = sc.next();

		AuthorVO vo = new AuthorVO(authorid, name, desc);
		AuthorDAO dao = new AuthorDAOimpleOracle();
		boolean success = dao.update(vo);

		System.out.println("Author Update : " + (success ? "성공" : "실패"));

	}

	private static void deleteauthor() {
		Scanner sc = new Scanner(System.in);
		System.out.print("저자번호 >>> ");
		long authorid = sc.nextLong();

		AuthorDAO dao = new AuthorDAOimpleOracle();

		boolean success = dao.delete(authorid);
		System.out.println("Author delete : " + (success ? "성공" : "실패"));
		sc.close();

	}

	private static void searchauthor() {
		Scanner sc = new Scanner(System.in);
		System.out.print("검색단어 >>> ");
		String Keyword = sc.next();
		
		AuthorDAO dao = new AuthorDAOimpleOracle();
		List<AuthorVO> list = dao.serch(Keyword);
		Iterator<AuthorVO> it = list.iterator();
		
		while(it.hasNext()) {
			AuthorVO vo = it.next();
			System.out.printf("%d %s %s%n",vo.getAuthorId(),vo.getAuthorName(),vo.getAuthorDesc()	 );
		}
		sc.close();

	}

}

 

'JAVA' 카테고리의 다른 글

Servlet & JSP  (0) 2021.08.11
Java Network and Thread  (0) 2021.08.11
JAVA Stream and I/O 보조 스트림 / Scanner  (0) 2021.08.11
JAVA Hash / Java I/O Programming  (0) 2021.08.11
Java Utility API / Geniric / Collection Framework  (0) 2021.08.11