Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

fetch="subselect" and fetch="join" not working as expected with HQL

 
Pankaj Kumarkk
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a contact and address entities where contact has 1-to-many relationship with address

I am trying to fetch all the addresses for all contacts in minimum sqls. I read the chapter 13(optimizing fetching and caching) of Java persistence with hibernate. It specifies 3 possible solutions:
1. Using batch-size
2. Using fetch="subselect"
3. Using fetch = "join"

Below is my java code:
List contacts = session.createQuery("from roseindia.tutorial.hibernate.Contact").list();
System.out.println("contacts.size" + contacts.size());
Iterator it = contacts.iterator();
while(it.hasNext())
{
Contact contact = (Contact)it.next();
}

<class name="roseindia.tutorial.hibernate.Contact" table="CONTACT" lazy="true">
<id name="id" type="long" column="ID" >
<generator class="assigned"/>
</id>
<property name="firstName">
<column name="FIRSTNAME" />
</property>
<property name="lastName">
<column name="LASTNAME"/>
</property>
<property name="email">
<column name="EMAIL"/>
</property>
<set name="addresses" table="ADDRESS" fetch="join">
<key column="CONTACTID"/>
<one-to-many class="roseindia.tutorial.hibernate.Address"/>
</set>
</class>

1. Batch size works fine and gives me 1 sql for the association table when i increase the batch size sufficiently
2. fetch="subselect" and fetch="join" doesn't work as expected and it gives me N+1 sqls for the above code

I read at below url that fetch="subselect" and fetch="join" doesn't work for HQLs and criteria. It works only with load/get

https://forum.hibernate.org/viewtopic.php?f=1&t=957561&start=0

I am confused about which to take as final answer. The book itself is written by Hibernate creater and thus the example could not be wrong.

Can somebody tell me whether book is correct or the said url(from Hibernate forum) is correct.

If book is correct then can anybody help me find the problem.

Thanks,
Satish
 
Pankaj Kumarkk
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got answer to 1 question. On reading more, I found that fetch="subselect" only applies to collection and not entity proxies.
Following is quote from book "subselect fetching is available only for collections and not entity proxies"

I interpret from above that subselect is available only for collections containing value types and not entity types.
I still am looking for answer to the 2nd question(fetch="join")
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic