> For the complete documentation index, see [llms.txt](https://dahye-jeong.gitbook.io/til/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dahye-jeong.gitbook.io/til/spring/2020-04-11-jpa-basic.md).

# JPA란?

## 개념 정리

![JPA, Hibernate, Spring Data JPA의 전반적인 그림](/files/-M4dgOUrQ_gjHp4JcHrF)

### H2 Database

H2는 자바 기반의 RDBMS이다. Browser console 지원, 저용량(2MB), JDBC API 지원 등 다양한 장점을 가지고 있다. 최소한의 리소스로 실행 가능한 경량 DB로서 테스트용으로 사용하기 알맞은 DB이다.

* [install h2 database ](https://www.h2database.com/html/installation.html)

### JPA

JPA(Java Persistence API)는 현재 ORM(Object Relational Mapping)의 기술 표준으로, 인터페이스 모음이다. 즉, ORM을 사용하기 위한 인터페이스를 모아둔 것이라 볼 수 있다. ORM에 대한 자바 API 규격이며 **Hibernate, OpenJPA** 등이 JPA를 구현한 구현체이다.

### Hibernate

JPA를 사용하기 위해서 JPA를 구현한 ORM 프레임워크 중 하나이&#xB2E4;**. Hibernate는 JPA 명세의 구현체**로, `javax.persistence.EntityManager` 와 같은 JPA의 인터페이스를 직접 구현한 라이브러리이다.

### Spring Data JPA

Spring Data JPA는 JPA를 쓰기 편하게 만들어 놓은 모듈로 개발자가 JPA를 더 쉽고 편하게 사용할 수 있도록 도와준다. 이는 JPA를 한단계 추상화 시킨 Repository라는 인터페이스를 제공함으로써 이루어진다. 사용자가 Repository 인터페이스에 정해진 규칙대로 메소드를 입력하면, Spring이 알아서 해당 메소드 이름에 적합한 쿼리를 날리는 구현체를 만들어 Bean으로 등록해준다.

## Spring Boot 설정

#### pom.xml

```markup
<!-- h2 database -->
<dependency>
  <groupId>com.h2database</groupId>
  <artifactId>h2</artifactId>
  <scope>runtime</scope>
</dependency>

<!-- jpa  -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
```

#### application.yml

```yaml
spring:
  datasource:
    driverClassName: org.h2.Driver
    url: jdbc:h2:mem:testdb                # testdb 스키마에 mem인 메모리 데이터 베이스로 동작
    username: sa
    password:
    sql-script-encoding: utf-8

  h2:
    console:
      enabled: true                            # h2 콘솔 사용
      path: /h2                                    # localhost:port/h2 로 접근 가능
      settings:
        trace: false                        # Print additional trace information 
        web-allow-others: true    # 브라우저로 접근가능하게 하기

  jpa:
    show-sql: true          # sql 쿼리 콘솔 출력
    properties:
      hibernate:
        format_sql: true     # sql 보기좋게 출력 
    generate-ddl: false       # @Entity 어노테이션 기준으로 DDL 작업 방지
    hibernate:
      ddl-auto: validate      # 변경된 스키마가 있는지 확인
```

다음과 같이 설정하면 기본적으로 h2 database에 jpa를 사용할 준비가 다 되었다.

## 참조

* <https://daddyprogrammer.org/post/152/spring-boot2-h2-database-intergrate/>
* <https://suhwan.dev/2019/02/24/jpa-vs-hibernate-vs-spring-data-jpa/>
