本文介绍了Hibernate为@ManyToOne JPA带注释的属性创建N + 1个查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这些课程:
@Entity
public class Invoice implements Serializable {
@Id
@Basic(optional = false)
private Integer number;
private BigDecimal value;
//Getters and setters
}
@Entity
public class InvoiceItem implements Serializable {
@EmbeddedId
protected InvoiceItemPK invoiceItemPk;
@ManyToOne
@JoinColumn(name = "invoice_number", insertable = false, updatable = false)
private Invoice invoice;
//Getters and setters
}
当我运行此查询时:
session.createQuery("select i from InvoiceItem i").list();
它执行一个查询以从InvoiceItem中选择记录,如果我有10000个发票项目,它会生成10000个附加查询以从每个InvoiceItem中选择发票.
It executes one query to select the records from InvoiceItem, and if I have 10000 invoice items, it generates 10000 additional queries to select the Invoice from each InvoiceItem.
我认为,如果所有记录都可以在单个sql中提取,那就更好了.实际上,我发现为什么它不是默认行为很奇怪.
I think it would be a lot better if all the records could be fetched in a single sql. Actually, I find it weird why it is not the default behavior.
那我该怎么办?
推荐答案
尝试
session.createQuery("select i from InvoiceItem i join fetch i.invoice inv").list();
它应该使用联接在单个SQL查询中获取所有数据.
It should get all the data in a single SQL query by using joins.
这篇关于Hibernate为@ManyToOne JPA带注释的属性创建N + 1个查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!