NHibernate HQL: left outer join with “with” clause

2020-03-02 06:11发布

问题:

In an EAV system, I have a mapping that looks like this:

<class name="Record">
   <map name="Values" table="RecordFieldValue">
      <key column="RecordFK">
      <index column="FieldFK">
      <element column="Value">
   </map>
</class>

I would like to select some Records, ordered by the value of each Record for a specific Field. However, note that not all Records will actually have a Value for that Field. In this case, the record should still be fetched and sorted with a null value.

The desired SQL would look like this:

select rec.*, val.Value
from Record rec
left outer join RecordFieldValue val
on val.RecordFK = rec.PK and val.FieldFK = :field
order by val.Value

After a lot of digging, I found that the correct way to modify the "on" clause of the left join in HQL is with the "with" keyword (see https://nhibernate.jira.com/browse/NH-514). So I tried this HQL:

from Record rec
left join rec.Values vals with index(vals) = :field
order by vals

Unfortunately, this produces the following error: with-clause expressions did not reference from-clause element to which the with-clause was associated. So I tried this instead:

from Record rec
left join rec.Values vals with index(rec.Values) = :field
order by vals

But that produced a new error: with clause can only reference columns in the driving table.

Any ideas on how to get this work? Thanks.

-- Brian

回答1:

This works:

from Record rec
left join rec.Values vals with vals.index = :field
order by vals

Not exactly intuitive or well-documented, but it gets the job done.