Is it possible to make a left join, but order by a column in the right table using hql?
For example we have these classes in the domain:
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 and Part2 properties are nullable.
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
);
Mapping:
<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>
and now if I try to order SomeDocuments by Part1.Content:
UnitOfWork.CurrentSession
.CreateQuery("from SomeDocument doc order by doc.Part1.Content")
.List<SomeDocument>();
I will get only rows where DocumentPart1_ID is not null. NHibernate will generate SQL like this:
select * from
SomeDocument doc,
DocumentPart docPart,
where doc.DocumentPart1_ID = docPart.Id
order by docPart.Content
but what I want is something like this:
select * from
SomeDocument doc
left join DocumentPart docPart on doc.DocumentPart1_ID = docPart.Id
order by docPart.Content
My database is Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 – 64bit
Explicitly specify to nhibernate that you want a left join in the query.
If you leave out the
select docfrom the query, NHibernate will select all the entities, in this case it would be equivalent to writingselect doc, part. This would create a result set of typeobject[]that represents a tuple ofSomeDocument, DocumentPart.