18

I have a situation where a Card entity has a foreign key to a Person.

public class Card implements java.io.Serializable {
    private String cardid;
    private Person person;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "USERID")
    public Person getPerson() {
        return this.person;
    }
}

The default fetch type for the person is LAZY. Can I specify the fetch type to EAGER within a query:

QCard qCard = QCard.card;
JPQLQuery query = getQuery().from(qCard);
query.list(qCard);

Thanks for any help.

night-crawler
  • 1,409
  • 1
  • 26
  • 39
Marko
  • 345
  • 1
  • 3
  • 11
  • You can just call the `getPerson()` method to load the Person object before your object is detached, do you have a specific reason to change the fetch type ? – Michael Técourt May 13 '14 at 09:45
  • The reason I want to change the fetch type is to optimize the query. I have a case where I need to load multiple foreign key objects. It seems to work slow. – Marko May 13 '14 at 10:15
  • So you're looking for the `FETCH` keyword from JPAQL in QueryDSL. Is this what you're looking for ? https://groups.google.com/forum/#!msg/querydsl/Geexg_eN2yA/iREXf-DM0nwJ – Michael Técourt May 13 '14 at 13:27
  • It seems to be what I'm looking for. I will give it a try and write back the results. So I can just add something like this for every foreign key object to eager load:"query.innerJoin(qCard.person).fetch();" – Marko May 13 '14 at 13:48
  • I added "query.innerJoin(qCard.cmsPerson).fetchAll();" but it still lazy fetches the person object. – Marko May 13 '14 at 15:54

1 Answers1

27

Did you try

QCard qCard = QCard.card;
List<Card> cards = getQuery().from(qCard)
    .innerJoin(qCard.person).fetch()
    .list(qCard);

For QueryDSL 4.0.2+

QCard qCard = QCard.card;
List<Card> cards = getQuery().from(qCard)
    .innerJoin(qCard.person).fetchJoin()
    .select(qCard).fetch();
F43nd1r
  • 7,690
  • 3
  • 24
  • 62
Timo Westkämper
  • 21,824
  • 5
  • 78
  • 111
  • Originaly I tried innerJoin with fetchAll. I found out that the combination leftJoin with fetch works. Not sure if this is the case or some caching was the problem. – Marko May 15 '14 at 07:36
  • Please put your working code in an answer and mark this issue as resolved – Michael Técourt May 15 '14 at 09:42
  • Timo's answer works. Person is fetched eagerly if I use fetch(), but not if I use fetchAll(). – Marko May 15 '14 at 10:43
  • 8
    As of [QueryDSL 4.0.2](https://github.com/querydsl/querydsl/issues/1414), the interface has changed. To set the fetch mode of the last join, call fetchJoin(). To finally get the results, call fetch(). So it would be List cards = getQuery().from(qCard) .innerJoin(qCard.person).fetchJoin() .fetch(); – ta55e Nov 24 '16 at 13:53