Nhibernate,HQL通过右表列保持连接顺序

时间:2012-01-06 07:54:55

标签: nhibernate

是否可以进行左连接,但是使用hql?

按右表中的列排序

例如,我们在域中有这些类:

public class SomeDocument
{
    public virtual int Id { get; set; }
    public virtual DocumentPart Part1 { get; set; }
    public virtual DocumentPart Part2 { get; set; }
}

public class DocumentPart
{
   public virtual int Id { get; set; }
   public virtual string Content { get; set; }
}

Part1和Part2属性可以为空。

SQL:

create table SomeDocument
  (
    Id number(*, 0) not null,
    DocumentPart1_ID NUMBER,
    DocumentPart2_ID NUMBER
  );

create table DocumentPart
  (
    Id number(*, 0) not null,
    Content nvarchar2(250) not null
  );

映射:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Testapp.domain" namespace="Testapp.domain.model">
  <class name='SomeDocument' table='SomeDocument' lazy="false">
    <many-to-one name='Part1' class="Testapp.domain.model.DocumentPart, Testapp.domain" lazy="false" column='DocumentPart1_ID' cascade="save-update" />
    <many-to-one name='Part1' class="Testapp.domain.model.DocumentPart, Testapp.domain" lazy="false" column='DocumentPart2_ID' cascade="save-update" />
  </class>
</hibernate-mapping>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Testapp.domain" namespace="Testapp.domain.model">
  <class name='DocumentPart' table='DocumentPart' lazy="false">
    <property name='Content' column='Content' not-null="true"/>
  </class>
</hibernate-mapping>

现在如果我尝试按SomeDocuments订购Part1.Content

UnitOfWork.CurrentSession
          .CreateQuery("from SomeDocument doc order by doc.Part1.Content")
          .List<SomeDocument>();

我只会获得DocumentPart1_ID不为空的行。 NHibernate会像这样生成SQL:

select * from 
SomeDocument doc, 
DocumentPart docPart,
where doc.DocumentPart1_ID = docPart.Id
order by docPart.Content

但我想要的是这样的:

select * from 
SomeDocument doc
left join DocumentPart docPart on doc.DocumentPart1_ID = docPart.Id
order by docPart.Content

我的数据库是Oracle Database 11g企业版11.1.0.7.0 - 64位

1 个答案:

答案 0 :(得分:1)

明确指定要在查询中使用左连接的nhibernate。

select doc from SomeDocument doc left join doc.Part1 part order by part.Content

如果从查询中省略select doc,NHibernate将选择所有实体,在这种情况下,它将等同于编写select doc, part。这将创建一个object[]类型的结果集,表示SomeDocument, DocumentPart的元组。