不应用Hibernate @Fetch(Join)而不是单独的SELECT

时间:2013-08-15 18:11:08

标签: java hibernate hql

我有一个Domain实体与@ManyToOne实体的Country单向关系,我想热切地加载JOIN而不是单独的选择。我考虑过使用@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; 

    ...
}

我正在使用HQL来查询这些实体。

但是Hibernate不应用提取策略。我试过@OneToOne(我的设计中没有改变任何东西),但这也行不通。这是一个示例SQL输出

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=?

我假设某些东西阻止它被应用。那是什么?

1 个答案:

答案 0 :(得分:1)

我正在查询我的Domain实体,例如

FROM Domain domain WHERE domain.type = :type

这导致Hibernate为返回的每个Country单独查询Domain个实体。

根据汤姆安德森的评论和答案here,我将我的HQL更改为

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

这会导致Hibernate只使用一个带有连接的大查询来一起检索DomainCountry,而不是对所有Domain个实体和SELECT进行一次查询}为每个人检索Country

使用Criteria,似乎没有必要。只有在使用HQL时才需要指定JOIN FETCH