Back-end/Java&Spring

Spring JDBC(1) - JDBC 이해

guwon2 2024. 9. 11. 16:50

프로젝트를 진행하면서는 대부분 ORM 기술인 JPA를 사용했고, Spring을 처음 공부할때는 잠깐 JDBC Template을 사용해서 과제를 진행한 적이 있었지만 JDBC API의 제대로 된 동작 과정과 JDBC만을 쓰는 코드는 공부해 본 적은 없는 것 같아 이번 기회에 공부를 해 보기로 했다.

JDBC 

JDBC(Java Database Connectivity)는 자바에서 데이터베이스에 접속할 수 있도록 하는 자바 API. JDBC

는 데이터베이스에서 자료를 쿼리하거나 업데이트하는 방법을 제공한다. - 위키백과

 

위키백과에 나와있는 것 처럼 JDBC는 

 

1. 데이터베이스마다 사용 방법이 모두 다르다는 문제 (데이터베이스를 바꾼다면 개발자가 그 방법들을 새로 학습해야 함)

2. 데이터베이스를 바꿀때 마다 프로덕션 코드도 같이 변경해야한다는 문제

 

를 해결해 주었다.

 

 

JDBC를 이용한 데이터베이스 연결

 

JDBCjava.sql.Connection`표준 커넥션 인터페이스를 정의한다.

 

package com.example.jdbc.connection;

import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import static com.example.jdbc.connection.ConnectionConst.*;

@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 IllegalStateException(e);
        }
    }
}

 

프린터를 사용할 때 각 프린터에 맞는 드라이버를 설치해야 사용할 수 있는 것 처럼

데이터베이스를 사용할 때도 각 데이터베이스의 드라이버를 통해 커넥션을 제공받아야 한다.

JDBC의 DriverManager 는 이런 DB 드라이버들을 관리하고, 커넥션을 획득하는 기능을 한다.

 

JDBC 개발

 

DriverManager을 통해 데이터베이스에 접근할 CRUD 코드를 작성해보면

package com.example.jdbc.repository;

import com.example.jdbc.connection.DBConnectionUtil;
import com.example.jdbc.domain.Member;
import lombok.extern.slf4j.Slf4j;

import java.sql.*;
import java.util.NoSuchElementException;


@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);
            }
        }
    }

    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);
        }
    }


    private Connection getConnection() {
        return DBConnectionUtil.getConnection();
    }
}

 

이러한 코드가 완성된다. 

 

만들어둔 DBConnectionUtil을 통해 getConnection 메서드로 커넥션을 획득하고

 

sql문을 con.prepareStatement()를 통해 준비하고, pstmt.executeUpdate()를 통해 전달을 해주면 된다.

조회는 executeQuery()를 사용한다.

 

 

출처

김영한 - Spring DB 1

 

https://kokodakadokok.tistory.com/entry/JDBC-DB-%EC%A0%91%EA%B7%BC%EC%9D%84-%EC%9C%84%ED%95%9C-%EC%9E%90%EB%B0%94-%ED%91%9C%EC%A4%80-%EC%9D%B8%ED%84%B0%ED%8E%98%EC%9D%B4%EC%8A%A4