코딩왕랄프👊🏻

[Spring] DAO, DTO 본문

카테고리 없음

[Spring] DAO, DTO

hyerm_2 2021. 7. 30. 13:25
반응형
SMALL
DAO?

Data Access Object

데이타베이스를 사용해 데이터를 조회, 조작하는 기능
사용자는 자신이 필요한 인터페이스를 DAO에게, DAO는 이 인터페이스를 통해 구현한 객체를사용자에게 전달

 

 

 

 

DTO?

Data Transfer Object = VO (Value Object)
계층 간 데이타 전송을 위한 자바 Beans
Form Data bean, Database Table bean이 있으며 각 데이터를 Mapping 하기 위한 데이터 객체


 

DAO 클래스 예제

=> DB와 연결할 Connection 가져오기

=> DB, Drive, Login 정보

=> 작업이 끝나면 사용한 Resource를 시스템에 돌려줌

package com.walab.java;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class roleDAO {
	private static String dburl = "jdbc:mysql://sql6.freemysqlhosting.net:3306/sql6427042";
	private static String dbUser = "sql6427042";
	private static String dbpasswd = "8he56Rfa7J";

	public Role getRole(Integer role_id) {
		Role role = null;
		Connection conn = null;
        PreparedStatement ps = null;
		ResultSet rs = null;
		
		try {
        	// 1. DBMS에 맞게 Driver를 로드.
			Class.forName("com.mysql.jdbc.Driver");

			// 2. java SQL 패키지의 DriverMager를 통해서 DBMS에 연결
			conn = DriverManager.getConnection(dburl, dbUser, dbpasswd);

			// 3.Sql 쿼리 String 생성
			String query = "SELECT description,role_id FROM role WHERE role_id = ?";

			// 4.DB에 Sql 쿼리 전달 하기 위한 객체 생성
			ps = conn.prepareStatement(query);

			//   3에서 ?에 대한 설정   , 1번째 ?로 에 값을 설정
			ps.setInt(1, role_id);

			// 5. 쿼리 실행 및 결과 얻기
			rs = ps.executeQuery();


			// 결과 값 빼내기 nex()함수의 결과 첫번재 컬럼을 빼난다.
			if (rs.next()) {
				// index로 뽑는 방법
				String description = rs.getString(1);

				// Column명으로 뽑는 방법
				int id = rs.getInt("role_id");
                
				role = new Role(description, id);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			if (ps != null) {
				try {
					ps.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return role;
	}
}

 

 

DTO 클래스 예제

=> 데이터를 받고 전달

package com.walab.java;
public class RoleDTO {
	String description;
	int role_id;
	
	
	public RoleDTO(String description, int role_id) {
		super();
		this.description = description;
		this.role_id = role_id;
	}
	
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public int getRole_id() {
		return role_id;
	}
	public void setRole_id(int role_id) {
		this.role_id = role_id;
	}

}

 

 

참고

https://gmlwjd9405.github.io/2018/05/15/setting-for-db-programming.html

반응형
LIST