새소식

IT/Spring

[Spring] CRUD:Read

  • -
728x90
반응형

데이터 조회 과정

 

① 사용자가 조회할 데이터를 웹 페이지에서 URL 요청을 보냄

 서버의 Controller가 요청을 받아 해당 URL에서 찾으려는 정보를 Repostiory에 전달

 리파지터리는 정보를 가지고 DB에 데이터 조회를 요청

 DB는 해당 데이터를 찾아 이를 Entity로 반환

 반환된 엔티티는 model을 통해 view template으로 전달됨

최종적으로 결과 view page가 완성돼 사용자의 화면에 출력

 


 URL 요청을 전달받음

@GetMapping("~~/{id}")

@GetMapping("/~~/{id}")
    public String show(@PathVariable Long id, Model model) {
}

 

@PathVarialbe 어노테이션을 붙여야 URL의 id를 가져올 수 있음

 

Repostitory는 특별히 조회된 데이터가 없는 경우 처리해야 함

 

방법 1

Optional<Article> Entity = Repository.findById(id);

방법2

Article Entity = Repository.findById(id).orElse(null);

 


  id로 DB에서 조회한 데이터를 모델에 article이라는 이름으로 등록

model.addAttribute("article", articleEntity);

 


반환 데이터 타입 불일치 문제 해결

 

1. 메서드가 반환하는 데이터 타입을 사용자가 작성한 데이터 타입으로 casting(형변환)하기

List<Article> articleEntityList = (List<Article>) articleRespository.findAll();

2. 사용자가 작성한 데이터 타입을 메서드가 반환하는 데이터 타입으로 수정하기

Iterable<Article> articleEntityList = articleRespository.findAll();

 

3, 메서드의 반환 데이터 타입을 원하는 타입으로 오버라이딩하기

// repository 파일

public interface ArticleRepository extends CrudRepository<Article, Long> {
    @Override
    ArrayList<Article> findAll(); // Iterable → ArrayList 수정
}
728x90

'IT > Spring' 카테고리의 다른 글

[Spring] CRUD:Update 01  (0) 2024.01.17
[Spring] 롬복  (0) 2024.01.14
[Spring]  (0) 2024.01.12
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.