仅使用一个SQL查询来获取页面中的结果

时间:2018-10-10 18:53:12

标签: java sql hibernate jpa hql

我想将XML响应分成多个页面,因为我有太多的XML项目无法发送回去。我尝试过:

XML请求:

<?xml version="1.0" encoding="UTF-8"?>
<reconcile>
  <start_date>2018-04-08T11:02:44</start_date>
  <end_date>2019-10-08T11:02:44</end_date>
  <page>1</page>
</reconcile>

JAXB:

@XmlRootElement(name = "reconcile")
@XmlAccessorType(XmlAccessType.FIELD)
public class Reconcile {

    @XmlElement(name = "start_date")
    @XmlJavaTypeAdapter(LocalDateTimeXmlAdapter.class)
    private LocalDateTime start_date;
    @XmlElement(name = "end_date")
    @XmlJavaTypeAdapter(LocalDateTimeXmlAdapter.class)
    private LocalDateTime end_date;
    @XmlElement(name = "page")
    private String page;
    ...../// getters and setters
}

SQL查询:

public List<PaymentTransactions> transactionsByDate(LocalDateTime start_date, LocalDateTime end_date, Merchants merchant, Terminals terminal) throws Exception {

        String hql = "select e from " + PaymentTransactions.class.getName() + " e where e.created_at >= ? and e.created_at <= ?";
        Query query = entityManager.createQuery(hql).setParameter(0, start_date).setParameter(1, end_date);
        List<PaymentTransactions> paymentTransactions = (List<PaymentTransactions>) query.getResultList();
        return paymentTransactions;
}

返回XML:

 List<PaymentTransactions> paymentTransactions = transactionsService
                    .transactionsByDate(reconcile.getStart_date(), reconcile.getEnd_date(), merchant, terminal);

            ReconcilePaymentResponses pr = new ReconcilePaymentResponses();
            pr.setPage("1");
            pr.setPages_count("10");
            pr.setPer_page("4");
            pr.setTotal_count(String.valueOf(paymentTransactions.size()));

            for (int e = 0; e < paymentTransactions.size(); e++) {
                PaymentTransactions pt = paymentTransactions.get(e);

                ReconcilePaymentResponse obj = new ReconcilePaymentResponse();
                obj.setTransaction_type(pt.getType());
                pr.getPaymentResponse().add(obj);
            }

            return pr;

XML响应:

<?xml version='1.0' encoding='UTF-8'?>
<payment_responses page="1" per_page="4" total_count="5" pages_count="10">
    <payment_response>
        <transaction_type>Type</transaction_type>
    </payment_response>
    <payment_response>
        <transaction_type>Type</transaction_type>
    </payment_response>
    <payment_response>
        <transaction_type>Type</transaction_type>
    </payment_response>
    .........
</payment_responses>

我想以某种方式将<payment_response>....</payment_response>分成页面以减少内存开销。例如,当我发送1时,我想返回前10个。

当前建议使用2条SQL查询。我只想使用一个SQL查询:

我创建了一个新的PageInfo类来存储页面信息。添加了一个查询以获取总行数并设置我的page_info。然后限制查询结果的数量。最后,将值设置为ReconcilePaymentResponse。

Class PageInfo {
    int current_page;
    int page_count;
    int per_page;
    int total_page;

    //constructor
    public PageInfo(int current_page, int page_count, int per_page) {
        //assign them
    }
    //getters
    //setters
}

SQL查询:

public List<PaymentTransactions> transactionsByDate(LocalDateTime start_date, LocalDateTime end_date, Merchants merchant, Terminals terminal,
    PageInfo pageInfo) throws Exception {

    //figure out number of total rows
    String count_hql = "select count(*) from " + PaymentTransactions.class.getName() + " e where e.created_at >= ? and e.created_at <= ?";
    Query count_query = entityManager.createQuery(count_hql);
    int count = countQuery.uniqueResult();

    //figure out total pages
    int total_page = (int)Math.ceil(count/(double)pageInfo.getPerPage());
    pageInfo.setTotal_Page(total_page);

    String hql = "select e from " + PaymentTransactions.class.getName() + " e where e.created_at >= ? and e.created_at <= ?";
    Query query = entityManager.createQuery(hql)
        //set starting point
        .setFirstResult((pageInfo.getCurrentPage()-1) * pageInfo.getPerPage)
        //set max rows to return
        .setMaxResults(pageInfo.getPerPage)
        .setParameter(0, start_date).setParameter(1, end_date);
    List<PaymentTransactions> paymentTransactions = (List<PaymentTransactions>) query.getResultList();
    return paymentTransactions;
}

返回XML:

        //initialize PageInfo with desired values
        PageInfo page_info = new PageInfo(1,10,4);
        List<PaymentTransactions> paymentTransactions = transactionsService
            .transactionsByDate(reconcile.getStart_date(), reconcile.getEnd_date(), merchant, terminal, page_info);  // pass in page_info

        ReconcilePaymentResponses pr = new ReconcilePaymentResponses();
        pr.setPage(page_info.getCurrentPage());
        pr.setPages_count(page_info.getPageCount());
        pr.setPer_page(page_info.getPerPage());
        pr.setTotal_count(String.valueOf(paymentTransactions.size()));

        for (int e = 0; e < paymentTransactions.size(); e++) {
            PaymentTransactions pt = paymentTransactions.get(e);

            ReconcilePaymentResponse obj = new ReconcilePaymentResponse();
            obj.setTransaction_type(pt.getType());
            pr.getPaymentResponse().add(obj);
        }

        return pr;

如何仅使用一个SQL查询?

3 个答案:

答案 0 :(得分:0)

如果您想要总计数(计算总页数),那么您需要两个查询,则无法在休眠中解决它(我说这是因为您可以(虽然不确定)可以构建讨厌的SQL查询,您可以在其中将计数查询与选择查询合并,但这确实不值得,即使优化也不会这样做。

请参阅:https://www.baeldung.com/hibernate-pagination

话虽如此,如果您可以选择的话,则可以切换为没有确定的页面数(您的UI可以是虚拟滚动,也可以是[Previous / Next]而无需结束。

答案 1 :(得分:0)

Hibernate中还有一个选项可以通过单个查询执行此操作,但它不是JPA的一部分。

ScrollableResults在后台处理开放的JDBC ResultSet,然后您可以前进到最后一行。

例如,从JPA查询开始:

    ScrollableResults scrollableResults = jpaQuery.unwrap(org.hibernate.query.Query.class).scroll();
    scrollableResults.scroll(offset);
    // Extract rows ...
    while (scrollableResults.next()) {
        PaymentTransactions paymentTransactions = (PaymentTransactions) scrollableResults.get(0);
        // ... process and check count
    }
    // Find the last row
    scrollableResults.last();
    int totalCount = scrollableResults.getRowNumber() + 1;

请注意,这不一定比两个查询选项更有效-尤其是对于大量结果。

答案 2 :(得分:0)

快速选项:

您可以使用 COUNT(*)OVER()作为结果集中的最后一列,它将存储没有限制的情况下将返回的总行数:

SELECT col1, col2, col3, COUNT(*) OVER() as Total
FROM yourTable 
LIMIT 0,10;

这可能不是最优雅的解决方案,因为您会在所有行中重复此数字,但它可以解决您的问题,并且应该表现出色。

优雅选项:

使用带有输出参数的存储过程-该过程将包含2个查询,但是您可以对存储过程进行一次优雅的调用。