排序功能存在問題,但可以使用分頁功能。
假設我們有:
@Entity
public class Service {
@Id
private Long id;
private String name;
//...
}
@Entity
public class UserService {
@Id
private Long id;
@ManyToOne
User user;
@ManyToOne
Service service;
@ManyToOne
Rating rating;
//...
}
然後我們創建一個投影:
public interface ServiceRating {
Long getServiceId();
String getServiceName();
Long getRatingId();
}
,然後創建一個查詢方法支持分頁:
public interface UserServiceRepo extends CrudRepository<UserService, Long> {
@Query("select s.id as serviceId, s.name as serviceName, us.rating.id as ratingId from UserService us join us.service s where us.user.id = ?1")
Page<ServiceRating> getServiceRating(Long userId, Pageable pageable);
}
(由於此查詢不不包含分組,不需要額外使用countQuery
(請參閱參數@Query
))。
測試:
Page<ServiceRating> pages = userServiceRepo.getServiceRating(1L, new PageRequest(0, 10));
assertThat(pages.getContent()).hasSize(10));
UPDATE
排序也可以正常使用。 只需創建一個排序對象,指定方向並存檔名稱(從投影):
Sort sort = new Sort(Sort.Direction.ASC, "serviceName");
userServiceRepo.getServiceRating(1L, new PageRequest(0, 10, sort));
顯示你的模型... – Cepr0
這是一個普遍的問題。爲什麼需要模型? – linc01n
讓我們來幫助你。查詢和查詢方法取決於您的模型... – Cepr0