What is the best optimized way to select many entities with entities in JPA?

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 them say that there are 10,000 orders, each of which has 20 items.

We need to repeat all order and all their objects. What is the best way to do this in JPA?

My problem is that if I just repeat 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);
    }
}

this will lead to 10.001 sql queries: 1 time: select * from the order 10,000 times: select * from the item where order_id =?

Is there any way to optimize it? Two questions? One request?

(We use EclipseLink)

Thank.

+3
source share
2 answers

EclipseLink Hint "eclipselink.batch" "o.items". , , .

+2

join fetch ( distinct, join fetch join):

select distinct o from Order o join fetch o.items
0

Source: https://habr.com/ru/post/1760169/


All Articles