2017-08-07 33 views
1

我看到Selecting from Multiple Tables in Spring Data已經有了多表的解決方案。 我想知道是否有可能在Spring JPA/DATA中同時編寫具有可分頁和排序功能的表的自定義查詢。在Spring JPA中使用Pageable和Sorting從多個表中選擇

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

顯示你的模型... – Cepr0

+0

這是一個普遍的問題。爲什麼需要模型? – linc01n

+0

讓我們來幫助你。查詢和查詢方法取決於您的模型... – Cepr0

回答

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

UPDATE

排序也可以正常使用。 只需創建一個排序對象,指定方向並存檔名稱(從投影):

Sort sort = new Sort(Sort.Direction.ASC, "serviceName"); 
userServiceRepo.getServiceRating(1L, new PageRequest(0, 10, sort)); 
+0

謝謝@ Cepr0! – linc01n

+0

@ linc01n'謝謝'等於'接受/提升'這裏的答案。請不要忘記這麼做... – Cepr0

+0

感謝提醒我。 – linc01n