Spring Boot에서는 spring-boot-starter-data-jpa를 통해 JPA 기능을 쉽게 사용할 수 있다.
이를 사용하기 위해서는 의존성(Dependency)을 추가해줘야 한다. 또한, 데이터베이스를 사용하기 위한 관련 의존성도 필요하다.
이 글에서는 H2를 사용한다.
pom.xml
// JPA 사용
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
// H2 사용
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>2.7.3</version>
</dependency>
Entity
- @Entity: 클래스가 데이터베이스의 테이블과 매핑된다는 것을 나타낸다.JPA는 해당 클래스의 인스턴스를 데이터베이스 테이블의 레코드와 연결한다.
- @id: 해당 테이블의 PK 필드를 나타낸다.
- @GeneratedValue: PK 생성 규칙을 나타낸다. 스프링부트 2.0에서는 GenerationType.IDENTITY 옵션을 추가해야만 auto_increment가 된다.
- @Column: 테이블의 칼럼을 나타낸다. 선언하지 않아도 해당 클래스의 필드는 모두 칼럼이되지만, 컬럼의 이름, 길이, NULL 허용 여부 등 다양한 속성을 설정할 수 있다.
- @Table: 매핑될 데이터베이스 테이블의 이름을 명시적으로 지정하거나, 다른 설정을 추가할 때 사용된다.
- @MIN, MAX: 필드이 값이 최소 500 최대 1000 이여야 한다는 것을 의미한다.
Entity 클래스에 값을 채우기 위해 Setter를 만들지 않는다. Setter 메소드는 클래스의 인스턴스 값들이 언제 어디서 변해야하는지 코드상으로 명확히 구분할 수 없게 만들어 차후 기능 변경 시 복잡함을 더한다.
DB에 삽입할 때는 생성자 또는 @Builder를 통해 최종값을 채운 후 DB에 삽입한다.
@Entity
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Table(name = "product")
public class ProductEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
String productId;
@Column(name = "productName", length = 100, nullable = false)
String productName;
@Min(500)
@Max(1000)
Integer productPrice;
Integer productStock;
}
JPA Repository 생성
- JpaRepository<T, ID> 인터페이스를 상속받는인터페이스를 만든다.
- T에는 객체 클래스(Entity)를 입력하고, ID에는 클래스의 ID(기본키)에 대한 데이터 타입을 입력한다.
- JpaRepository를 상속한 ProductRepository가 실질적으로 DB와 통신한다고 생각하면 된다.
package com.example.jpaproject.repository;
import com.example.jpaproject.data.entity.ProductEntity;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductRepository extends JpaRepository<ProductEntity, String> {
}
JpaRepository는 기본적인 CRUD 기능을 제공한다.
application properties
## db설정
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.datasource.url=jdbc:mariadb://localhost:3307/testdb
spring.datasource.username=root
spring.datasource.password=password
# Hibernate 설정
spring.jpa.hibernate.ddl-auto=create
# Hibernate가 실행하는 SQL 쿼리를 콘솔에 출력하도록 설정
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto
Hibernate가 애플리케이션을 시작할 때, 데이터베이스의 테이블을 어떻게 관리할지를 결정한다.
5가지의 설정이 있다.
- create: 애플리케이션 실행 시 테이블을 새로 생성
- update: 변경 사항이 있을 경우, 테이블을 업데이트(데이터는 보존)
- create-drop: 애플리케이션 종료 시점에 테이블을 삭제합
- validate: 데이터베이스 스키마가 엔티티와 일치하는지 검증
- none: Hibernate가 아무런 스키마 관리를 하지 않음
개발단계에서는 create를 주로 사용하지만 운영 단계 에서는 절대로 사용하면 안된다. 보통 validate와 none을 사용한다.
위와 같이 설정하고 실행하면
Hibernate가 product 데이터베이스에 테이블을 생성한다는 로그와 함께 데이터 베이스가 생성된 것을 확인할 수 있다.
(created_at과 updated_at 컬럼은 @EntityListeners 관련하여 생긴 컬럼인데 무시하도록 하자)
Hibernate: create table product (product_price integer check ((product_price>=500) and (product_price<=1000)), product_stock integer, created_at datetime(6), product_id bigint not null auto_increment, updated_at datetime(6), product_name varchar(500) not null, primary key (product_id)) engine=InnoDB
참고
[Start Spring Boot] JPA로 데이터베이스 사용하기 (velog.io)
[JPA] Spring 에서 JPA 사용하기 (tistory.com)
[Spring Boot] 스프링부트 프로젝트에 Spring Data JPA 적용하기 (tistory.com)
'Spring' 카테고리의 다른 글
유효성 검증(Validation) (0) | 2024.09.08 |
---|---|
Logback이란? (1) | 2024.09.08 |
JPA란? (3) | 2024.09.01 |
의존성 주입 방법 (0) | 2024.08.25 |
Spring boot 3 버전 이상 swagger 사용법 (0) | 2024.08.24 |