tags:

views:

49

answers:

2

I have the following hql. This works fine if i don't try and include the "OrderItem" entity. I understand that there is no "on" clause in hql. What is the best way to join orderItem

 var hql = new StringBuilder();
    hql.Append(
    @"select p.Id, p.Name, p.Description, p.ProductKey, p.CustomerSku, p.ImageUrl, p.ImageThumbUrl, p.ImageLargeUrl,COUNT(oi.Quantity) as quantity 
            from ProductCampaign pc
            join pc.Product p 
            left join OrderItem oi with oi.Product.Id = p.Id
            where pc.Campaign.Id = :CampaignId ");

   hql.Append(@"group by p.Id, p.Name, P.Description, p.ProductKey, p.CustomerSku, p.ImageUrl, p.ImageThumbUrl, p.ImageLargeUrl ");
   var results = _session.CreateQuery(hql.ToString());
   results.SetParameter("CampaignId", campaignId);

Here is the sql i wish to achieve.

select p.Id, p.name, p.description, p.ProductKey, p.CustomerSku, p.ImageUrl, p.ImageThumbUrl, p.ImageLargeUrl,COUNT(oi.Quantity) as quantity from ProductCampaign pc
inner join Products p on pc.ProductId = p.Id
left join orderitems oi on pc.ProductId = oi.ProductId
where pc.CampaignId = 1
group by  p.Id, p.name, p.description, p.ProductKey, p.CustomerSku, p.ImageUrl, p.ImageThumbUrl, p.ImageLargeUrl
A: 

Try using a where instead of a with:

select p.Id, p.Name, p.Description, p.ProductKey, p.CustomerSku, p.ImageUrl, p.ImageThumbUrl, p.ImageLargeUrl, COUNT(oi.Quantity) as quantity 
            from ProductCampaign pc
            join pc.Product p             
            left join OrderItem oi where oi.Product.Id = p.Id 
            and pc.Campaign.Id = :CampaignId

NHibernate Non-Mapped Joins

Rafael Belliard
That won't work. The syntax for left join is still incorrect.
Diego Mijelshon
A: 

In order to use HQL left joins, you must map the relationships, as a path from one of the "from" tables is expected (see 13.3. Associations and joins)

Try changing OrderItems.Product id to a proper Product many-to-one, and use a right join.

As a side note, your entity names shold be singular. It looks like you are just replicating your table structure as classes.

Diego Mijelshon