开发者

How to prevent unnecessary select on insert?

开发者 https://www.devze.com 2023-03-15 03:37 出处:网络
I have the following scenario (in Java / Hibernate): I have two entity classes: X and Y. X has a @ManyToOne association to Y which is not cascaded.

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

  • I have two entity classes: X and Y. X has a @ManyToOne association to Y which is not cascaded.
  • I create an (unmanaged) instance x of X and an (unmanaged) instance y of Y, and fill the reference to y in x. The only field of y that is filled is the primary key.
  • Entity y already has a corresponding row in the underlying database, but entity x is new.
  • I persist entity x.

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

  • SELECT y
  • INSERT x

Furthermore, I also notice that after the persist of x开发者_Go百科, 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消