포트폴리오/SPRINGBOOT 옛날

2-05 : repository

서버관리자 페페 2022. 9. 29. 18:46

단 하나의 맥락

: entity로 만든 박스(테이블)에 자료를 CRUD 하고, 서비스가 만들어지기 전 test로 기능을 시험해본다

 


 

Semiflow Bundle

- 리포지터리 생성과 테스트

- Save

- Read

- Update

- Delete

- 답변 Save

- 답변 Read

- A에 연결된 Q, Q에 연결된 A

 


 

자각

 

(Repository 개념)

- 리포지터리는 interface 형식으로, JpaRepository를 상속한다

- import org.springframework.data.jpa.repository.JpaRepository; 를 플러그인으로 사용한다

- 또한 제네릭스 타입의 상속으로, <Entity Type, Primary Key Type> 를 cursor로 사용한다

 

-

 

(Test 개념)

- Service 연결 전 Repository의 기능 작동은 src/test/java의 ApplicationTexts.java에 테스트 코드를 작성 실행한다

- 테스트 파일의 class는 @SpringBootTest 로 어노테이션 되어 있다 

- 테스트 파일의 Repository 객체는 private, @Autowired 로 어노테이션 되어 있다

- 테스트 파일의 method는 @Test 로 어노테이션 되어 있으며, Junit test시 해당 메소드를 실행한다

- @SpringBootTest P/I 는 import org.springframework.boot.test.context.SpringBootTest; 를 사용한다

- @Autowired P/I 는 import org.springframework.beans.factory.annotation.Autowired; 를 사용한다

- @Test P/I 는 import org.junit.jupiter.api.Test; 를 사용한다

- 로컬 서버를 중지해야 정상 테스트 된다

 

-

 

(질문 Create)

- A1 : Question q1 = new Question(); // 저장될 Entity > 테이블단

- A2 : q1.setSubject("sbb가 무엇인가요?");

- A3 : q1.setContent("sbb에 대해 알고 싶습니다");

- A4 : q1.setCreateDate(LocalDateTime.now());

- A5 : this.questionRepository.save(q1); // 저장

 

-

 

(정상 생성여부 체크)

- h2-console : SELECT*FROM QUESTION 으로 리포지터리의 기능이 잘 작동함을 확인한다

 

 

-

 

 

(질문 READ - findAll)

A1 : List<Question> all = this.questionRepository.findAll(); // 모든 데이터를 담는다

A2 : asserEquals(2, all.size()); // 사이즈가 일치 확인

A3 : Question q = all.get(0); // 모든 데이터에서 1번 데이터단을 추출한다

A4 : assertEquals("sbb가 무엇인가요?", q.getSubject()) // 단일 데이터단에서 원하는 종류(제목)에 접근

 

(assertEquals은 "import static org.junit.jupiter.api.Assertions.assertEquals;" P/I 를 사용한다)

 

 

-

 

 

(질문 READ - findById)

A1 : Optional<Question> oq = this.questionRepository.findById(1); 로 

A2-0 : if (oq.isPresent()) // 위상-존재여부-을 먼저 확인한 뒤 

A2-1 : Question q = oq.get(); 

A2-2 : assertEquals("sbb가 무엇인가요?", q.getSubject()); // 로 접근

 

(Optional은 "import java.util.Optional;" P/I 를 사용한다)

 

 

-

 

 

(질문 READ - findBySubject)

> SbbApplicationTests에서

A1 : Question q = this.questionRepository.findBySubject("sbb가 무엇인가요?");

A2 : assertEquals(1, q.getId()); 로 원하는 데이터 종류(id) 에 접근한다

 

> QuestionRepository에서

A1 : Question findBySubject(String subject); // 메서드 선언

 

 

-

 

(콘솔 로그에서 실행된 쿼리 확인)

> application.properties의 #JPA에서

- spring.jpa.properties.hibernate.format_sql=true

- spring.jpa.properties.hibernate.show_sql=true

 

를 추가하여 콘솔로그를 추적가능하다  콘솔 로그에는, 쿼리의 where 단에 subject가 포함된 것을 알 수 있다 

 

 

