Search code examples
hibernatehql

how to use fetch in Hibernate Query Language


This is not a techincal problem, just a syntax correction that I am not getting.

I have hibernate 3.6 and I have mapped my model classes in the xml files. The default type mentioned in those xml files are that these classes are to be brought as lazily. Since its hardcoded, I cannot change that behaviour.

The model that I am trying to bring looks like this.

class A {
    private int id;
    private B b;
    private C c;
}

The classes B and C needs to be loaded eagerly in my case.

SO I wrote the query like this.

from A.class.getName() a where a.id = :id;

In this query, where do I put the fetch keyword. Below one throws errors:

from A.class.getName a fetch where a.id = :id;

In examples on the internet, they are doing some joins on the query and then getting some values like this:

from Cat as cat inner join fetch cat.mate left join fetch cat.kittens

However, in my case, all the joins are done internally in the xml files. I don't have to do joins in the query. So where do I put the "fetch" keyword to state that initiate all the linked classes (B and C) also at the same time non-lazily.

Note:

  1. I cannot use criteria api because I don't want to add additional jars in my project.

Solution

  • The syntax is

    select a from A a
    left join fetch a.b
    left join fetch a.c
    where a.id = :id
    

    Relevant part of the documentation:

    A "fetch" join allows associations or collections of values to be initialized along with their parent objects using a single select. This is particularly useful in the case of a collection. It effectively overrides the outer join and lazy declarations of the mapping file for associations and collections. See Section 20.1, “Fetching strategies” for more information.

    from Cat as cat
    inner join fetch cat.mate
    left join fetch cat.kittens