gpt4 book ai didi

java - 如何为带有子选择的查询编写 HIbernate 条件

转载 作者:搜寻专家 更新时间:2023-11-01 03:54:02 25 4
gpt4 key购买 nike

我有两个实体 IssueIssue_Tracker。我正在使用 hibernate 3.6 和一对多关联。

问题.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";

最佳答案

首先,我建议您将容易混淆的 Issue.issueTracker 名称更改为 Issue.issueTrackers,因为它是一个 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();

关于java - 如何为带有子选择的查询编写 HIbernate 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14314052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com