Note that there are some explanatory texts on larger screens.

plurals
  1. POSub-optimal queries over many-to-many relations with HQL
    primarykey
    data
    text
    <p>I have two entities, Location and Industry, and a link-table between them. I've configured a many-to-many relationship, in both directions, between the two entities.</p> <p>In a search query, I'm trying to select Locations that are associated with a list of industries.</p> <p>After days and days of trying to wrangle the criteria API, I've decided to drop down to HQL and abandon the criteria API. But even that isn't going well for me - it seems, regardless of whether I hand-write this HQL query, or let the criteria API do it, I end up with the same result.</p> <p>I managed to produce the right result in two ways - like this:</p> <pre><code>var q = Data.Query("select distinct loc from Location loc join loc.Industries ind where ind in (:ind)"); q.SetParameterList("ind", new Industry[] { Data.GetIndustry(4), Data.GetIndustry(5) }); </code></pre> <p>And (better) like that:</p> <pre><code>var q = Data.Query("select distinct loc from Location loc join loc.Industries ind where ind.id in (:ind)"); q.SetParameterList("ind", new int[] { 4, 5 }); </code></pre> <p>Unfortunately, both result in a sub-optimal query:</p> <pre><code>select distinct location0_.Id as Id16_, location0_.Name as Name16_, (etc.) from Location location0_ inner join LocationIndustry industries1_ on location0_.Id=industries1_.LocationId inner join Industry industry2_ on industries1_.IndustryId=industry2_.Id where industry2_.Id in (? , ?) </code></pre> <p>Why the extra join?</p> <p>Is NH not smart enough to know that the Industry.Id property, being the only Industry-property involved in the query, is stored in the LocationIndustry link-table, and there is no need for the extra join to the Industry table itself?</p> <p>Or am I doing something wrong?</p> <p>Ideally, the most intuitive thing for me would be to write:</p> <pre><code>from Location loc where loc.Industries in (:ind) </code></pre> <p>This does not work - it throws an error and says it does not know about the Industries property. I guess because Industries, being a "property" in programming terms, is actually a "relationship" in terms of DBMS.</p> <p>What is the simplest and most efficient way to write this query in HQL?</p> <p>Thanks!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload