Rubrick
Rubrick

Reputation: 308

How to prevent unnecessary select on insert?

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

When I perform this scenario, I expect to see one query: INSERT x. However, what actually happens is that Hibernate performs TWO queries:

Furthermore, I also notice that after the persist of x, the reference to y does not actually become managed and there is no instance of Y in the session! So, why is the SELECT on y performed at all? Are there ways to prevent this behaviour?

Upvotes: 5

Views: 591

Answers (1)

SelimOber
SelimOber

Reputation: 708

You don't need to (actually you shouldn't) instantiate Y manually. You can do a variant of this (depending on your configuration)

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

This doesn't retrieve Y from database, instead it loads a proxy consisting only from the pk you mentioned.

Then assigning y to x, and persisting x would behave as you expect.

Upvotes: 3

Related Questions