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

How can I convert JPAQuery object, which involves joins, to 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()));

是的,你可以。似乎您正在使用 Spring 数据。只需创建一个新的存储库接口,或使用 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);