PostsRepository 인터페이스에 쿼리를 추가해야 한다.
JPA에서 기본적으로 제공하지 않는 메소드는 쿼리를 작성해서 만들 수 있다.
public interface PostsRepository extends JpaRepository<Posts, Long> {
@Query("SELECT p FROM Posts p ORDER BY p.id DESC")
List<Posts> findAllDesc();
}
readOnly = true
조회 기능만 가능. 트랜잭션 범위는 유지하고 조회 기능만 남겨두기 때문에 조회 속도가 개선된다.
PostsListResponseDto 변환 -> List로 반환한다.
@Transactional(readOnly = true)
public List<PostsListResponseDto> findByDesc() {
return postsRepository.findAllDesc().stream()
.map(PostsListResponseDto::new)
.collect(Collectors.toList());
}
entity와 맞닿아있는 계층. entity에서 데이터를 가져온다.
@Getter
public class PostsListResponseDto {
private Long id;
private String title;
private String author;
private LocalDateTime modifiedDate;
public PostsListResponseDto(Posts entity) {
this.id = entity.getId();
this.title = entity.getTitle();
this.author = entity.getAuthor();
this.modifiedDate = entity.getModifiedDate();
}
}
Model
: 서버 템플릿 엔진에서 사용할 수 있는 객체를 저장
postsService.findAllDesc()
로 가져온 결과를 posts 형식으로 index 화면 파일에 전달한다.
@GetMapping("/")
public String index(Model model) {
model.addAttribute("posts", postsService.findByDesc());
return "index";
}