2015-11-11 41 views
9

我有一個簡單的REST服務,它使用Spring引導CrudRepository訪問數據。使用Spring引導過濾數據CrudRepository

這個倉庫已經實現分頁和排序功能是這樣的:

public interface FlightRepository extends CrudRepository<Flight, Long> { 
    List<Flight> findAll(Pageable pageable); 
} 

調用它:

Sort sort = new Sort(direction, ordering); 
PageRequest page = new PageRequest(xoffset, xbase, sort); 

return flightRepo.findAll(page); 

我想還可以添加過濾這個倉庫(例如僅返回實體id > 13 AND id < 27 )。 CrudRepository似乎不支持這個功能。有什麼方法可以實現這一點,還是我需要使用不同的方法?

感謝您的任何提示!

回答

7

另一種解決方法是在上述註釋中提到的關於必須爲每個參數組合創建查詢方法的問題,可以通過Criteria API或使用QueryDSL。這就是第二點 - - 查詢定義一組固定的

的查詢方法爲大,因爲 的應用程序可能會增長數量:

這兩種方法在下面的響應關切,概述 標準。爲了避免這兩個缺點,如果你可以想出一組原子謂詞,你可以動態地合併 來建立你的查詢,這會不會很酷?

https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/

我覺得QueryDSL有點更容易使用。你只需要定義一個接口方法,然後你可以傳遞任何參數組合作爲謂詞。

例如

public interface UserRepository extends PagingAndSortingRepository<User, Long>, QueryDslPredicateExecutor<User> { 
    public List<User> findAll(Predicate predicate); 
} 

和查詢:

repository.findAll(QUser.user.address.town.eq("Glasgow").and(QUser.user.gender.eq(Gender.M))); 

repository.findAll(QUser.user.address.town.eq("Edinburgh")); 

repository.findAll(QUser.user.foreName.eq("Jim")); 

其中QUSER是QueryDSL自動生成的類。

http://docs.spring.io/spring-data/jpa/docs/current/api/index.html?org/springframework/data/jpa/repository/support/QueryDslRepositorySupport.html

http://www.querydsl.com/static/querydsl/2.1.0/reference/html/ch02s02.html

更新

從春數據模塊的高斯林版本現在有自動謂詞代從HTTP參數在Web應用程序的支持。

https://spring.io/blog/2015/09/04/what-s-new-in-spring-data-release-gosling#querydsl-web-support

0

聲明下面的功能在你的倉庫[EDITED]

Page<Flight> findByIdBetween(Long start, Long end, Pageable pageable) 

然後,你可以調用從倉庫的實例此功能。請參考spring-data reference以獲取更多信息。

+0

這可以結合Pageable嗎?我希望我可以在某個對象中指定它並將它傳遞給函數。當需要一些靈活性時(用戶可以指定要過濾的自定義字段,並且我將不得不爲每個可能的組合指定一個像這樣的函數...) – Smajl

+0

是的,您可以簡單地使用'List findByIdBetween(Long start ,長結束,可分頁)' – pezetem

+0

也建議您將擴展接口更改爲'PagingAndSortingRepository' .. –