给定模型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