給定模型Activity,其中包含具有報告類型(一對多)模型的包。我想獲得所有活動的列表,其中包含每項活動的報告數量。這兩個查詢不會導致任何好處,計數器始終爲1(這是錯誤的):HQL幫助:總計(計數)
select act, (select count(r) from act.Reports r) from Activity act
或者:
select act, count(elements(act.Reports)) from Activity act group by act.ActivityId, act.Title
是否有可能寫HQL合適的查詢來解決這個簡單的任務?
Thx for any tipps! sl3dg3
編輯: 映射後。活動:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class
name="Core.Models.Config.Activity, Core"
table="Activity"
>
<!-- primary key -->
<id name="ActivityId" type="Int32" unsaved-value="0" access="property">
<column name="ActivityId" not-null="true"/>
<generator class="identity" />
</id>
<!-- Properties -->
<many-to-one name="Title" fetch="join" cascade="all"/>
<!-- One-To-Many Reports -->
<bag name="Reports" inverse="true" fetch="join">
<key column="ReportId" />
<one-to-many class="Core.Models.Report"/>
</bag>
</class>
</hibernate-mapping>
映射報告:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class
name="Core.Models.Report, Core"
table="Report"
>
<!-- primary key -->
<id name="ReportId" type="Int32" unsaved-value="0" access="property">
<column name="ReportId" not-null="true"/>
<generator class="identity" />
</id>
<!-- Properties (shortened - there are more many-to-one and one bag -->
<property name="Created" />
<many-to-one name="Activity" column="ActivityId" />
</class>
類的活動:
public class Activity
{
public Activity()
{
Title = new Translation();
}
public virtual int ActivityId { get; set; }
public virtual Translation Title { get; set; }
public virtual IList<Report> Reports { get; set; }
}
類報告:
public class Report
{
/// <summary>
/// HNIBERNATE ONLY
/// </summary>
public Report()
{ }
/// <summary>
/// Init Report
/// </summary>
public Report(User author)
{
// ... Shortened
Activity = new Activity();
}
public virtual Activity Activity { get; set; }
}
至於第一個查詢:不幸的是,我仍然得到每個活動一(並且只有一個)報告作爲計數。至於第二個查詢,這正是我上面寫的 - 我的也是正確的,但沒有很好格式化;-) – sl3dg3 2011-03-22 16:39:33
@ sl3dg3對不起,我沒有正確測試這些。我只是在測試環境中測試了這些查詢,並且它們運行良好。你可以發佈映射和類定義嗎? – 2011-03-22 22:42:38
@Florian我在原帖中添加了映射... – sl3dg3 2011-03-23 08:35:26