[英]Use only one SQL query to get result in pages
我想將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查詢?
如果您想要總計數(計算總頁數),那么您需要兩個查詢,則無法在休眠中解決它(我說這是因為您可以(雖然不確定)可以在其中構建討厭的SQL查詢)將count查詢與select查詢合並,但這確實不值得,即使是優化也不會這樣做)。
參見: https : //www.baeldung.com/hibernate-pagination
也就是說,如果您可以選擇,則可以切換為沒有確定的頁面數(您的UI可以是虛擬滾動,也可以是[Previous / Next]而無需結束)。
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;
請注意,這不一定比兩個查詢選項更有效-特別是對於大量結果。
快速選項:
您可以將COUNT(*)OVER()用作結果集中的最后一列,它將存儲沒有限制的情況下將返回的總行數:
SELECT col1, col2, col3, COUNT(*) OVER() as Total
FROM yourTable
LIMIT 0,10;
這可能不是最優雅的解決方案,因為您會在所有行中重復此數字,但是它可以解決您的問題,並且應該表現出色。
優雅的選擇:
使用帶有輸出參數的存儲過程-該過程將包含2個查詢,但您將對存儲過程進行一次優雅的調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.