gpt4 book ai didi

java - HIbernate fetch join 发出额外的 sql 语句

转载 作者:太空宇宙 更新时间:2023-11-04 08:48:59 24 4
gpt4 key购买 nike

考虑以下具有两个 ManyToOne 引用的 Parent 类。

@Entity
@Table(name = "PARENT")
public class Parent {

private static final long serialVersionUID = 3730163805206219313L;

@Id
@SequenceGenerator(name = "SEQ#PARENT", sequenceName = "SEQ#PARENT", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ#PARENT")
@Column(name = "ID")
private long id;

@ManyToOne(optional = false, fetch=FetchType.EAGER)
@Fetch(FetchMode.JOIN)
@JoinColumn(name="CHILD_1_ID", referencedColumnName="FK_COLUMN_NAME")
private Child childInstance1;

@ManyToOne(optional = false, fetch=FetchType.EAGER)
@Fetch(FetchMode.JOIN)
@JoinColumn(name="CHILD_2_ID", referencedColumnName="FK_COLUMN_NAME")
private Child childInstance2;

@Column(name = "USER_ID")
private String userId;
}

我使用以下 hql 查询来加载父实例:

"from Parent p  join fetch p.childInstance1 join fetch p.childInstance2 where p.userId = :userId"

这总是导致 hibernate 发出单独的 sql 语句来加载 childInstance1 行,即使它执行了 fetch join。

对于避免额外的 sql 语句的任何帮助,我们表示赞赏。

最佳答案

我无法重现。给定以下实体:

@Entity
public class Parent3764122 {
@Id @GeneratedValue
private long id;

@ManyToOne(optional = false/*, fetch=FetchType.EAGER*/) // EAGER by default
//@Fetch(FetchMode.JOIN) // unnecessary
@JoinColumn(name="CHILD_1_ID")
private Child3764122 childInstance1;

@ManyToOne(optional = false/*, fetch=FetchType.EAGER*/) // EAGER by default
//@Fetch(FetchMode.JOIN) // unnecessary
@JoinColumn(name="CHILD_2_ID")
private Child3764122 childInstance2;

@Column(name = "USER_ID")
private String userId;
...
}

@Entity
public class Child3764122 {
@Id @GeneratedValue
private Long id;

...
}

以下 HQL 查询:

from Parent3764122 p join fetch p.childInstance1 join fetch p.childInstance2 where p.id = :id

生成以下 SQL:

select
parent3764x0_.id as id129_0_,
child37641x1_.id as id130_1_,
child37641x2_.id as id130_2_,
parent3764x0_.CHILD_1_ID as CHILD3_129_0_,
parent3764x0_.CHILD_2_ID as CHILD4_129_0_,
parent3764x0_.USER_ID as USER2_129_0_
from
Parent3764122 parent3764x0_
inner join
Child3764122 child37641x1_
on parent3764x0_.CHILD_1_ID=child37641x1_.id
inner join
Child3764122 child37641x2_
on parent3764x0_.CHILD_2_ID=child37641x2_.id
where
parent3764x0_.id=?

在 Hibernate 3.3.0.SP1、Hibernate Annotations 3.4.0.GA 中按预期工作。

关于java - HIbernate fetch join 发出额外的 sql 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3764122/

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