我看到Selecting from Multiple Tables in Spring Data已经有了多个表的解决方案。 我想知道是否可以在Spring JPA / DATA中同时编写具有可分页和排序功能的表的自定义查询。
SELECT s.service_id, s.name, us.rating_id
FROM services s,
ratings r,
user_services us
where
us.service_id = s.service_id and
us.rating_id = r.rating_id and
us.user_id= ?
;
先谢谢你的帮助。
答案 0 :(得分:1)
排序功能有问题,但可以使用分页。
假设我们有:
@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));
<强>更新强>
排序也很完美。 只需创建一个Sort对象,指定方向和字段名称(来自投影):
Sort sort = new Sort(Sort.Direction.ASC, "serviceName");
userServiceRepo.getServiceRating(1L, new PageRequest(0, 10, sort));