728x90
반응형
JDBC 프로그래밍의 단점을 보완하는 스프링
JDBC API를 이용하면 DB 연동에 필요한 Connection을 구한 다음 쿼리를 실행하기 위한 PreparedStatement를 생성합니다. 그리고 쿼리를 실행한 뒤에는 finally 블록에서 ResultSet, PreparedStatement, Connection을 닫습니다.
JDBC API를 이용한 DB 연동 코드 구조
Member member;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/spring5fs", "spring5", "spring5");
...
} catch (SQLException e) {
e.printStackTrace()[
throw e;
} finally {
if(rs != null)
try { rs.close(); } catch (SQLException e2){}
if(pstmt != null)
try { pstmt.close(); } catch (SQLException e1){}
if(conn != null)
try { conn.close(); } catch (SQLException e){}
}
여기서 문제는 catch 문 이하입니다. 위의 코드는 JDBC 프로그래밍을 할 때 구조적으로 반복될 수밖에 없습니다.
이러한 구조적인 반복을 줄이기 위해 템플릿 메서드 패턴과 전략 패턴을 함께 사용해야합니다. 스프링은 바로 이 두 패턴을 엮은 JdbcTemplate 클래스를 제공합니다.
JdbcTemplate 클래스를 사용하여 DB 연동
List<Member> results = jdbcTemplate.qurey(
"select * from MEMBER where EMAIL = ?",
new RowMapper<Member>(){
@Override
public Member mapRow(ResultSet rs, int rowNum) throws SQLException{
Member member = new Member(rs.getString("EMAIL"),
rs.getString("PASSWORD"),
..
);
member.setId(rs.getLong("ID"));
return member;
}
}, email);
return result.isEmpty() ? null : results.get(0);
위 코드를 람다식으로 표현
List<Member> results = jdbcTemplate.qurey(
"select * from MEMBER where EMAIL = ?",
(ResultSet rs, int rowNum) -> {
Member member = new Member(rs.getString("EMAIL"),
...
);
member.setId(rs.getLong("ID"));
return member;
}, email);
return results.isEmpty() ? null : results.get(0);
위와 같이 스프링은 JdbcTemplate를 통해 DB 연동을 제공합니다. 스프링이 제공하는 또 하나의 장점은 트랜잭션 관리가 쉽습니다.
JDBC API로 트랜잭션을 처리하면 Connection의 setAUtoCommit(false)을 이용해서 자동커밋을 비활성화하고, commit()과 rollback() 메서드를 이용해서 트랜잭션을 커밋하거나 롤백해야 합니다.
스프링을 사용하면 트랜잭션을 적용하고 싶은 메서드에 @Transactional 만 붙여주면 됩니다.
@Transactional
public void insert(Member member){
...
}
커밋과 롤백처리는 스프링이 알아서 처리하므로 개발자는 트랜잭션 처리를 제외한 핵심 코드에만 집중해서 작성하면 됩니다.
728x90
반응형
'Spring' 카테고리의 다른 글
[Spring] Spring DB 연동 - Tomcat JDBC의 프로퍼티 (0) | 2024.02.18 |
---|---|
[Spring] Spring JDBC - DB 연결해보기 (1) | 2024.02.17 |
[Spring] Spring AOP - @Around의 Pointcut 설정과 @Pointcut 재사용 (0) | 2024.02.16 |
[Spring] Spring AOP - Advice 적용순서 (0) | 2024.02.14 |
[Spring] AOP - execution 명시자 표현식 (0) | 2024.02.05 |