티스토리 뷰

Context는 '맥락'이라는 뜻 입니다. 여기에서 context는 JDBC를 이용해 DB를 업데이트 한다는 변하지 않는 맥락이 있습니다.

 

맥락은 스타벅스에서 커피를 주문 하는 것과 비유를 해보면

1.고객은 스타벅스 직원에게 메뉴들을 주문하고

2.직원은 전체 얼마인지 계산을 해서 고객에게 알려주고

3.고객은 결제를 하고

4.주문한 메뉴들이 만들어 지면 받아가는 맥락입니다.

 

여기에서 핵심 메소드는 executeSql입니다. executeSql은 Sql문을 받아서 실행을 해주는 역할을 하고 있습니다.

public class JdbcContext

JdbcContext클래스는 DataSource를 외부에서 받아주는 기능이 있고 executeSql은 workWithStatementStrategy에 PreparedStatement를 전달하고 전달 받은 preparedStatement를 workWithStatementStrategy는 실행 하는 방식 입니다.

 

이 작업은 '맥락'으로서 update를 실행 할 때는 바뀌지 않는 작업 입니다.

 

토비의스프링3 3장 Template Callback 내용까지 적용하면 만들 수 있는 클래스 입니다.

 

Spring안에는 JdbcContext가 이미 구현 되어 있지만 구현하는 과정을 통해 스프링에 대해 배울 수 있습니다.

package dao;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JdbcContext {
    private DataSource dataSource;

    public JdbcContext(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public void executeSql(String query) throws SQLException {
        this.workWithStatementStrategy(new StatementStrategy() {
            @Override
            public PreparedStatement makePreparedStatement(Connection c) throws SQLException {
                PreparedStatement ps = c.prepareStatement(query);
                return ps;
            }
        });
    }
    public void workWithStatementStrategy(StatementStrategy stmt) throws SQLException {

        Connection c = null;
        PreparedStatement ps = null;
        try {
            c = this.dataSource.getConnection();
            ps = stmt.makePreparedStatement(c);
            ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            throw throwables;
        } finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (c != null) {
                try {
                    c.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

위 JdbcContext 클래스에서 최종 실행하는 method는 executeSql()입니다. dataSource를 di받아서 Connection을 생성하고 workWithStatementStrategy는 preparedStatement를 실행해주는 역할을 합니다.

 

public void delete(int id) throws SQLException {
	this.jdbcContext.executeSql("delete from car_model where id="+id);
}

실행 할 때는 CarModelDao의 delete()메소드에서 query만 만들어주면 실행은 위에 JdbcContext.executeSql()이 쿼리를 실행 해줍니다.

 

executeSql은 workWithStatementStrategy()를 실행 하는데요 workWthStatementStrategy는 인터페이스 StatementStrage의 구현체를 받아서 preparedStatement를 만들고 쿼리를 실행 합니다.

 

end.

 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함