Load recursive object graph without N+1 Cartesian Product with JPA and Hibernate

前端 未结 1 1859
隐瞒了意图╮
隐瞒了意图╮ 2021-02-04 04:36

When converting a project from Ibatis to JPA 2.1, I\'m faced with a problem where I have to load a complete object graph for a set of objects, without hitting N+1 selects or usi

相关标签:
1条回答
  • 2021-02-04 05:08

    Available options

    There are some strategies to achieve your goals:

    • sub-select fetching would load all lazy entities with an additional sub-select, the very first time you need a lazy association of that given type. This sounds appealing at first, but it makes your app fragile to the number of additional sub-select entities to fetch and may propagate to other service methods.

    • batch fetching is easier to control since you can enforce the number of entities to be loaded in one batch and might not affect too much other use cases.

    • using a recursive common table expression if your DB supports it.

    Plan ahead

    In the end, it's all about what you plan on doing with the selected rows. If it's just about displaying them into a view, then a native query is more than enough.

    If you need to retain the entities across multiple requests (first the view part, the second for the update part) then entities are a better approach.

    From your response, I see you need to issue an EntityManager.merge() and probably rely on cascading to propagate children's state transitions (add/remove).

    Since we are talking about 3 JPA queries, and as long as you don't get a Cartesian Product then you should be fine with JPA.

    Conclusion

    You should strive for the minimum amount of queries but it doesn't mean you will always have to have one and only one query. Two or three queries are not an issue at all.

    As long as you control the query number and don't get into an N+1 query issue] you are fine with more than one query too. Trading a Cartesian Product (2 one-to-many fetches) for one join and one additional select is a good deal anyway.

    In the end, you should always check the EXPLAIN ANALYZE query plan and reinforce/rethink your strategy.

    0 讨论(0)
提交回复
热议问题