본문 바로가기
학습/Spring

[spring] 스프링 부트에서 Spring Data JPA 사용하기

by KKambi 2020. 5. 7.

ORM

Object Relational Mapping

  • Object와 Relation을 맵핑할 때 발생하는 개념적 불일치에 대한 솔루션을 제공하는 프레임워크
  • 객체지향
    1. 클래스는 primitive type / reference type의 멤버 필드와 메소드를 가질 수 있다.
    2. 객체는 담고 있는 필드, 메소드에 따라 크기가 다양하다.
    3. 객체는 hashCode(), equlas(), == 로 비교될 수 있다.
  • Relational Database
    1. 테이블은 컬럼만 가질 수 있다.
    2. 테이블은 크기가 한정적이다. 예상될 수 있다.
    3. 레코드의 식별자는 id로 단순하다.
  • 이렇게 많은 차이를 보이는 객체와 RDB를 ORM이 연결해준다.

 

 

Spring Data JPA

org.springframework.boot:spring-boot-starter-data-jpa 의존성 추가

  • JPA는 인터페이스로 표준 명세서의 불과
  • Hibernate : 구현체 필요
  • Spring Data JPA : 구현체를 쉽게 사용하고자 추상화시켜놓음
  • 결론 : Spring Data JPA 사용 = Hibernate 사용 = JDBC의 DataSource 사용하게 됨

 

cf) JPA관련 클래스들은 모두 javax.persistence 패키지에 존재

 

 

객체 맵핑

@Entity class

  • 특정 테이블의 컬럼만을 멤버 필드로 가지는 클래스
  • JPA가 관리
  • 기본 생성자 필수
  • 구현체에만 선언 가능
  • @Id : Repository를 통해 저장할 때 자동으로 순번 부여
  • 자바 빈 규약을 따르므로 getter 필요
  • equals()와 hashCode()도 구현해주면 좋음

 

 

Repository interface

  • JpaRepositroy<entity type, pk type>을 extends하는 repository 인터페이스 생성
  • @Repository를 선언하지 않아도, JpaRepostiory를 상속하면 자동으로 빈 등록

 

cf) @Component를 역할에 맞게 구체화시킨 것이 @Controller / @Service / @Repository

cf) @Repository는 DB에 접근하는 클래스 = DAO

 

 

테스트 해보기

  • slice test (@DataJpaTest)
  • DataSource, jdbcTemplate을 bean으로 주입받을 수 있음 (JPA 관련 빈)
  • 슬라이스 테스트 = In-memory DB 필수 (h2)
  • @SpringBootTest는 모든 빈을 등록하므로 느림

 

테스트1

  • 비어있는 테스트
  • @Autowired로 선언한 Bean이 잘 주입받는지 확인가능
  • 테스트 어플리케이션이 잘 실행되는지 확인가능
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@RunWith(SpringRunner.class)
@DataJpaTest
public class AccountRepositoryTest {
 
    @Autowired
    AccountRepository accountRepository;
 
    @Autowired
    DataSource dataSource;
 
    @Autowired
    JdbcTemplate jdbcTemplate;
 
    @Test
    public void di(){
 
    }
}
cs

 

테스트2

  • repository test
  • Entity 객체 생성하여 컬럼 세팅
  • Repository에 해당 객체를 save했을 때 나오는 반환값으로 테스트
  • findByUsername()으로 존재하지 않는 엔티티 객체, 존재하는 엔티티 객체에 테스트
  • repository 인터페이스에서 메소드 시그니처만 선언해도 알아서 구현해줌 (쿼리 메소드)
  • assertThat으로 존재 여부 테스트
1
2
3
4
5
6
7
8
9
10
11
12
13
14
    @Test
    public void account(){
        Account account = Account.builder().userName("kkambi").password("123123").build();
 
        Account newAccount = accountRepository.save(account);
 
        assertThat(newAccount).isNotNull();
 
        Account foundAccount = accountRepository.findByUserName("kkambi");
        assertThat(foundAccount).isNotNull();
 
        Account notFoundAccount = accountRepository.findByUserName("babo");
        assertThat(notFoundAccount).isNull();
    }
cs

 

 

쿼리를 직접 쓰고 싶다면?

repository 인터페이스 내의 메소드에 @Query(nativeQuery = true, value = "쿼리문") 선언

댓글