简体   繁体   English

在JPA中选择具有子实体的许多实体的最佳优化方法是什么?

[英]What is the best optimized way to select many entities with subentities in JPA?

Let's say we have: 假设我们有:

@Entity public class Order {
  @Id private int id;
  @OneToMany(mappedBy="order") private List<Item> items;
  ...
}

and

@Entity public class Item {
  @Id private int id;
  @ManyToOne private Order order;
  ...
}

And let's say there is 10.000 orders with each having 20 items. 我们说有10,000个订单,每个订单有20个项目。

We need to iterate thought all order and all their items. 我们需要迭代思考所有订单及其所有项目。 What is the best way to do it in JPA? 在JPA中最好的方法是什么?

My issue is, if I just iterate the elements like: 我的问题是,如果我只是迭代这些元素:

for (Order order: em.createTypeQuery("select o from Order o", Order.class).getResultList()) {
    report.printOrder(order);
    for (Item item: order.getItems()) {
        report.printOrderItem(item);
    }
}

it will result in 10.001 sql queries: 1 time: select * from order 10.000 times: select * from item where order_id = ? 它将导致10.001 sql查询:1次:从订单中选择* 10.000次:从项目中选择*,其中order_id =?

Is there any way to optimize it? 有没有办法优化它? Two queries? 两个疑问? One query? 一个查询?

(We are using EclipseLink) (我们正在使用EclipseLink)

Thanks. 谢谢。

You may also want to consider the EclipseLink query Hint "eclipselink.batch" with value "o.items". 您可能还需要考虑EclipseLink查询Hint“eclipselink.batch”,其值为“o.items”。 This results in two queries but can be more effecient than once large joined query. 这导致两个查询,但可能比一次大型连接查询更有效。

您可以使用join fetch (这也需要distinct因为join fetch具有join语义):

select distinct o from Order o join fetch o.items

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM