Spring 입문 (JPA 기초)

KimGwangmin·2026년 9월 7일

JDBC (Java Database Connectivity)

  • 자바에서 직접 SQL을 실행해 DB와 통신하는 저수준 API
  • SQL 중심
// JDBC
public class UserDaoJdbc {

    public User findByName(String name) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        User user = null;

        try {
            conn = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/hello", "user", "password");

            String sql = "SELECT id, name, email, age FROM users WHERE name = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, name);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                user = new User();
                user.setId(rs.getLong("id"));
                user.setName(rs.getString("name"));
                user.setEmail(rs.getString("email"));
                user.setAge(rs.getInt("age"));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) rs.close();
                if (pstmt != null) pstmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return user;
    }
}

JPA (Java Persistence API)

  • ORM
  • 객체 중심
  • 내부적으로 JDBC 사용
public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByName(String name);
}

  • Spring Data JPA: JPA를 편하게 사용할 수 있게 해주는 라이브러리
  • Hibernate: JPA 인터페이스의 구현체, 다양한 DB와 통신할 수 있음 (Dialect)

0개의 댓글