如何防止插入时不必要的选择?
我有以下场景(在 Java / Hibernate 中):
- 我有两个实体类:X 和 Y。X 与 Y 有一个 @ManyToOne 关联,该关联不是级联的。
- 我创建 X 的(非托管)实例 x 和 Y 的(非托管)实例 y,并在 x 中填充对 y 的引用。 y 唯一被填充的字段是主键。
- 实体 y 在底层数据库中已经有对应的行,但实体 x 是新的。
- 我坚持实体x。
当我执行此场景时,我希望看到一个查询:INSERT x。然而,实际发生的是 Hibernate 执行两个查询:
- SELECT y
- INSERT x
此外,我还注意到,在 x 持久化之后,对 y 的引用实际上并未变为托管状态,并且会话中没有 Y 的实例!那么,为什么要对 y 执行 SELECT 呢?有办法防止这种行为吗?
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, 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不需要(实际上您不应该)手动实例化 Y。您可以执行此操作的变体(取决于您的配置),
这不会从数据库中检索 Y,而是加载仅由您提到的 pk 组成的代理。
然后将 y 分配给 x,并保留 x 将按照您的预期运行。
You don't need to (actually you shouldn't) instantiate Y manually. You can do a variant of this (depending on your configuration)
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.