Book/Spring boot 와 AWS로 혼자 구현하는 웹서비스
[Book] 16) 전체 조회 화면 및 기능을 만들어보자!
kkkkkkkkkkkk
2022. 4. 2. 19:45
🥢 전체 조회 화면 구성하기!
아래 코드는 앞전에 만든 index.mustache 파일에 있는 코드입니다.
<table class="table table-horizontal table-bordered">
<thead class="thead-strong">
<tr>
<th>게시글번호</th>
<th>제목</th>
<th>작성자</th>
<th>최종수정일</th>
</tr>
</thead>
<tbody id="tbody">
{{#posts}}
<tr>
<td>{{id}}</td>
<td><a href="/posts/update/{{id}}">{{title}}</a></td>
<td>{{author}}</td>
<td>{{modifiedDate}}</td>
</tr>
{{/posts}}
</tbody>
</table>
😀 Repository 에 전체 조회 기능 만들기!!
PostsRepository 에 기능을 추가해봅시다.
@Query("select p from Posts p order by p.id desc")
List<Posts> findAllDesc();
List 타입으로 Posts의 모든 데이터를 내림차순으로 받아옵니다.
spring data jpa 의 기능으로 메서드 만으로 위와 같은 기능을 만들 수 있습니다.
List*<*Posts*>* findAllByOrderByIdDesc*()*;
하지만 위와 같은 메서드는 가독성이 떨어지므로 @Query 에노테이션으로 쿼리문을 만들어 사용했습니다.
🥲 Service 클래스에 전체 조회 기능 만들기!!
PostsService 클래스에 기능을 추가해봅시다.
@Transactional(readOnly = true)
public List<PostsListResponseDto> findAllDesc() {
return postsRepository.findAllDesc()
.stream()
.map(PostsListResponseDto::new)
.collect(Collectors.toList());
}
@Transactional(readOnly = true) 로 하는 이유는 트랜잭션 범위는 유지하되 조회 기능만 남겨두어 성능을 향상시킬 목적으로 사용 되었습니다.
메시지 수신자가 PostsListsResponseDto 이므로 stream 을 이용하여 객체 타입을 변환 시켜주고 List 타입으로 만들어줍니다.
😀 PostsListsResponseDto 클래스 생성
@Getter
public class PostsListResponseDto{
private Long id;
private String title;
private String author;
private LocalDateTime modifiedTime;
@Builder
public PostsListResponseDto(Posts entity) {
this.id = entity.getId();
this.title = entity.getTitle();
this.author = entity.getAuthor();
this.modifiedTime = entity.getModifiedTime();
}
}
😀 findAllDesc() 기능 테스트 코드 작성해보기!!
@Test
void findAllDesc() {
// given && when
List<PostsListResponseDto> responseDtos = postsService.findAllDesc();
// then
assertThat(responseDtos.isEmpty()).isFalse();
assertThat(responseDtos.size()).isEqualTo(2);
assertThat(responseDtos.get(0).getTitle()).isEqualTo("테스트2");
assertThat(responseDtos.get(1).getTitle()).isEqualTo("테스트1");
}
responseDto를 받아와서 검증을 진행합니다!!
😀 Model에 객체를 담아보자!
@GetMapping("/")
public String index(Model model) {
model.addAttribute("posts", postsService.findAllDesc());
return "index";
}
Model 은 서버 템플릿 엔진에서 객체를 저장할 수 있게 해줍니다.
위의 코드는 postsService.findAllDesc() 의 반환 값을 posts 로 index.mustache 파일에 전달합니다.!