HIbernate fetch join 发出额外的 sql 语句
考虑以下具有两个 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 语句的帮助都是值得赞赏的。
Consider the following Parent class that has two ManyToOne references.
@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;
}
I am using the following hql query to load the Parent instance:
"from Parent p join fetch p.childInstance1 join fetch p.childInstance2 where p.userId = :userId"
This always results in hibernate issuing separate sql statements to load the childInstance1 rows even though it does the fetch join.
Any help in avoiding the extra sql statements is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我无法重现。给定以下实体:
以及
以下 HQL 查询:
生成以下 SQL:
在 Hibernate 3.3.0.SP1、Hibernate Annotations 3.4.0.GA 中按预期工作。
I cannot reproduce. Given the following entities:
and
The following HQL query:
Generates the following SQL:
Works as expected with Hibernate 3.3.0.SP1, Hibernate Annotations 3.4.0.GA.