31.3 JPA와 스프링 데이터 JPA

Java Persistence API는 객체를 관계형 데이터베이스에 "매핑"할 수있는 표준 기술입니다. spring-boot-starter-data-jpaPOM은 시작하는 빠른 방법을 제공합니다. 다음과 같은 주요 종속성을 제공합니다.

  • Hibernate : 가장 인기있는 JPA 구현 중 하나.

  • Spring Data JPA : JPA 기반 리포지토리를 쉽게 구현할 수 있습니다.

  • Spring ORMs : Spring Framework의 핵심 ORM 지원.

JPA 또는 Spring Data에 대한 세부 정보는 여기에 포함되지 않습니다. spring.io에서 "JPA로 데이터 접근하기"가이드를 따르고 Spring Data JPA와 Hibernate 참조 문서를 읽을 수있다.

31.3.1 엔티티 클래스

전통적으로 JPA "Entity"클래스는 persistence.xml파일에 지정 됩니다. Spring Boot를 사용하면 이 파일은 필요 없으며 "Entity Scanning"이 대신 사용됩니다. 기본적으로 기본 구성 클래스 ( @EnableAutoConfiguration또는로 주석 처리 된 패키지) 아래의 모든 패키지 @SpringBootApplication가 검색됩니다.

모든 클래스는 주석 @Entity, @Embeddable또는 @MappedSuperclass간주됩니다. 일반적인 엔티티 클래스는 다음 예제와 유사합니다.

package com.example.myapp.domain;

import java.io.Serializable;
import javax.persistence.*;

@Entity
public class City implements Serializable {

	@Id
	@GeneratedValue
	private Long id;

	@Column(nullable = false)
	private String name;

	@Column(nullable = false)
	private String state;

	// ... additional members, often include @OneToMany mappings

	protected City() {
		// no-args constructor required by JPA spec
		// this one is protected since it shouldn't be used directly
	}

	public City(String name, String state) {
		this.name = name;
		this.state = state;
	}

	public String getName() {
		return this.name;
	}

	public String getState() {
		return this.state;
	}

	// ... etc

}

@EntityScan어노테이션 을 사용하여 엔티티 스캐닝 위치를 사용자 정의 할 수 있습니다 . " 84.4 절."Spring 구성과 @Entity 정의의 분리 " 절을 참조하십시오 .

31.3.2 스프링 데이터 JPA 저장소

스프링 데이터 JPA 리포지토리는 데이터에 액세스하기 위해 정의 할 수있는 인터페이스입니다. JPA 쿼리는 메소드 이름에서 자동으로 작성됩니다. 예를 들어, CityRepository인터페이스는 findAllByState(String state) 메소드를 선언하여 주어진 상태에서 모든 도시를 찾는 할 수 있습니다 .

보다 복잡한 쿼리의 경우, Spring 데이터의 Queryannotation으로 메소드에 주석을 달 수 있습니다 .

Spring 데이터 저장소는 일반적으로 Repository또는 CrudRepository 인터페이스 에서 확장 됩니다. 당신이 자동 구성을 사용하는 경우, 저장소는 기본 구성 클래스 ( @EnableAutoConfiguration또는 @SpringBootApplication주석 이 포함 된 패키지)에서 저장소가 검색됩니다.

다음 예제는 일반적인 스프링 데이터 저장소 인터페이스 정의를 보여줍니다.

package com.example.myapp.domain;

import org.springframework.data.domain.*;
import org.springframework.data.repository.*;

public interface CityRepository extends Repository<City, Long> {

	Page<City> findAll(Pageable pageable);

	City findByNameAndStateAllIgnoringCase(String name, String state);

}

Spring 데이터 JPA 저장소는 세 가지 다른 부트 스트래핑 모드를 지원합니다 : default, deferred, and lazy. deferred or lazy 부트 스트랩을 사용하려면 spring.data.jpa.repositories.bootstrap-mode을 각각 deferred또는 lazy설정하십시오. deferred or lazy 부트 스트랩을 사용할 때, 자동 구성된 EntityManagerFactoryBuilder 는 컨텍스트를 AsyncTaskExecutor를 부트 스트랩 실행 프로그램으로 사용합니다 (있는 경우). 둘 이상이 있으면 이름 applicationTaskExecutor이 지정된 이름으로 사용됩니다.

deferred or lazy의 차이점은 다들 모른대..

Spring Data JPA의 표면을 간신히 긁어 모았습니다. 자세한 내용은 Spring 데이터 JPA 참조 문서를 참조 하십시오 .

31.3.3 JPA 데이터베이스 생성 및 삭제

기본적으로 JPA 데이터베이스는 내장 데이터베이스 (H2, HSQL 또는 Derby)를 사용하는 경우 에만 자동으로 생성 됩니다 . spring.jpa.*특성 을 사용하여 JPA 설정을 명시 적으로 구성 할 수 있습니다 . 예를 들어, 테이블을 작성하고 제거하려면 다음 행을 application.properties다음에 추가 할 수 있습니다 .

spring.jpa.hibernate.ddl-auto = create-drop

이것에 대한 Hibernate의 내부 속성 이름 (만약 당신이 그것을 더 잘 기억한다면)이있다 hibernate.hbm2ddl.auto. 다른 Hibernate 네이티브 프로퍼티들과 함께 이것을 사용할 수있다. spring.jpa.properties.*(접두사는 엔티티 관리자에 추가하기 전에 제거된다.) 다음 줄은 Hibernate를위한 JPA 속성 설정의 예를 보여준다.

spring.jpa.properties.hibernate.globally_quoted_identifiers = true

앞의 예제에서의 라인은 hibernate.globally_quoted_identifiers프로퍼티 에 대한 true값을 Hibernate 엔티티 관리자로 전달한다.

기본적으로 DDL 실행 (또는 유효성 검사)은 ApplicationContext 시작될 때까지 연기 됩니다. spring.jpa.generate-ddl플래그 도 있지만 Hibernate 자동 구성이 활성화되어 있으면 ddl-auto설정이 더 세밀 하기 때문에 사용되지 않습니다 .

31.3.4 뷰에서 EntityManager 열기

웹 어플리케이션을 실행하고 있다면 Spring Boot는 기본적 OpenEntityManagerInViewInterceptor 으로 웹 뷰에서 느슨한 로딩을 허용하기 위해 "View에서 EntityManager 열기"패턴을 적용하도록 등록 합니다. 이 동작을 원하지 않는 경우, 당신은application.properties에서 spring.jpa.open-in-viewfalse으로 정해야합니다.

Last updated