简体   繁体   中英

NHibernate Join on multiple columns

I am using NHibernate 2.2 and I want to make a simple join over tow columns in the XML-mapping.

Let's say I have two tables:

在此处输入图片说明

Now I want a simple select and join over the two tables:

SELECT t1.*, t2.ProductionDate
FROM table1
JOIN table2 t2 ON t1.Name = t2.Name AND t1.Price = t2.Price

How can I do this in NHibernate with XML-mapping?

In XML mappings, you map the relations between your classes. Only if your classes have a relation like this:

  class Class1
  {
    public Class2 { get; set; }
  }

you can map this relation. BUT it usually needs to be related using primary keys. There is a way to map other properties as well using property-ref , but there it starts to be weird, especially when multiple columns come in.

I doubt that you have such a relation in your classes anyway.

So the link should only be made within a query. It is similar to the way you do it in SQL. Note that "joins" in HQL are limited to real relations (as I have demonstrated above), not arbitrary property comparison (unlike SQL, where there is no difference).

HQL:

select c1.*, c2.ProductionDate
from Class1 c1, Class2 c2
where c1.Name = c2.Name and c1.Price = c2.Price

It is not possible with Criteria (unless using subqueries, but then you cannot return ProductionDate). There is no way to make it an outer join other than fall back to SQL.

Comment: You may think that NHibernate is not much of a help here. This is indeed the case. The reason is that NHibernate is an ORM and lets you implement your business logic in an object oriented way. The kind of relation you have here is not a typical object oriented relation. It's not the way how you usually deal with classes in a pure OO design.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM