EclipseLink JPA:我可以从一个构建器运行多个查询吗?

2024-02-21

我有一个构建和运行条件查询的方法。该查询执行我想要的操作,特别是它根据用户输入过滤(和排序)记录。

此外,查询大小仅限于屏幕上的记录数。这很重要,因为数据表可能非常大。

但是,如果应用过滤器,我想计算在查询不受限制的情况下将返回的记录数。因此,这意味着运行两个查询:一个用于获取记录,另一个用于计算整个集合中的记录。它看起来像这样:

public List<Log> runQuery(TableQueryParameters tqp) {

    // get the builder, query, and root

    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Log> query = builder.createQuery(Log.class);
    Root<Log> root = query.from(Log.class); 

    // build the requested filters

    Predicate filter = null;
    for (TableQueryParameters.FilterTerm ft : tqp.getFilterTerms()) {

       // this section runs trough the user input and constructs the 
       // predicate

    }
    if (filter != null) query.where(filter);

    // attach the requested ordering

    List<Order> orders = new ArrayList<Order>();
    for (TableQueryParameters.SortTerm st : tqp.getActiveSortTerms()) {

        // this section constructs the Order objects

    }
    if (!orders.isEmpty()) query.orderBy(orders);        

    // run the query

    TypedQuery<Log> typedQuery = em.createQuery(query);
    typedQuery.setFirstResult((int) tqp.getStartRecord());
    typedQuery.setMaxResults(tqp.getPageSize());
    List<Log> list = typedQuery.getResultList();

    // if we need the result size, fetch it now

    if (tqp.isNeedResultSize()) {
        CriteriaQuery<Long> countQuery = builder.createQuery(Long.class);
        countQuery.select(builder.count(countQuery.from(Log.class)));
        if (filter != null) countQuery.where(filter);
        tqp.setResultSize(em.createQuery(countQuery).getSingleResult().intValue());
    }

    return list;
}

因此,我在同一个 CriteriaBuilder 上调用 createQuery 两次,并在它们之间共享 Predicate 对象(过滤器)。当我运行第二个查询时,我有时收到以下消息:

异常 [EclipseLink-6089](Eclipse 持久性服务 - 2.2.0.v20110202-r8913): org.eclipse.persistence.exceptions.QueryException 异常 描述:表达式未正确初始化。仅有的 应将单个 ExpressionBuilder 用于查询。并联用 表达式,查询类必须提供给ExpressionBuilder 构造函数,并且查询的 ExpressionBuilder 必须始终位于 表达式的左侧。表达式:[ 基数 com.myqwip.database.Log] 查询:ReportQuery(referenceClass=Log ) at org.eclipse.persistence.exceptions.QueryException.noExpressionBuilderFound(QueryException.java:874) 在 org.eclipse.persistence.expressions.ExpressionBuilder.getDescriptor(ExpressionBuilder.java:195) 在 org.eclipse.persistence.internal.expressions.DataExpression.getMapping(DataExpression.java:214)

有人可以告诉我为什么这个错误间歇性地出现,以及我应该做什么来解决这个问题?


对问题的简短回答:是的,可以,但只能按顺序进行。

在上面的方法中,您开始创建第一个查询,然后开始创建第二个查询,执行第二个查询,然后执行第一个查询。

我有同样的问题。不知道为什么会断断续续的难受。

换句话说,您开始创建第一个查询,在完成之前,您开始创建并执行另一个查询。

Hibernate 不会抱怨,但 eclipselink 不喜欢它。

如果您只是从查询计数开始,执行它,然后创建并执行另一个查询(通过将其拆分为 2 个方法来完成),eclipselink 不会抱怨。

see https://issues.jboss.org/browse/SEAMSECURITY-91 https://issues.jboss.org/browse/SEAMSECURITY-91

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

EclipseLink JPA:我可以从一个构建器运行多个查询吗? 的相关文章

随机推荐