users@glassfish.java.net

Re: JOIN FETCH not working right

From: Ryan de Laplante <ryan_at_ijws.com>
Date: Tue, 24 Feb 2009 22:24:50 -0500

I found the problem:

<c:forEach items="#{myBean.someList}" var="instance">
    <li>#{instance.name}</li>
</c:forEach>

c:forEach is calling #{myBean.someList} for every item which would
result in a new query to the database. I thought it was only calling my
bean once, then iterating through it.

I tried using c:set to store the List, then c:forEach on the new EL
variable. Same behavior.

I ended making myBean's someList method cache the results in request
scope to solve the problem.


Ryan


Ryan de Laplante wrote:
> Even if I set @OneToOne(fetch=FetchType.LAZY) and run "SELECT h FROM
> Hotel h" it runs hundreds of queries. I tried switching the JPA
> provider to Hibernate and it does the same, or worse. It seems to be
> n*n queries now.
>
>
>
> Ryan de Laplante wrote:
>> Hi,
>>
>> I'm using GlassFish V2 and am trying to run a JPQL query, but am
>> having the n+1 problem where it should be running a single query, but
>> it is running a query for every single result. The JOIN FETCH
>> feature is supposed to fix that, and it does in a way. The generated
>> SQL changes to include all fields from both tables to make it
>> possible to build all entities using a single query. The problem is
>> that this query is still being run for every single result.
>>
>> I have two entities: Hotel and HotelSettings. Both entities have
>> an id field called hotelCode which happen to have the same value in
>> both tables. Hotel has the following relationship:
>>
>> @OneToOne
>> @JoinColumn(name="SiteCode", insertable=false, updatable=false)
>> private HotelSettings settings;
>>
>> The HotelSettings entity doesn't know about the Hotel entity. The
>> JPQL query looks like this:
>>
>> SELECT h FROM Hotel h LEFT JOIN FETCH h.settings
>>
>>
>> Any ideas? Is this a TopLink Essentials bug?
>>
>>
>> Thanks,
>> Ryan