开发者

Sub-optimal queries over many-to-many relations with HQL

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.

In a search query, I'm trying to select Locations that are associated with a list of industries.

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.

I managed to produce the right result in two ways - like this:

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) });

And (better) like that:

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 });

Unfortunately, both result in a sub-optimal query:

select distinct
  location0_.Id as Id16_,
  location0_.Name as Name16_,
  (etc.)
from Location location0_
  inner join LocationIndust开发者_JS百科ry industries1_
    on location0_.Id=industries1_.LocationId
  inner join Industry industry2_
    on industries1_.IndustryId=industry2_.Id
where
  industry2_.Id in (? , ?)

Why the extra join?

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?

Or am I doing something wrong?

Ideally, the most intuitive thing for me would be to write:

from Location loc where loc.Industries in (:ind)

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.

What is the simplest and most efficient way to write this query in HQL?

Thanks!


I'm not sure you can avoid this extra join given the mapping strategy you have used.

You could avoid it by using an intermediary class but this would mean you would need a class structure like this:

public class Industry {
    //Other stuff
    public virtual List<LocationIndustry> LocationIndustries {get; set:;}
}

public class LocationIndustry {
    public virtual Location Location {get; set;}
    public virtual Industry Industry {get; set;}
}

public class Location {
    //normal stuff
    public virtual IList<LocationIndustry> LocationIndustries {get; set;}
}

Then you can query on the LocationIndustry class and avoid the join to Location.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