我有两个实体Issue
和Issue_Tracker
。
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;
当我离开加入表时,我使用查询得到以下数据:
SELECT issues.issue_id,
issues.issue_description,
issue_tracker.tracker_status,
issue_tracker.tracked_time
FROM issues
LEFT JOIN issue_tracker on issues.issue_id = issue_tracker.issue_id
WHERE issues.status = "Escalate To"
,输出
issue_id tracker_status tracked_time
123 Assigned 1/8/2013 11:44 //1st entry
123 Assigned 1/9/2013 11:45
123 Completed 1/10/2013 12:52 // last entry
32 Assigned 1/9/2013 16:46 //1st entry
32 Assigned 1/10/2013 18:46 //last entry
33 Assigned 1/9/2013 16:47 //1st entry
33 Cancel 1/9/2013 17:49 //last entry
现在当我使用标准进行这些连接时,我得到了这些结果
issue_id tracker_status tracked_time
123 Assigned 1/8/2013 11:44 //1st entry of issue_id 123
32 Assigned 1/9/2013 16:46
33 Assigned 1/9/2013 16:47
使用以下标准
Criteria criteria = session.createCriteria(Issue.class);
criteria.setFirstResult(from);
criteria.setMaxResults(size);
criteria.setFetchMode("Issue.issueTracker",FetchMode.JOIN);
criteria.add(Restrictions.eq("status", "Escalate To"));
现在预期的输出是
issue_id tracker_status tracked_time
123 Completed 1/10/2013 12:52 // last entry
32 Assigned 1/10/2013 18:46 //last entry
33 Cancel 1/9/2013 17:49 //last entry
如何实现这一目标,自从过去三天我就被困在这里,任何帮助都会很棒,是不是因为这条线我正在尝试一对多的映射
private Set<Issue_Tracker> issueTracker = new HashSet<Issue_Tracker>(0);
因为设置不允许重复值,如果是,那么可能的方法是什么。
答案 0 :(得分:1)
试试这个:
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";