Merge n+1 problem

Hi experts!

I have a spring boot aplication which has a biderectional one-to-many mapping with both sides lazy. When data comes from presentation layer I do a merge operation through a parent entity. It’s an edit operation so parent and child entities all have ids.
But it seems that there is so called “n+1” problem. I can see in logs that hibernate does an additional select to load each child entity. It doesn’t make a join to load all data at once.

In one of my prevous projects we used another jpa provider(not hibernate) and had a similliar issue, so a “hacky” solution was to preload data in persistent context mannualy using one query before calling merge.

Do I miss something in project setting or entity mappings? I think there shouldn’t be such an issue with hibernate.

Hi,
You should load the modified entities before copying your DTOs into these entities. Use left join fetch to load all of them efficiently.
…do not use merge here

If you want to fix/improve this in Hibernate, you can create a JIRA issue and discuss your idea for a solution with us on Zulip. It’s a tradeoff as you can imagine. Join fetching too much can lead to performance issues as well and might even be unnecessary if there are many “null” FKs, but I think it would be great if we would introduce an option to configure the behavior.