[
Date Prev][
Date Next][
Thread Prev][
Thread Next][
Date Index][
Thread Index]
[
List Home]
Re: [eclipselink-users] Lazy loading performance problem
|
To avoid N+1 on a LAZY OneToMany relationship which you want preloaded you should use the JOIN FETCH/LEFT JOIN FETCH syntax.
-Noah
On Nov 7, 2011, at 10:41 AM, Warren Tang wrote:
> But fetch join on OneToMany/ManyToMany relationship has problems with pagination.
>
> The problem seems to be called N+1 select problem. I searched hard but could found a solution.
>
> It's a problem everyone faces, right? How do you solve it?
>
> Regards,
> Warren Tang <http://blog.tangcs.com>
>
>
> On Friday, November 04, 2011 5:43:32 PM, Leon Derks wrote:
>> Hello.
>>
>> I think you can do this with a fetch join like:
>> SELECT pub FROM Publisher pub JOIN pub.magazines mag
>>
>> Leon
>>
>> On Nov 4, 2011, at 10:36 AM, Warren Tang wrote:
>>
>>> Hi, everybody
>>>
>>> I have an ExamPaper entity which has many ChoiceQuestions. The
>>> questions are lazy loaded by default (fetch=LAZY).
>>>
>>> Now I want to get all the quesitions that belong to a specific
>>> ExamPaper, so I use the following JPQL:
>>>
>>> "select p.questions from ExamPaper p where p.id=:paperId";
>>>
>>> The problem is that questions are "lazy" loaded, so there is one
>>> "SELECT" executed for *every single* question. But I want to select
>>> them all in one go for performance reasons. What should I do?
>>>
>>> ------------------ Code listing -----------------------------------
>>>
>>> @Entity
>>> public class ExamPaper {
>>> public static final String SELECT_QUESTION_BY_PAPER = "select
>>> p.questions from ExamPaper p where p.id=:paperId";
>>> @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
>>> private Long id;
>>> private String name;
>>> @OneToMany(fetch = FetchType.LAZY, orphanRemoval = true, cascade =
>>> {CascadeType.ALL})
>>> List<ChoiceQuestion> questions;
>>>
>>> ... ...
>>> }
>>>
>>> query = em.createQuery(ExamPaper.SELECT_QUESTION_BY_PAPER,
>>> ChoiceQuestion.class);
>>> query.setParameter("paperId", examPaperId);
>>> query.setFirstResult(startPosition);
>>> query.setMaxResults(maxResult);
>>> list = query.getResultList();
>>>
>>> --
>>> Regards,
>>> Warren Tang <http://blog.tangcs.com/>
>>> _______________________________________________
>>> eclipselink-users mailing list
>>> eclipselink-users@xxxxxxxxxxx <mailto:eclipselink-users@xxxxxxxxxxx>
>>> https://dev.eclipse.org/mailman/listinfo/eclipselink-users
>>
>>
>>
>> _______________________________________________
>> eclipselink-users mailing list
>> eclipselink-users@xxxxxxxxxxx
>> https://dev.eclipse.org/mailman/listinfo/eclipselink-users
> _______________________________________________
> eclipselink-users mailing list
> eclipselink-users@xxxxxxxxxxx
> https://dev.eclipse.org/mailman/listinfo/eclipselink-users