0

我有一个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=?

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

4

1 回答 1

1

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

FROM Domain domain WHERE domain.type = :type

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

根据 Tom Anderson 的评论和此处的答案,我将 HQL 更改为

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

这导致 Hibernate 只使用一个带有连接的大查询来检索DomainCountry一起检索,而不是一个查询用于所有Domain实体并SELECT检索Country每个实体。

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

于 2013-08-15T20:38:30.147 回答