gpt4 book ai didi

java - Hibernate 生成的额外 sql

转载 作者:行者123 更新时间:2023-11-30 07:13:56 24 4
gpt4 key购买 nike

我正在尝试使用 session.save 保存一个对象,如下所示:

beginTransaction();
sessionFactory.getCurrentSession().save(entity);
entity.setName("Entity " + Math.random());
commitTransaction();

生成以下sql:

1)insert into entity
2)update set name =

即使尽可能晚地刷新更改,为什么它还要生成单独的更新 sql?

最佳答案

这是预期的 Hibernate 行为,正如 Gavin( hibernate 开发者之一)所解释的那样 here :

Expected Hibernate behavior (we have debated whether this is really correct or not!) is that the INSERT statement will insert exactly the data that was set when save() was called. This gives the user a bit finer grained control, especially in a context where there are triggers etc. However, if you are not careful, it could perform badly.

To avoid the INSERT-then-UPDATE, simply fully initialize the object before saving it.

但是,如果您对此不满意(在我的情况下,使用扩展持久性上下文时真的很烦人):有一个 Hibernate 3.5.6_final 的补丁 here改变这种行为。

关于java - Hibernate 生成的额外 sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18892741/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com