views:

63

answers:

2

Here is roughly our data model (the entity names are fake and only for example purposes).

Product has a many-to-many relationship with Shipper. Shipper then has a one-to-many relationship with Warehouse.

Basically: Product has many Shippers which have many Warehouses.

We have a mapping from Product to Shipper and from Warehouse to Shipper. But NOT FROM Shipper to Product or Warehouse.

I've been trying to construct a query to return (for now just the count of) all the Warehouses which are related to a particular Product.

First Attempt: Got a list of Shippers from the Product. Created a query for Warehouse where the Shipper was IN our set. This works, but it's two queries. We need it to be one query.

+1  A: 

Something like?

from warehouse w 
where w.Shipper in 
     (select p.shippers from product p where p.id = 2) 
Fried Hoeben
Essentially yes. But how can this be constructed using the Criteria API?
Joseph Daigle
Can't help you there, I've always stuck the HQL format because I found it more powerful and easier to predict what SQL would end up getting to the database.
Fried Hoeben
A: 

Turns out you do need a mapping from Shipper to Product to make this work. But that's okay, just make it a no-access "query only" property.

Then it's as simple as doing a sub-select:

var subcriteria = DetachedCriteria.For<Shipper>()
                .CreateCriteria("Products", "productsForCategory")
                .Add(Property.ForName("productsForCategory.Id").Eq(product.Id))
                .SetProjection(Projections.Id());

And then putting that IN the other query:

Session.CreateCriteria<Warehouse>()
                .Add(Subqueries.PropertyIn("Shipper", subcriteria))
Joseph Daigle