2017-02-28 47 views
2

我的查詢看起來是這樣的 -如何將包含連接的JPAQuery對象轉換爲Predicate?

  @Override 
      public Page<Country> findPaginatedCountries(String country, Optional<String> status, Pageable pageable) { 

       QCountry qCountry= QCountry.someObject; 
       QActiveCountry qActiveCountry = QActiveCountry.activeCountry; 

       JPAQuery jpaQuery = new JPAQuery(entityManager); 

       QueryBase queryBase = jpaQuery.from(qCountry).innerJoin(qActiveCountry).fetch() 
         .where(qCountry.codeLeft.country.upper().eq(country.toUpperCase())) 
         .where(qCountry.codeRight.country.upper().eq(country.toUpperCase())); 



       if(status.isPresent()){ 
        queryBase = queryBase.where(qActiveCountry.id(qCountry.active.id)) 
          .where(qActiveCountry.status.upper().eq(status.get().toUpperCase())); 
       } 
.......} 

我可以寫一個謂詞代替,這將導致相同的響應?

Predicate predicate= qCountry.id.eq(qActiveCountry.id).and(qCountry.codeLeft.country.upper().eq(country.toUpperCase())).and(qCountry.codeRight.country.upper().eq(country.toUpperCase())); 

回答

1

是的,你可以。似乎你正在使用Spring Data。只要創建一個新的存儲庫界面,或QueryDslPredicateExecutor擴展現有JPARepository類型的接口,如:

@Repository 
public interface CountryRepository extends JpaRepository<Country, Long>, 
QueryDslPredicateExecutor<Country> 

現在,你可以通過你的謂語,如:

Predicate countryExpression= qCountry.id.eq(qActiveCountry.id).and(qCountry.codeLeft.country.upper().eq(country.toUpperCase())).and(qCountry.codeRight.country.upper().eq(country.toUpperCase())); 
CountryRepository.findAll(countryExpression, pageable); 
相關問題