• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

n+1 select problem

 
Bhavik Patel
Ranch Hand
Posts: 155
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In my mapping i have one named query defined as

from productGroup order by name

producGroup has many products ...<set name="products" ...>

so running the above queries it also tries to load all the products..That is ok with me but i want it to be loaded in singel query instead of individual select statements ... How do i wrote the above query so it also load all products while loading the product group instead of running n times select for each product whicle referring the collection products.

thanks
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are a few ways, the best is to add a FetchMode to your Query object by calling the Query objects setFetchMode() method, so pass FetchMode.JOIN, or FetchMode.SUBSELECT.

Join will eager fetch it, so one query, and SubSelect will have two queries, the first for the one side, and the second for the collection.

Mark
 
Bhavik Patel
Ranch Hand
Posts: 155
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so i can write something like

from ProductGroup as pg left fetch join pg.products

but Does the above query will give me unique results..I mean no duplicates after join ...??
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Basically yes that is the query you want to write. Examine the query and figure out if it will return duplicate results or not.

Mark
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic