티스토리 뷰

Spring

데이터 5~6부 : 스프링 데이터 JPA

kingsubin 2020. 7. 12. 16:25

 

Spring Data JPA -> JPA -> Hibernate -> Datasource

 

- 의존성 추가

spring-boot-starter-data-jpa,

 

- 실제 수행과 테스트를 위한 디비 의존성 추가

h2, postgresql

 

- 클래스 생성

@Entity -> 테이블을 객체화 시켰다고 생각.

@GeneratedValue -> repository를 통해 저장할 때, 자동으로 값을 준다 . Auto라고 생각.

기본적으로 id , getter,setter가 필요하다.

getter,setter, equlas,hashCode 생성 , 롬복을 활용해도 좋다.

 

 

 

- Repository interface 생성

extends JpaRepository<'entity class', 'id'>

 

 

- 테스트 

@SpringbootTest로 통합 테스트, @DataJpaTest로 슬라이스 테스트가 있다.

통합 테스트로 할때는 application.properties가 적용되어 실제 내가 쓸려고 하는 db에 영향을 미친다.

 

추천하는 방법은 슬라이스 테스트이다. 

슬라이스 테스트를 할때는 인메모리 데이터베이스를 사용한다 (h2).

 

@SpringbootTest를 사용하고 싶다면,

@SpringbootTest(properties = "spring.datasource.url={ 테스트용 db url }")

 

@DataJpaTest를 통해 Datasource, JdbcTemplate 를 주입받을 수 있다.

 

@DataJpaTest 사용시 출력으로 h2를 사용중임을 알 수 있다.

 

 

기존에 findByUsername이라는 메소드는 없다.

 

findBy필드(필드타입 이름)

AccountRepository에서 findByUsername이라는 메소드 생성

메소드만 추가하면, 빈으로 등록하는 것 까지 spring data jpa가 알아서 해준다.

 

@Query로 커스텀 할 수도 있다

ex) @Query(nativeQuery = true, value = "select * from account where username = '{0}' ")

      Account findByUsername(String username );

 

 

 


※참조

www.inflearn.com/course/스프링부트/lecture/13560

 

'Spring' 카테고리의 다른 글

시큐리티 1부~2부  (0) 2020.07.13
데이터 7부 : 데이터베이스 초기화  (0) 2020.07.13
데이터 4부 : PostgreSQL  (0) 2020.07.12
데이터 3부 : MySQL  (0) 2020.07.12
데이터 2부 : 인메모리 데이터베이스  (0) 2020.07.12