ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 1.2.2 커넥션 만들기의 추출
    책/토비의 스프링 2024. 7. 7. 14:11

    책을 읽고 흘려버리기 보단, 꼭꼭 씹어먹기 위해 정리해봅니다.

    이 포스팅은 이일민님의 <토비의 스프링3>에 기반하고 있습니다.


     

    1. 문제의 상황

    데이터베이스 커넥션에 관련된 내용이 모든 메소드에 반복되고 있다.

    변경이 필요할 경우 모든 메소드를 변경해야하는 문제가 있다.

     

     

    1. 개선 전

    메소드 add, get, deleteAll 모두 데이터베이스 커넥션에 대한 관심사가 포함되어 있다.

    더보기
    public class UserDao {
      public void add(User user) throws SQLException, ClassNotFoundException {
        Class.forName("com.mysql.jdbc.Driver");
        Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/springbook", "root", "12345678");
    
        PreparedStatement ps = c.prepareStatement("insert into users (id, name, password) values (?, ?, ?)");
        ps.setString(1, user.getId());
        ps.setString(2, user.getName());
        ps.setString(3, user.getPassword());
    
        ps.executeUpdate();
    
        ps.close();
        c.close();
      }
    
      public User get(String userId) throws SQLException, ClassNotFoundException {
        Class.forName("com.mysql.jdbc.Driver");
        Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/springbook", "root", "12345678");
    
        PreparedStatement ps = c.prepareStatement("select * from users where id = ?");
        ps.setString(1, userId);
        ResultSet rs = ps.executeQuery();
        rs.next();
    
        User user = new User();
        user.setId(rs.getString("id"));
        user.setName(rs.getString("name"));
        user.setPassword(rs.getString("password"));
    
        rs.close();
        ps.close();
        c.close();
    
        return user;
      }
    
      public void deleteAll() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/springbook", "root", "12345678");
    
        PreparedStatement ps = c.prepareStatement("delete from users");
        ps.executeUpdate();
    
        ps.close();
        c.close();
      }
    }

     

     

    2. 공통의 메소드를 사용한 관심사 분리

    '데이터베이스 연결' 이라는 관심사를 분리한 getConnection 메소드를 생성

    데이터베이스 연결 관련된 내용이 수정되어야한다면 getConnection만 수정하면된다.

    더보기
    public class UserDao {
      public void add(User user) throws SQLException, ClassNotFoundException {
        Connection c = getConnection();
    
        PreparedStatement ps = c.prepareStatement("insert into users (id, name, password) values (?, ?, ?)");
        ps.setString(1, user.getId());
        ps.setString(2, user.getName());
        ps.setString(3, user.getPassword());
    
        ps.executeUpdate();
    
        ps.close();
        c.close();
      }
    
      public User get(String userId) throws SQLException, ClassNotFoundException {
        Connection c = getConnection();
    
        PreparedStatement ps = c.prepareStatement("select * from users where id = ?");
        ps.setString(1, userId);
        ResultSet rs = ps.executeQuery();
        rs.next();
    
        User user = new User();
        user.setId(rs.getString("id"));
        user.setName(rs.getString("name"));
        user.setPassword(rs.getString("password"));
    
        rs.close();
        ps.close();
        c.close();
    
        return user;
      }
    
      public void deleteAll() throws ClassNotFoundException, SQLException {
        Connection c = getConnection();
    
        PreparedStatement ps = c.prepareStatement("delete from users");
        ps.executeUpdate();
    
        ps.close();
        c.close();
      }
      
      public Connection getConnection() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/springbook", "root", "12345678");
        
        return c;
      }
    }
    

     

     

    
    public class UserDao {
      public void add(User user) throws SQLException, ClassNotFoundException {
        Connection c = getConnection();
    	...
      }
    
      public User get(String userId) throws SQLException, ClassNotFoundException {
        Connection c = getConnection();
    	...
      }
    
      public void deleteAll() throws ClassNotFoundException, SQLException {
        Connection c = getConnection();
    	...
      }
    
      public Connection getConnection() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/springbook", "root", "12345678");
    
        return c;
      }
    }

     

     


    [출처]

    이일민님의 <토비의 스프링3>

    [이미지 출처]

    https://m.yes24.com/Goods/Detail/4020006

    ' > 토비의 스프링' 카테고리의 다른 글

    1.4.1 오브젝트 팩토리  (0) 2024.07.08
    1.3.3 관계설정 책임의 분리  (0) 2024.07.07
    1.3.1 클래스의 분리  (0) 2024.07.07
    1.2.3 DB 커넥션 만들기의 독립  (0) 2024.07.07
    1.1 초난감 DAO  (0) 2024.07.07
Designed by Tistory.