YagSill

JAVA Spring boot DB데이터 전체 조회해보기 본문

JAVA Spring

JAVA Spring boot DB데이터 전체 조회해보기

YagSill 2022. 1. 14. 09:18
728x90

안냐세여~ Yagsill입니다.

이전 포스트에 이어 DB데이터의 모든 데이터를 조회해보는 시간을 갖도록 하겠씁니답!

 

DB에 차곡차곡 데이터를 넣었다면 해당 데이터를 전체를 한번 조회해 보아야 하겠죠??

그럴때 저희는 findAll() 메소드를 호출해서 확인해 볼 수 있습니다.

.findAll()

저의 DB의 구조를 Entity를 통해서 만들었습니다.

그렇다면 DB에 CRUD 할 수 있는 기능이 필요하겠죠? 그것이 Repository 입니다.

저는 DB를 따로 SQL로 만들지 않고 웹에 Entity를 이용해서 구조만 만들었기 때문에 Repository를 이용해서 데이터를 뽑을 수 있습니다.

 

articleRepository의 findAll은 타입이 다르기 때문에. articleRepository에서 타입을 정의 해주어야 함.
      List<Article> articleEntityList = articleRepository.findAll();

 

->  articleEntityList 라는 변수에 articleRepository 저의 ArticleRepository입니다. 거기서 .findAll()을 하게되면 되는데,

보시다시피 articleRepository의 타입이 List<Article> 이잖아요? 다시말하자면 List<Entity이름> 입니다. 어쨋건 List타입이에요.

-> 그래서 저는 해당 articleRepository의 타입을 정의해 줄겁니다.

 

public interface ArticleRepository extends CrudRepository<Article,Long> {

    //findAll을 사용하기 위하여 메소드를 Ovverride 해주어야 합니다. 그래야지만 Controller에서 사용할 수 있습니다.
    @Override
    ArrayList<Article> findAll();
}

이렇게 말이죠.

 

이상태로 빌드를 해보면? 웹에 아무것도 안떠요. 왜냐하면 우리는 Controller에서 웹을 보여주기 위해서는 링크를 설정해 주어야 한다고 했습니다.

 

@GetMapping("articles")
    public String index(Model model) {
        // 1. 모든 Article을 가져옵니다.
        // 2. articleRepository의 findAll은 타입이 다르기 때문에. articleRepository에서 타입을 정의 해주어야 함.
        List<Article> articleEntityList = articleRepository.findAll();

        //2. 가져온 Article 묶믐을 뷰로 전달.
        model.addAttribute("articleList",articleEntityList);

        //3 뷰 페이지 설정
        return "articles/index";
    }

}

 

-> Model 타입의 model을 인자값으로 받구요.

-> model에 addAttributename을 "articlList"로 지정해 두고. 위에서 선언한 articleEntityList 변수를 가져옵니다.

-> 그리고 뷰 페이지를 만들어서 보여주면 됩니다.

 

articles/index.mustache 웹 코드 입니다.

{{>layouts/header}}

// 부트스트랩에서 따온 테이블 레이아웃 코드
<table class="table">
    <thead>
    <tr>
        <th scope="col">ID</th>
        <th scope="col">Title</th>
        <th scope="col">Content</th>
    </tr>
    </thead>
    <tbody>
    {{#articleList}}
        <tr>
            <th>{{id}}</th>
            <td>{{title}}</td>
            <td>{{content}}</td>
        </tr>
    {{/articleList}}
    </tbody>
</table>
// 부트스트랩에서 따온 테이블 레이아웃 코드

{{>layouts/footer}}

 

짠 이렇게 되면 웹에서 직접 확인이 가능하답니다~

 

감사합니다~!!

728x90