앞에서 만든 엔티티와 JPA 를 통해 데이터베이스에 테이블을 생성하였습니다.
데이터베이스에 저장된 데이터들을 처리하기 위해서는 JPA Repository 가 필요한데
Repository 는 데이터에 접근하는 메서드를 사용하기 위한 인터페이스로
Question 과 Answer Repository 를 작성해보겠습니다.
시작
먼저 위와 같이 repository 를 저장할 repository 패키지를 하나 만들어줍니다.
모든 repository 는 이 패키지 안에서 관리를 하겠습니다.
QuestionRepository
Repository 를 만들기 위해서는 다음 과정으로 진행합니다.
- JpaRepository 인터페이스 상속
- 제네릭 타입 지정 <대상 엔티티, 엔티티 기본키의 속성 타입>
여기서 QuestionRepository 는 Question 엔티티에 접근해서 사용하기 때문에
대상 엔티티는 Question, 엔티티 기본키의 속성 타입은 Quesiton 의 기본키인 id 의 타입인 Integer 가 됩니다.
package com.crud.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.crud.model.Question;
public interface QuestionRepository extends JpaRepository<Question, Integer>{
}
위와 같이 QuestionRepository 인터페이스를 만들고 JpaRepository 를 상속합니다.
Repository 는 findAll, findById 등의 기본 메서드들이 있지만 우리가 원하는 속성(subject) 을 통해 조회하기 위해서는
메서드를 따로 작성해야합니다.
package com.crud.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.crud.model.Question;
public interface QuestionRepository extends JpaRepository<Question, Integer>{
Question findBySubject(String subject);
}
이제 findBySubject 메서드를 통해 subject 값으로 데이터를 조회할 수 있습니다.
findBy + 엔티티의 속성명(subject, content 등)
이때 and 조건을 사용하면 여러개의 속성으로 조회할 수 있습니다.
다음과 같이 subject 와 content 두개 속성으로 조회를 하는 findBySubjectAndContent 메서드를 생성해보겠습니다.
findBy + 엔티티의 속성명 + 조건(And, Or, Between 등) + 엔티티의 속성명
package com.crud.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.crud.model.Question;
public interface QuestionRepository extends JpaRepository<Question, Integer>{
Question findBySubject(String subject);
Question findBySubjectAndContent(String subject, String content);
}
다음으로 제목(subject) 에 특정 문자열이 포함된 데이터를 조회하는 메서드를 만들어보겠습니다.
package com.crud.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.crud.model.Question;
public interface QuestionRepository extends JpaRepository<Question, Integer>{
Question findBySubject(String subject);
Question findBySubjectAndContent(String subject, String content);
List<Question> findBySubjectLike(String subject);
}
결과가 여러개일 경우 위와 같이 메서드의 리턴 타입은 List<> 형태로 작성해줍니다.
AnswerRepository
QuestionRepository 와 동일하게 AnswerRepository 도 생성합니다.
package com.crud.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.crud.model.Answer;
public interface AnswerRepository extends JpaRepository<Answer, Integer> {
}
Answer 엔티티는 Repository 의 기본 메서드로 접근할것이기 때문에 따로 메서드는 작성하지 않겠습니다.
데이터 조회
위에서 만든 QuestionRepository 를 통해 데이터를 조회해보겠습니다.
먼저 question 테이블에 테스트 데이터를 하나 넣어줍니다.
MariaDB [springboot_crud]> insert into question (subject, content) values ('first test subject', 'hello this is first test content');
Query OK, 1 row affected (0.004 sec)
MariaDB [springboot_crud]> select * from question;
+----+----------------------------------+-------------+--------------------+
| id | content | create_date | subject |
+----+----------------------------------+-------------+--------------------+
| 1 | hello this is first test content | NULL | first test subject |
+----+----------------------------------+-------------+--------------------+
1 row in set (0.000 sec)
다음으로 브라우저에 localhost:8080/question/list 를 입력했을때 콘솔창에 데이터를 출력해보겠습니다.
controller 패키지 안에 QuestionController 를 생성하고 다음과 같이 입력합니다.
package com.crud.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.crud.model.Question;
import com.crud.repository.QuestionRepository;
@RestController
public class QuestionController {
@Autowired
private QuestionRepository questionRepository;
@GetMapping("/question/list")
public String list() {
List<Question> questionList = questionRepository.findAll();
for(Question question : questionList) {
System.out.println("제목 : " + question.getSubject());
System.out.println("내용 : " + question.getContent());
}
return "test";
}
}
마지막으로 application.properties 파일의 hibernate.ddl-auto 를 create 에서 update 로 수정합니다.
브라우저를 통해 localhost:8080/question/list 접속해보면 화면에 test 라는 글자가 보이며
Eclipse 콘솔창에는 테스트 데이터가 출력되는것을 확인할 수 있습니다.
제목 : first test subject
내용 : hello this is first test content
'Spring > Springboot 실습' 카테고리의 다른 글
게시판 만들기 - 질문 상세페이지 작성 (0) | 2023.01.08 |
---|---|
게시판 만들기 - service 작성 (0) | 2023.01.08 |
게시판 만들기 - 브라우저를 통한 데이터 출력 (0) | 2023.01.08 |
게시판 만들기 - JPA 를 통한 테이블 생성 (0) | 2023.01.05 |
게시판 만들기 - 시작 및 환경설정 (0) | 2023.01.04 |