Spring JPA中具有分页和排序功能的多个表中的选择

lin*_*01n 2 spring jpa spring-data-jpa

我看到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= ?
;
Run Code Online (Sandbox Code Playgroud)

感谢您的帮助。

Cep*_*pr0 5

排序功能尚有疑问,但可以使用分页。

假设我们有:

@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;   

    //...
}
Run Code Online (Sandbox Code Playgroud)

然后我们创建一个投影:

public interface ServiceRating {
    Long getServiceId();
    String getServiceName();
    Long getRatingId();
}
Run Code Online (Sandbox Code Playgroud)

然后创建一个支持分页的查询方法:

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);
}
Run Code Online (Sandbox Code Playgroud)

(由于此查询不包含分组,因此不必使用其他分组countQuery(请参阅的参数@Query)。

测试:

Page<ServiceRating> pages = userServiceRepo.getServiceRating(1L, new PageRequest(0, 10));
assertThat(pages.getContent()).hasSize(10));
Run Code Online (Sandbox Code Playgroud)

更新

排序也很完美。只需创建一个Sort对象,指定方向和文件名(来自投影):

Sort sort = new Sort(Sort.Direction.ASC, "serviceName");
userServiceRepo.getServiceRating(1L, new PageRequest(0, 10, sort));
Run Code Online (Sandbox Code Playgroud)