
Published on September 07, 2021 by Eunbi.N
Spring Toby
JDBC try/catch/finally 코드의 문제점
분리와 재사용을 위한 디자인패턴
DB커넥션 가져오기
DI 적용을 위한 클라이언트/컨텍스트 분리
// 메소드로 분리한 컨텍스트 코드
public void jdbcContextWithStatementStrategy(StatementStrategy stmt) throws SQLException {
Connection c = null;
PreparedStatement ps = null;
try{
c = dataSource.getConnection();
ps = stmt.makePreparedStatement(c);
ps.executeUpdate();
}catch (SQLException e){
throw e;
} finally{
if(ps !=null){
try {
ps.close();
}catch(SQLException e) {}
}
if(c !=null){
try {
c.close();
}catch(SQLException e) {}
}
}
}
// 클라이언트 담당 메소드
public void deleteAll() throws SQLException {
StatementStrategy st = new DeleteAllStatement(); // 전략 클래스의 Obj 생성
jdbcContextWithStatementStrategy(st); // 컨텍스트 호출. StatementStrategy 전달
}