How to prevent unnecessary selection when pasting?

I have the following script (in Java / Hibernate):

  • I have two classes of entities: X and Y. X has an association of @ManyToOne with Y, which is not cascaded.
  • I create an (unmanaged) instance of x from X and a (unmanaged) instance of y from Y and populate the link to y in x. The first key is only the y field, which is filled.
  • Object y already has a matching row in the underlying database, but object x is new.
  • I save the x object.

When I run this script, I expect to see one query: INSERT x. However, what actually happens is that Hibernate executes TWO requests:

  • SELECT y
  • INSERT x

In addition, I also notice that after saving x, the reference to y is not actually controlled, and there is no instance of Y in the session! So why does SELECT on y run at all? Are there any ways to prevent this behavior?

+5
source share
1 answer

You do not need (actually not needed) to copy Y manually. You can do a variant of this (depending on your configuration)

Y y = (Y) session.load(Y.class, pk);

This does not extract Y from the database, but loads a proxy consisting only of the pk you specify.

Then assigning y x, and saving x will behave as you expect.

+2
source

All Articles