[Spring] 스프링 DB 1편 - 데이터 접근 핵심 원리 섹션1 JDBC 이해
◼️ JDBC 이해
각 데이터베이스마다 사용법이 달라 JDBC 자바 표준이 등장했다. 자바는 표준 인터페이스를 정의하고, 개발자는 표준 인터페이스만 학습 후 개발하면된다.
🪄 참고 - 표준화의 한계
JDBC의 등장으로 많은 것이 편리해졌지만, 각각의 데이터베이스마다 SQL, 데이터타입 등의 일부 사용법이 다르다. 결국 데이터베이스를 변경하면 JDBC 코드는 변경하지 않아도 되지만 SQL은 해당 데이터베이스에 맞도록 변경 해야한다. 참고로 JPA(Java Persistence API)를 사용하면 이렇게 각각의 데이터베이스마다 다른 SQL을 정의해야 하는 문제도 많은 부분 해결할 수 있다.
◼️ JDBC와 최신 데이터 접근 기술
JDBC를 편리하게 사용하는 다양한 기술이 존재하는데, 대표적으로 SQL Mapper와 ORM 기술로 나눈다.
(이 기술들은 내부에서는 모두 JDBC를 사용한다. )
SQL Mapper | ORM 기술 |
장점: JDBC를 편리하게 사용하도록 도와준다. SQL 응답 결과를 객체로 편리하게 변환해준다. JDBC의 반복 코드를 제거해준다. 단점: 개발자가 SQL을 직접 작성해야한다. 대표 기술: 스프링 JdbcTemplate, MyBatis |
객체를 관계형 데이터베이스 테이블과 매핑해주는 기술. 반복적인 SQL을 직접 작성하지 않고, ORM 기술이 SQL을 동적으로 만들어 실행해준다. 대표 기술: JPA, 하이버네이트, 이클립스링크 JPA는 자바 진영의 ORM 표준 인터페이스이고, 이것을 구현한 것으로 하이버네이트와 이클립스 링크 등의 구현 기술이 있다. |
◼️ JDBC DriverManager 연결 이해
1. 애플리케이션 로직에서 커넥션이 필요하면 DriverManager.getConnection() 을 호출한다.
2. DriverManager 는 라이브러리에 등록된 드라이버 목록을 자동으로 인식한다. 이 드라이버들에게 순서대로 다 음 정보를 넘겨서 커넥션을 획득할 수 있는지 확인한다.
- URL: 예) jdbc:h2:tcp://localhost/~/test
- 이름, 비밀번호 등 접속에 필요한 추가 정보
- 여기서 각각의 드라이버는 URL 정보를 체크해서 본인이 처리할 수 있는 요청인지 확인한다. 예를 들어서 URL이 jdbc:h2 로 시작하면 이것은 h2 데이터베이스에 접근하기 위한 규칙이다. 따라서 H2 드라이버는 본인이 처리할 수 있으므로 실제 데이터베이스에 연결해서 커넥션을 획득하고 이 커넥션을 클라이언트에 반환한다. 반면에 URL이 jdbc:h2 로 시작했는데 MySQL 드라이버가 먼저 실행되면 이 경우 본인이 처리 할 수 없다는 결과를 반환하게 되고, 다음 드라이버에게 순서가 넘어간다.
3. 이렇게 찾은 커넥션 구현체가 클라이언트에 반환된다.
◼️ JDBC 개발
데이터를 변경할 때는 executeUpdate() 를 사용하지만, 데이터를 조회할 때는 executeQuery() 를 사용한다. executeQuery() 는 결과를 ResultSet 에 담아서 반환한다.
🟢ResultSet
- rs.next() : 호출하면 커서를 다음으로 이동. 참고로 최초의 커서는 데이터를 가리키고 있지 않기 때문에 rs.next() 를 최초 한번은 호출해야 데이터를 조회할 수 있다.
- rs.next() 의 결과가 false 면 더이상 커서가 가리키는 데이터가 없다는 뜻이다.
🔶JDBC 사용 실습
@Slf4j
public class DBConnectionUtil {
public static Connection getConnection() {
try{
Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
log.info("get connection={}, class={}",connection, connection.getClass());
return connection;
}catch (SQLException e){
throw new IllegalArgumentException(e);
}
}
}
/**
* JDBC - DriverManager 사용
*/
@Slf4j
public class MemberRepositoryV0 {
public Member save(Member member) throws SQLException {
String sql = "insert into member(member_id, money) values(?, ?)";
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getConnection();
pstmt = con.prepareStatement(sql);
pstmt.setString(1, member.getMemberId());
pstmt.setInt(2, member.getMoney());
pstmt.executeUpdate();
return member;
} catch (SQLException e) {
log.error("db error", e);
throw e;
} finally {
close(con, pstmt, null);
}
}
private void close(Connection con, Statement stmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.info("error", e);
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
log.info("error", e);
}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) {
log.info("error", e);
}
}
}
private Connection getConnection() {
return DBConnectionUtil.getConnection();
}
public Member findById(String memberId) throws SQLException {
String sql = "select * from member where member_id = ?";
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = getConnection();
pstmt = con.prepareStatement(sql);
pstmt.setString(1, memberId);
rs = pstmt.executeQuery();
if (rs.next()) {
Member member = new Member();
member.setMemberId(rs.getString("member_id"));
member.setMoney(rs.getInt("money"));
return member;
} else {
throw new NoSuchElementException("member not found memberId=" + memberId);
}
} catch (SQLException e) {
log.error("db error", e);
throw e;
} finally {
close(con, pstmt, rs);
}
}
public void update(String memberId, int money) throws SQLException {
String sql = "update member set money=? where member_id=?";
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getConnection();
pstmt = con.prepareStatement(sql);
pstmt.setInt(1, money);
pstmt.setString(2, memberId);
int resultSize = pstmt.executeUpdate();
log.info("resultSize={}", resultSize);
} catch (SQLException e) {
log.error("db error", e);
throw e;
} finally {
close(con, pstmt, null);
}
}
public void delete(String memberId) throws SQLException {
String sql = "delete from member where member_id=?";
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getConnection();
pstmt = con.prepareStatement(sql);
pstmt.setString(1, memberId);
pstmt.executeUpdate();
} catch (SQLException e) {
log.error("db error", e);
throw e;
} finally {
close(con, pstmt, null);
}
}
}
'Spring' 카테고리의 다른 글
[Spring] 스프링 DB 1편 - 데이터 접근 핵심 원리 섹션3 트랜잭션 이해 (0) | 2024.06.02 |
---|---|
[Spring] 스프링 DB 1편 - 데이터 접근 핵심 원리 섹션2 커넥션풀과 데이터소스 이해 (0) | 2024.05.29 |
[Spring] 스프링 MVC 2편 - 백엔드 웹 개발 활용 기술 섹션11 스프링 파일 업로드 (0) | 2024.05.21 |
[Spring] Spring Type Conversion 문서 정리 및 요약 (0) | 2024.05.18 |
[Spring] 스프링 MVC 2편 - 백엔드 웹 개발 활용 기술 섹션10 스프링 타입 컨버터 (0) | 2024.05.18 |