ecsimsw

JDBC / DAO, DTO 본문

JDBC / DAO, DTO

JinHwan Kim 2020. 5. 17. 21:31

이전 코드 

 

  이전에 Statement로 sql을 적용시키고, 같은 명령을 값만 바꿔서 더 빠르게 처리하기 위해서 PreparedStatement를 사용해서 아래 코드로 insert와 select를 만들었다.

 

  그런데도 그 코드는 다른 기능과 함께 사용하려면 아마 함수나 객체로 만들어 처리하는게 더 가시적이고 편할 것이다.

 

  즉 데이터베이스의 CRUD를 모듈화 한 것이 DAO이다. 

try{
    Class.forName("com.mysql.jdbc.Driver");
    String url ="jdbc:mysql://localhost:3306/hellojdbc?serverTimezone=UTC";
    conn = DriverManager.getConnection(url, "root", "root");
    System.out.println("연결 성공");

    Statement stat=conn.createStatement();
    
    String sql = "insert into logininfo (id, pw) values (?,?)";
    PreparedStatement pstat = conn.prepareStatement(sql);
    pstat.setString(1,"id123");
    pstat.setString(2,"pw123");
    pstat.executeUpdate();
    
    sql = "select * FROM logininfo WHERE id= (?)";
    pstat = conn.prepareStatement(sql);
    pstat.setString(1, "admin");
    rs =pstat.executeQuery();
    
    while(rs.next()) {
        String id =rs.getString("id");
        String pw =rs.getString("pw");
        System.out.println(id+" "+pw);
    }
    rs.close();
   
}
catch(ClassNotFoundException e){
    System.out.println(e+"드라이버 로딩 실패");
}
catch(SQLException e){
    System.out.println("에러: " + e);
}
finally{
    try{
        if( conn != null && !conn.isClosed()){
            conn.close();
        }
    }
    catch( SQLException e){
        e.printStackTrace();
    }
}


DAO / Data Access Object

 

  db 연결과 쿼리 적용을 위한 객체를 만들었다. 

 

  생성 시, db와 연결하고, 기능에 따라 sql을 적용한다.

 

  이런 모듈화로 servlet에서 사용하기도 편하고, 데이터베이스를 다루는 코드 자체도 관리가 편해질 것이다.  

public class AccountDAO {
   	Connection conn = null;
	
   	public AccountDAO(){
           Class.forName("com.mysql.cj.jdbc.Driver");
           String url ="jdbc:mysql://localhost:3306/hellojdbc?serverTimezone=UTC";
           conn = DriverManager.getConnection(url, "root", "root");
	}
	
	public int insertAccount(String newId, String newPw) {
	   String sql = "insert into logininfo (id, pw) values (?,?)";
           PreparedStatement pstat = null;
	   int result = 0;
       
	   pstat = conn.prepareStatement(sql);
	   pstat.setString(1,newId);
	   pstat.setString(2,newPw);

	   result = pstat.executeUpdate();
	 
	   if( conn != null) conn.close();
	   if( pstat != null) pstat.close();
        
           return result;
       }
}

  다만 insert를 위해선 해당 새로운 데이터의 컬럼(newId, newPw)를 파라미터로 입력해줘야한다.  

 

  또 select를 구현하다고 치면, 해당 데이터의 컬럼 목록을 다 포함할 수 있는 배열의 list를 반환하도록 해야할 것이다.

 

  그냥 데이터베이스의 컬럼을 변수로 갖는 클래스를 만들어 관리하면 어떨까. 객체 자체가 마치 하나의 데이터처럼 사용되는 것이다.

 

 

DTO / Data Transfer Obejct

 

  데이터베이스의 자료를 자바에서 쓸 수 있도록 전환해주는 클래스를 정의한다. 

 

  데이터베이스를 구성하는 칼럼을 변수로 갖고, getter와 setter로 자료를 저장하고 가져온다.

public class AccountDTO {
	
	int no;
	String id = null;
	String pw = null;

	public AccountDTO(int no, String id, String pw) {
		this.no = no;
		this.id = id;
		this.pw = pw;
	}

	public int getNo() {
		return no;
	}

	public String getId() {
		return id;
	}

	public String getPw() {
		return pw;
	}
}

 

 

전체 코드

 

AccountDAO

public class AccountDAO {
   	Connection conn = null;
	
   	public AccountDAO(){
	   try{
             Class.forName("com.mysql.cj.jdbc.Driver");
             String url ="jdbc:mysql://localhost:3306/hellojdbc?serverTimezone=UTC";
             conn = DriverManager.getConnection(url, "root", "root");
	   }
	   catch(Exception e) {
	      e.printStackTrace();
	      System.out.println(e);
	   }
	}
	
	public int insertAccount(AccountDTO accountDTO) {
	   String sql = "insert into logininfo (id, pw) values (?,?)";
           PreparedStatement pstat = null;
	   int result = 0;
        
           try {
	      pstat = conn.prepareStatement(sql);
	      pstat.setString(1,accountDTO.getId());
	      pstat.setString(2,accountDTO.getPw());

	      result = pstat.executeUpdate();
	   }
           catch (SQLException e) {
	      e.printStackTrace();
	   }
           finally {
	      try {
	         if( conn != null) conn.close();
	         if( pstat != null) pstat.close();
	      } catch (SQLException e) {
	         e.printStackTrace();
	      }
	   }
        
        return result;
       }
	
       public ArrayList<AccountDTO> selectAccount(){
	   ArrayList<AccountDTO> resultSet = new ArrayList<>();
		
	   String sql = "select * FROM logininfo";
           PreparedStatement pstat = null;
           ResultSet rs = null;
       
	   try {
	      pstat = conn.prepareStatement(sql);
              rs =pstat.executeQuery();
		        
	      while(rs.next()) {
	         int no = rs.getInt("no");
	         String id =rs.getString("id");
	         String pw =rs.getString("pw");
	            
	         resultSet.add(new AccountDTO(no,id,pw));
	      }	    
	  } 
	  catch (SQLException e) {
	      e.printStackTrace();
	  } 
	  finally {
	    try {
	        if( rs != null) rs.close();
	        if( conn != null) conn.close();
	        if( pstat != null) pstat.close();
	    } catch (SQLException e) {
	        e.printStackTrace();
	   }
	}
     
	return resultSet;
   }
}

 

AccountDTO

public class AccountDTO {	
	int no;
	String id = null;
	String pw = null;
	
	
	public AccountDTO(String id, String pw) {
		this.id = id;
		this.pw = pw;
	}

	public AccountDTO(int no, String id, String pw) {
		this.no = no;
		this.id = id;
		this.pw = pw;
	}

	public int getNo() {
		return no;
	}

	public void setNo(int no) {
		this.no = no;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getPw() {
		return pw;
	}

	public void setPw(String pw) {
		this.pw = pw;
	}
	
	
}

 

ServletEX

@WebServlet("/login")
public class ServletEX extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		AccountDAO accountDAO = new AccountDAO();
		
		AccountDTO newData = new AccountDTO(0, "newID", "newPW");
		accountDAO.insertAccount(newData);
		
		accountDAO = new AccountDAO();
		
		ArrayList<AccountDTO> sellected = accountDAO.selectAccount();
		for(AccountDTO tempDTO : sellected) {
			System.out.println(tempDTO.getId() + tempDTO.getPw());
		}
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
Comments