Spring Data에서 날짜별로 마지막으로 주문한 레코드 가져오기
Spring Data 저장소에서 날짜별로 정렬된 테이블의 마지막 레코드를 가져오는 방법을 정의하려고 합니다.이건 내 실체야:
@Entity
public class News {
@Id
@GeneratedValue
private Long id;
@Column(nullable = false)
private String title;
@Column(nullable = false)
private String text;
private Date publicationDate;
/* Getters and Setters */
}
여기가 제 저장소입니다.
public interface NewsRepository extends JpaRepository<News, Long> {
List<News> findFirst5OrderByPublicationDateDesc();
}
프로젝트 시작을 사용하려고 하면 다음 오류가 발생합니다.
원인: org.springframework.data.mapping.속성 참조 예외:날짜 유형에 대한 속성 설명을 찾을 수 없습니다!통과 경로: News.publicationDate.
Desc를 제거하면 다음과 같이 표시됩니다.
원인: java.util.해당 요소 없음예외.
내가 뭘 잘못하고 있는 거지?
메소드의 서명이 올바르지 않은 것으로 나타났습니다.올바른 것은 다음과 같습니다.
findFirst5ByOrderByPublicationDateDesc()
공식 샘플에 다음과 같은 내용이 포함되어 있기 때문에 약간 혼란스럽습니다.
List<User> findTop10ByLastname(String lastname, Pageable pageable);
보시는 것처럼, 거기에는 보통의 것이 하나 있습니다.
Spring JpaRepository에는 큰 도움이 될 수 있는 페이지가 있습니다.이것도 완벽하게 작동할 것입니다.
상위 10개 레코드를 반환하려면 다음을 사용할 수 있습니다.
사용자 지정 페이지 개체 만들기
Pageable pageable = new PageRequest(0, 10, Sort.Direction.ASC, "id");
Page<News> topPage = newsRepository.findByPublicationDate(id, pageable);
List<News> topUsersList = topPage.getContent();
NewsRepository 인터페이스에서 메서드를 생성해야 합니다.
Page<News> findByPublicationDate(Date date, Pageable pageable);
이렇게 하면 최상위 레코드가 반환됩니다.
최근 10개의 레코드를 반환하려면 다음을 사용합니다.
Pageable pageable = new PageRequest(0, 10, Sort.Direction.DESC, "id");
Page<News> bottomPage = newsRepository.findByPublicationDate(id, pageable);
// this is a list of the last 10 records, you can choose to invert it by using
List<News> bottomUsersList = bottomPage.getContent();
Collections.inverse(bottomUsersList);
이렇게 하면 동일한 NewsRespository가 재사용되므로 다른 메서드를 생성할 필요가 없습니다.
페이지를 사용하면 다른 열로 정렬할 수 있다는 장점이 있습니다. (ASC 또는 DESC)
// To get top by text
Pageable pageable = new PageRequest(0, 10, Sort.Direction.ASC, "text");
// Top by title
Pageable pageable = new PageRequest(0, 10, Sort.Direction.ASC, "title");
// Top by publicationDate
Pageable pageable = new PageRequest(0, 10, Sort.Direction.ASC, "publicationDate");
반환해야 하는 레코드 수에 따라 10개를 바꿀 수 있습니다.
언급URL : https://stackoverflow.com/questions/27567351/get-last-records-ordered-by-date-on-spring-data
'codememo' 카테고리의 다른 글
| 범위() VS 셀() - 실행 시간 (0) | 2023.08.26 |
|---|---|
| iOS 4.0 iTunes Backup에서 Manifest.mbdb 파일을 구문 분석하는 방법 (0) | 2023.08.26 |
| Swift UIV뷰 배경색 불투명도 (0) | 2023.08.26 |
| Spring Rest Controller에서 Excel 파일을 다운로드하는 방법 (0) | 2023.08.26 |
| jQuery.ajax가 400개의 잘못된 요청을 반환합니다. (0) | 2023.08.21 |