Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279890

Hibernate @Fetch(Join) isn't being applied instead of separate SELECTs

I have a Domain Entity with a @ManyToOne uni-directional relation to a Country Entity which I'd like to be eagerly loaded with a JOIN instead of separate selects. I thought about using @Fetch.

@Entity
@Table
public class Domain {
    @Id
    @GenericGenerator(name = "generator", strategy = "increment")
    @GeneratedValue(generator = "generator")
    @Column(name = "domain_id")
    private Long domainId;

    @Fetch(FetchMode.JOIN)
    @ManyToOne(optional = false, fetch = FetchType.EAGER)
    private Country country; 

    ...
}

I'm using HQL to query these entities.

But Hibernate doesn't apply the fetching strategy. I've tried with @OneToOne (which doesn't change anything in my design), but that also doesn't work. Here's a sample SQL output

Hibernate: select domain0_.domain_id as domain1_2_, domain0_.country as country2_, domain0_.name as name2_, domain0_.type as type2_ from domain domain0_ order by domain0_.name limit ?
Hibernate: select country0_.country_id as country1_1_0_, country0_.code as code1_0_, country0_.currency as currency1_0_, country0_.name as name1_0_ from country country0_ where country0_.country_id=?
Hibernate: select country0_.country_id as country1_1_0_, country0_.code as code1_0_, country0_.currency as currency1_0_, country0_.name as name1_0_ from country country0_ where country0_.country_id=?
Hibernate: select country0_.country_id as country1_1_0_, country0_.code as code1_0_, country0_.currency as currency1_0_, country0_.name as name1_0_ from country country0_ where country0_.country_id=?
Hibernate: select country0_.country_id as country1_1_0_, country0_.code as code1_0_, country0_.currency as currency1_0_, country0_.name as name1_0_ from country country0_ where country0_.country_id=?
Hibernate: select country0_.country_id as country1_1_0_, country0_.code as code1_0_, country0_.currency as currency1_0_, country0_.name as name1_0_ from country country0_ where country0_.country_id=?

I'm assuming something is preventing it from being applied. What is that?

Upvotes: 0

Views: 1517

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279890

I was querying my Domain entities like

FROM Domain domain WHERE domain.type = :type

and this was causing Hibernate to query Country entity individually for each Domain returned.

Based on Tom Anderson's comment and the answer here, I made the change in my HQL to

FROM Domain domain JOIN FETCH domain.country WHERE domain.type = :type

This causes Hibernate to only use one big query with a join in it to retrieve Domain and Country together, instead of one query for all Domain entities and a SELECT to retrieve the Country for each of those.

With Criteria, it seems this isn't necessary. Only when you use HQL do you need to specify the JOIN FETCH.

Upvotes: 1

Related Questions