复杂的SQL查询到NHibernate DetachedCriteria或HQL

时间:2010-07-19 11:44:33

标签: sql nhibernate detachedcriteria

我有以下SQL查询返回我需要的结果:

SELECT     
Person.FirstName,Person.LastName,OrganisationUnit.Name AS UnitName, RS_SkillsArea.Name AS SkillsArea, Activity.Name AS ActivityName, Activity.CLASS, Activity.StartsOn, Activity.EndsOn, 

SUM(ActivityCost.CostAmount) / 

NULLIF(
 (
  SELECT COUNT(Registration.ActivityId) FROM         
  Registration INNER JOIN AttemptResultsSummary ON Registration.CurrentResultId = AttemptResultsSummary.AttemptResultsSummaryId AND 
  Registration.RegistrationId = AttemptResultsSummary.RegistrationId
  WHERE     (Registration.Status = 1) AND (Registration.ActivityId = Activity.ActivityId) 
  AND (AttemptResultsSummary.AttendanceStatus <> 1)
 ) 
 ,0) 
 AS IndividualCost

 FROM         Registration AS Registration_1 INNER JOIN
                      Activity ON Registration_1.ActivityId = Activity.ActivityId INNER JOIN
                      Person ON Registration_1.PersonId = Person.PersonId INNER JOIN
                      OrganisationUnit ON Person.OrganisationUnitId = OrganisationUnit.OrganisationUnitId INNER JOIN
                      AttemptResultsSummary ON Registration_1.CurrentResultId = AttemptResultsSummary.AttemptResultsSummaryId AND 
                      Registration_1.RegistrationId = AttemptResultsSummary.RegistrationId AND Activity.ActivityId = AttemptResultsSummary.ActivityId AND 
                      Person.PersonId = AttemptResultsSummary.PersonId INNER JOIN 
                      ActivityCost ON Activity.ActivityId = ActivityCost.ActivityId LEFT OUTER JOIN
                          (SELECT     Category.Name, Category.CategoryId
                            FROM          Category INNER JOIN
                                                   CategoryGroup ON Category.[Group] = CategoryGroup.CategoryGroupId
                            WHERE      (CategoryGroup.Name = N'Skills Area')) AS RS_SkillsArea INNER JOIN
                      ActivityInCategory ON RS_SkillsArea.CategoryId = ActivityInCategory.CategoryId ON Activity.ActivityId = ActivityInCategory.ActivityId

AND AttemptResultsSummary.AttendanceStatus <> 1



GROUP BY RS_SkillsArea.Name, Person.FirstName,Person.LastName,Activity.Name, Activity.CLASS, Activity.StartsOn, Activity.EndsOn, Activity.ActivityId, OrganisationUnit.Name, 
                      AttemptResultsSummary.CompletionStatus, AttemptResultsSummary.AttendanceStatus

HAVING AttemptResultsSummary.AttendanceStatus <> 1

基本上有没有办法使用DetachedCriteria或HQL对实体做同样的事情而不是直接SQL?

这两个挑战是:

  1. 每行的成本计算查询。

  2. 派生表连接(由于此值可能不存在,因此需要为外连接)

  3. 我很感激任何指针。我宁愿不使用SQL,因为基础设施的变化和(缺乏)重构支持的问题

1 个答案:

答案 0 :(得分:2)

查看官方HQL示例@ http://docs.jboss.org/hibernate/stable/core/reference/en/html/queryhql.html#queryhql-examples

在我看来,'派生连接'将更容易使用HQL。

在性能方面,我的第一个开始是使用您的首选探查器来捕获使用本机SQL的成本,然后使用NHProf在NHibernate上花费多少。