EntityManager.merge () returns a SELECT for all objects in the object graph

I use JPA 2 and Hibernate 3. I noticed that calling EntityManager.merge() calls SELECT for each reference object in the PLUS object graph the internal connections between some of them.

Suppose you want to combine () a FooBar.

 @Entity public class FooBar { @ManyToOne private Foo foo; @ManyToOne private Bar bar; } @Entity public class Foo { @ManyToOne private Baz baz; } @Entity public class Bar { @ManyToOne private Baz baz; } 

If you do, Hibernate will issue a SELECT for each of FooBar, Foo, and Bar, and two for Baz. He will then release SELECT for Foo, connected to Baz, and another for Bar, connected to Baz. Since I just wanted to combine FooBar, I expected one SELECT from it, but I got a huge amount of 7 SELECT!

First of all, is this normal? Secondly, if so, is there a way to release only one SELECT?

Thanks.

+4
source share
1 answer

You call merge(..) with a separate object (i.e. not associated with the session). What is hibernate here: it loads an object with the identifier of the passed object from the database and:

  • If the record is not found, inserts the passed object
  • if an object is found, passes all fields and returns a permanent object

In the latter case, loading from the database is involved, so Hibernate needs to get the whole object. Consequently, many choose.

You can try fetchType=LAZY for ManyToOne relationships (by default they wish).

+5
source

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


All Articles