본문 바로가기
프로젝트/스프링 부트와 AWS로 혼자 구현하는 웹 서비스_실습

스프링 부트와 AWS로 혼자 구현하는 웹 서비스 06

by dudung__ 2023. 8. 13.

하던 것에 이어, Posts 클래스로 DB에 접근하게 해줄 JpaRepository를 생성

import org.springframework.data.jpa.repository.JpaRepository;


public interface PostsRepository extends JpaRepository<Posts, Long> {
}

 

인터페이스를 생성하고, JPA 레포지토리를 상속하면, 기본적인 CRUD 메소드가 자동으로 생성됨

 

C : create

R : Read

U : Update

D : Delete

 

장고 수업을 들으면서, 게시판 코드를 작성할때 많이 작성해본 기억이 나는 부분이였음 ㅎㅎ..

 

 

 

03_3 JPA 테스트 코드 작성하기

전에 했던것과 같이, TEST 패키지에 main에 있는 패키지와 동일한 경로로 TEST 패키지경로, 클래스를 만들어서 진행함

 

 

import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

@RunWith(SpringRunner.class)
@SpringBootTest
public class PostsRepositoryTest {

    @Autowired
    PostsRepository postsRepository;

    @After //1
    public void cleanup(){
        postsRepository.deleteAll();
    }

    @Test
    public void boardSave_get(){
        // given
        String title = "테스트 게시글";
        String content = "테스트 본문";

        postsRepository.save(
                Posts.builder() //2
                        .title(title)
                        .content(content)
                        .author("jojoldu@gmail.com")
                        .build()
        );
        
        // when 
        List<Posts> postsList = postsRepository.findAll(); //3
        
        
        // then
        Posts posts = postsList.get(0);
        assertThat(posts.getTitle()).isEqualTo(title);
        assertThat(posts.getContent()).isEqualTo(content);
    }
}

 

 

1. @after

Junit에서 단위테스트가 끝날 떄마다 수행되는 메소드를 지정

 

2. postsRepository.save

테이블 posts에 insert/update 쿼리를 실행

-> id값이 있다면 update, 없다면 insert쿼리를 진행

 

이 부분을 작성할때도, 사소한 문제가 생겼었음

Posts.builder()

이 .builder() 메서드가 어떤 방법을 써봐도 빨간줄이기에, 인텔리제이 프로그램을 껐다가 다시 켰더니 아무것도 만지지 않았는데, 오류가 사라졌음

 

it업계에서 기기나 개발 도구가 문제가 생기면 해볼 수 있는 방법을 다 해보고 않되면 껐다 키라더니 괜히 있는 말이 아닌듯한..(물론 백업은 확실하게 해놔야겠지만 ㅎㅎ)

 

 

3. postsRepository.findAll

테이블 posts에 있는 모든 데이터를 조회

 

 이후에 TEST를 돌려보니

 

 

성공적으로 TEST가 돌아간것을볼 수 있었음

 

 

 

후에 실제로 실행된 쿼리가 어떤 형태인지 궁금했는데, 마침 책에서 이부분에 대해서 말해준것이 있어 따라해 보았음

- src.main.resource 아래에 application.properties 파일을 생성

spring.jpa.show_sql=true

 

다음 코드를 추가한 후, 다시 테스트를 진행

 

책에 나온것과 비슷한 실행 형태를 확인할 수 있었고

 

출력의 형태가 H2의 쿼리 문법이 적용된 상태인데, H2는 MySQL쿼리도 정상적으로 수행되기 떄문에 출력을 MySQL로 변경

=> 이때 작성한 코드를 넣은 이후로 테스트에서 계속 오류가 발생함

 

 

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

=> 이코드가 예전 버전에 사용하던거라고 하는데.. 구글링을 해봐도 효과가 있는 해결책은 보이지 않음..