Spring/Spring Data JPA

[자바 ORM 표준 JPA 프로그래밍] 1. JPA 소개

noahkim_ 2023. 11. 28. 00:05

김영한 님의 "자바 ORM 표준 JPA 프로그래밍" 책을 정리한 포스팅 입니다.

 

1. SQL을 직접 다룰 때 발생하는 문제점

Repetition

steps for developing an sql mapper
// JDBC 연결 정보
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";

// 데이터베이스 연결 및 쿼리 실행
try (Connection connection = DriverManager.getConnection(url, username, password)) {
    String sql = "SELECT id, name, email FROM users WHERE id = ?";
    try (PreparedStatement statement = connection.prepareStatement(sql)) {
        statement.setInt(1, 1); // 예시로 id가 1인 사용자 조회
        try (ResultSet resultSet = statement.executeQuery()) {
            if (resultSet.next()) {
                // 결과를 DTO로 매핑
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String email = resultSet.getString("email");

                // DTO 객체 생성
                UserDTO user = new UserDTO(id, name, email); 
                
                // ...
            }
        }
    }
} catch (SQLException e) {
    e.printStackTrace();
}
  • write SQL
  • call JDBC API
  • map to DTO (database-object)

 

problem
  • boilerplate code (SQL Query, JDBC API)

 

SQL-dependent development

strong dependency relationship
  • query's result must match entity's field (when modifing query, it's necessary to update entity's fields)
  • difficulty in layer separation

 

2. 패러다임의 불일치

Identity

database
  • PK value to distinguish rows

 

JPA
  • return value of equals() to distinguish instance

 

Inheritence

database
  • not exist
  • can be represented using supertype-subtype

 

JPA
  • can handle database as object by generating query for supertype-subtype

 

Association

database
  • join query (referential integrity)

 

JPA
  • interact with associated objects (exchange message)

 

Entity Graph 

  • entity relationship

 

database
  • join query (referential integrity)

 

JPA
  • Loading associated objects based on navigation starting point
  • lazy loading: request query at point of object usage

 

3. JPA란 무엇인가?

  • Java ORM Standard Specification

 

ORM

  • Object Relation Mapping
  • How the application manages the databases

 

Strength

Readability & Maintainability
  • Object-Table mapping resolves paradigm mismatch by handling paradigm-specific tasks
  • Automated database operations (JpaRepository)
  • Standard mechanisms for object lifecycle (@PreUpdate, @PrePersist)

 

Easily manage the data access layer
  • Abstraction can avoid dependency on specific database vendor & technologies

 

Performance improvement
  • Provides first-level cache

 

Vendor

  • Hibernate, EclipseLink, DataNucleus