2011-01-07 25 views
2

有兩個表格,報告和報告評論。每個報告評論都是通過外鍵分配給報告的,因此報告具有零到多個報告評論。
如果我需要一個列表,這給了我與每一份報告的評論中的相應號碼的所有報告,我會做以下(含SQL):我如何檢索entite + JPA/Hibernate的附加值列表?

SELECT r.*, c.cnt 
FROM report r 
LEFT JOIN (
    SELECT ir.id AS report_id, COUNT(ic.id) AS cnt 
    FROM report ir 
    INNER JOIN reportcomment ic ON ir.id = ic.report_id 
    GROUP BY ir.id 
) c ON c.report_id = r.id 

我想和JPA來獲取這樣的列表/休眠並將c.cnt存儲在我的Report實體對象中。 這怎麼可能實現?

回答

2

我覺得simpliest的辦法是在Report創建一個短暫的領域,並通過轉換相應的查詢manully返回的元組,這樣的事情:

List<Object[]> tuples = em.createQuery(
    "SELECT r, COUNT(c) " + 
    "FROM ReportComment c RIGHT JOIN c.report r" + 
    "GROUP BY r.id, ...").getResultList(); 

List<Report> reports = new ArrayList<Report>(); 
for (Object[] tuple: tuples) { 
    Report r = (Report) tuple[0]; 
    r.setCommentCount((Long) tuple[1]); 
    reports.add(r); 
} 
+0

看起來很有前途 - 我會盡力的! – Zeemee 2011-01-10 07:58:36

0

我敢肯定有很多的原因,什麼你的工作是不是這樣設計的。可能有更多原因讓你不想重新設計它。我知道這可能不是回答你的問題在所有的,但如果我是你,我有時間,我不得不傾斜度,使這樣的事情:

public class Comment { 
... 
List<CommentReport> commentReports = new ArrayList<CommentReport>(); 

@OneToMany(mappedBy="comment") 
public List<CommentReports> getCommentReports() { 
    return commentReports; 
} 

public void setCommentReports(List<CommentReport> commentReports) { 
    this.commentReports = commentReports; 
} 

@Transient 
public int countReports() { 
    return commentReports.size(); 
} 

我已經提出了什麼假設你在Web應用程序中工作,並正在使用某種開放會話的視圖。否則,你可能不得不熱切地提取那些可能不好的評論。

但是,如果你打算使用休眠,爲什麼不去更進一步?它的目的是抽象和隱藏數據庫代碼,我所提供的是朝這個方向邁出的一步。

+0

zmf,你的方法當然是最明顯的方法,如果我的例子不會被簡化:)。現實是,沒有「報告評論」,子選擇本身返回「報告」。我不想要一個持久的關係。 但無論如何感謝您的補充。 – Zeemee 2011-01-10 06:39:38