-

 

 

(질문 READ - findBySubjectAndContent)

> SbbApplicationTests에서

A1 : Question q = this.questionRepository.findBySubjectAndContent("sbb가 무엇인가요?", "sbb에 대해서 알고 싶습니다");

A2 : assertEquals(1, q.getId());

 

> QuestionRepository에서 

A1 : Question findBySubjectAndContent(String subject, String content);

 

 

-

 

(질문 READ - findBySubjectLike)

> sbbApplicationTests에서

A1: List<Question> qList = this.questionRepository.findBySubjectLike("sbb%"); 

A2 : Question q = qList.get(0); 

A3 : assertEquals("sbb가 무엇인가요?", q.getSubject()); 로

 

> QuestionRepository에서

A1 : List<Question> findBysubjectLike(String subject);

 

 

-

 

(질문 UPDATE)

A1 : Optional<Question> oq = this.questionRepository.findById(1); // 로 원하는 테이블 단을 담고

A2 : assertTrue(oq.isPresent()); // 존재하는 지 확인한다

A3 : Question q = oq.get; // 로 객체를 담고

A4 : q.setSubject("수정된 제목"); 

A5 : this.questionRepository.save(q); // 저장함으로서 업데이트된다

 

assertTrue는 "import static org.junit.jupiter.api.Assertions.assertTrue;" P/I 를 사용한다

콘솔 로그를 보면, 다음과 같은 update문이 실행되었음을 확인 가능하다 

 

-

 

(질문 DELETE)

A1 : assertEquals(2, this.questionRepository.count());로 삭제 실행 전 데이터건수를 확인한다

A6 : assertEquals(1, this.questionRepository.count());로 삭제 실행 후 데이터건수를 확인한다

A2 : Optional<Question> oq = this.questionRepository.findById(1); 

A3 : assertTrue(oq.isPresent()); 

A4 : question q = oq.get(); 

A5 : this.questionRepository.delete(q); // 로 삭제한다

 

-

 

(답변 CREATE)

P1 : private QuestionRepository questionRepository;(@Autowired)

P2 : private AnswerRepository answerRepository;(@Autowired)

 

A1 : Optinal<Question> oq = this.questionRepository.findById(2);

A2 : assertTrue(oq.isPresent());

A3 : Question q = oq.get(); 

 

A4 : Answer a  = new Answer();

A5 : a.setQuestion(q);

A6 : a.setContent("네, 자동으로 생성됩니다");

A7 : a.setCreateDate(LocalDateTime.now());

A8 : this.answerRepository.save(a); 

 

-

 

(답변 READ)

A1 : Optional<Answer> oa = this.answerRepository.findById(1);

A2 : asserTrue(oa.isPresent());

A3 : Answer a = oa.get(); // 로 원하는 데이터단을 가져오고

A4 : assertEquals(2, a.getQuestion().getId()); // A 내 Q 내 id도 조회해본다

 

 

-

 

 

(답변에 연결된 질문)

A1 : a.getQuestion();

 

-

 

(질문에 연결된 답변)

A1 : Optional<Question> oq = this.questionRepository.findById(2);

A2 : assertTrue(oq.isPresent());

A3 : Question q = oq.get();

 

A4 : List<Answer> answerList = q.getAnswerList(); // 로 특정 Q 커서에 담긴 A 리스트를 조회

A5 : assertEquals(1, answerList.size()); // 추출

A6 : assertEquals("네 자동으로 생성됩니다.", answerList.get(0).getContent()); 

 

 

- @Transactional 어노테이션으로 오류 처리

- Transactional은 "import org.springframework.transaction.annotation.Transactional;" P/I 를 사용한다

'포트폴리오 > SPRINGBOOT 옛날' 카테고리의 다른 글

2-08 : redirecting to ROOT URL  (1) 2022.10.01
2-07 : template  (3) 2022.09.30
2-04 : Entity  (4) 2022.09.27
2-03 : ORM / JPA / H2-DB / JPA 셋팅  (4) 2022.09.27
2-02 : Controller  (0) 2022.09.27