2013-01-14 122 views
4

我有兩個實體問題Issue_Tracker。我使用的是hibernate 3.6和一對多關聯。如何爲帶有子查詢的查詢編寫HIbernate標準

Issue.java

public class Issue implements Serializable { 
     private Integer issue_id; 
     private String issue_description; 
     private Date issue_raised_date; 
     private Set<Issue_Tracker> issueTracker = new HashSet<Issue_Tracker>(0); 

     @OneToMany(fetch=FetchType.LAZY, mappedBy="issue_id") 
     public Set<Issue_Tracker> getIssueTracker() { 
     return issueTracker; 
} 

public void setIssueTracker(Set<Issue_Tracker> issueTracker) { 
    this.issueTracker = issueTracker; 

Issue_Tracker.java

public class Issue_Tracker implements Serializable 
{ 
    private Integer issue_id; 
    private String tracker_status; 
    private Timestamp tracked_time;** 

這是sql查詢,如何實現這一目標使用標準

SELECT i.issue_id, i.issue_description, 
     it.tracker_status, it.tracked_time 
FROM issues i 
LEFT JOIN (SELECT it.issue_id, it.tracker_status, it.tracked_time 
      FROM issue_tracker it 
      INNER JOIN (SELECT issue_id, MAX(tracked_time) tracked_time 
         FROM issue_tracker GROUP BY issue_id 
         ) A ON it.issue_id = A.issue_id AND it.tracked_time = A.tracked_time 
     ) it ON i.issue_id = it.issue_id 
WHERE i.status = "Escalate To"; 
+0

爲什麼要標準?您已經有SQL查詢,只需使用它。 –

+0

謝謝,這就是我所做的,但它有可能實現這一使用標準,因爲我是標準的@beginner級別,所以如此 –

回答

0

首先我建議你將Issue.issueTracker的名稱改爲Issue.issueTracker,因爲它是一個Set。當您查詢時,它使事情更容易閱讀。但是無所謂。

在Criteria API中我不認爲你可以直接翻譯這個SQL。你最好寫一份你想要的結果集的描述。你想最後跟蹤時間爲「升級到」狀態的所有問題?如果是這樣,這應該接近你想要的。

DetachedCriteria inner = DetachedCriteria.forClass(IssueTracker.class, "inner") 
     .setProjection(Projections.max("inner.tracked_time")); 

    Criteria crit = session.createCriteria(Issue.class, "issue"); 

    // Add the join with an ON clause (I am not sure why you need the LEFT JOIN) 
    crit.createAlias("issueTracker", "it", Criteria.LEFT_JOIN, 
     Subqueries.eqProperty("it.tracked_time", inner)); 

    // Specify the SELECT fields 
    crit.setProjections(Projections.projectionList() 
      .add(Projections.property("issue_id")) 
      // etc 
      .add(Projections.property("it.tracked_time")); 

    crit.add(Restrictions.eq("status", "Escalate To"); 

    List<Object[]> rows = crit.list();