使用PageImpl时,Spring JPA Criteria Builder出错

时间:2017-09-02 08:20:41

标签: spring hibernate jpa spring-boot hibernate-criteria

我在项目中使用Spring Boot和Spring数据。对于查询数据,我使用条件构建器来添加条件和顺序。源代码如下:

        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<TranxLog> query = builder.createQuery(TranxLog.class);
        Root r = query.from(TranxLog.class);
        Predicate predicate = builder.conjunction();
        predicate = builder.and(predicate, builder.greaterThanOrEqualTo(r.get("purchaseDate"), ParseUtils.strToDate(formModel.getSearchFromDate())));
        predicate = builder.and(predicate, builder.lessThanOrEqualTo(r.get("purchaseDate"), ParseUtils.strToDate(formModel.getSearchToDate())));
        predicate = builder.and(predicate, builder.equal(r.get("deleted"), "N"));
        predicate = builder.and(predicate, builder.equal(r.get("clientId"), user.getClientId()));
        query.where(predicate);
        query.orderBy(builder.desc(r.<Date>get("purchaseDate")), builder.asc(r.get("merchantId")),builder.asc(r.get("terminalId")),builder.asc(r.get("tranxLogId")));

        CriteriaQuery<TranxLog> select = query.select(query.from(TranxLog.class));
        TypedQuery<TranxLog> typedQuery = entityManager.createQuery(select);

        CriteriaQuery<Long> countQuery = builder.createQuery(Long.class);
        countQuery.select(builder.count(countQuery.from(TranxLog.class)));
        Long count = entityManager.createQuery(countQuery).getSingleResult();
        typedQuery.setFirstResult(page.getPageNumber() * page.getPageSize());
        typedQuery.setMaxResults(page.getPageSize());

        List<TranxLog> resultList = typedQuery.getResultList();
        return new PageImpl<TranxLog>(resultList, page, count);

这是hibernate查询

SELECT
            tranxlog1_.tranx_log_id AS tranx_log_id1_30_,
            tranxlog1_.account_id AS account_id2_30_,
            tranxlog1_.acq_iss AS acq_iss3_30_,
            tranxlog1_.acqbin AS acqbin4_30_
FROM
            tranx_log tranxlog0_,
            tranx_log tranxlog1_
        WHERE
                1 = 1
            AND
                tranxlog0_.purchase_date >=?
            AND
                tranxlog0_.purchase_date <=?
            AND
                tranxlog0_.deleted =?
            AND
                tranxlog0_.client_id =?
        ORDER BY
            tranxlog0_.purchase_date DESC,
            tranxlog0_.merchant_id ASC,
            tranxlog0_.terminal_id ASC,
            tranxlog0_.tranx_log_id ASC

查看查询,您会看到select来自tranxlog1,但是按tranxlog0排序,因此数据结果输入错误。

我不知道为什么它有from tranxlog0_ and tranxlog1_,因为如果我返回一个List,它就会完美,但Page有2个错误的顺序。

有什么想法吗?非常感谢。

0 个答案:

没有答案