gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:14:18 24 4
gpt4 key购买 nike

我有一个 Domain 实体,它与我希望立即加载的 Country 实体具有 @ManyToOne 单向关系使用 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=?

我假设有什么东西阻止了它的应用。那是什么?

最佳答案

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

FROM Domain domain WHERE domain.type = :type

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

基于汤姆·安德森的评论和答案here ,我将 HQL 更改为

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

这会导致 Hibernate 仅使用一个带有联接的大型查询来一起检索 DomainCountry,而不是对所有 Domain 使用一个查询code> 实体和用于检索每个实体的 CountrySELECT

对于Criteria,似乎没有必要这样做。仅当您使用HQL时,才需要指定JOIN FETCH

关于java - 未应用 Hibernate @Fetch(Join) 而不是单独的 SELECT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18258942/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com