如何将涉及连接的JPAQuery对象转换为Predicate?

时间:2017-02-28 05:50:53

标签: querydsl

我的查询看起来像这样 -

            @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 个答案:

答案 0 :(得分:2)

是的,你可以。似乎您正在使用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);