为什么Hibernate会触发onFlushDirty两次?

发布于 2024-09-09 07:41:31 字数 184 浏览 2 评论 0原文

最近我经常使用 Castle ActiveRecord 框架,它运行得很好,直到我发现一些奇怪的行为:在某些情况下 onFlushDirty 被触发两次。当我进行简单查询时它甚至会被触发。我真的很困惑,因为我试图在 onFlushDirty 中创建审核数据,当我读取数据时,它会被触发,从而导致它保存相同的数据。

我怎样才能避免这种行为?

Lately I have been using the Castle ActiveRecord framework a lot and it has worked fine until I found some strange behaviour: the onFlushDirty is triggered twice in some situations. It is even triggered when I make a simple query. I'm really confused cause I'm trying to create auditing data in onFlushDirty and as I read data it's triggered which causes it to save identical data.

How can I avoid this behaviour?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

月下客 2024-09-16 07:41:31

我想我解决了我的问题,但我不知道为什么会发生这种情况。

首先,我在数据库中的数据在某些日期字段和整数字段中具有空值(数据来自 Btrieve 的迁移)。

当我在数据网格中加载数据时,触发了 onFlushDirty 事件,当我调试和观看数据时,我看到在具有 null 值的日期字段上,它的 previousState 为 null,currentState 为 '0001-01-01 00:00:00 '。我在数据库中将日期字段的空值更改为“0001-01-01 00:00:00”,将整数字段更改为零,并且当我将数据加载到数据网格上时,onFlushDirty 事件再也没有触发。

但问题仍然存在。为什么会发生这种情况或者这种行为是否正确?

I think I resolved my issue but I don't know why this happens.

First of all, the data I have in database has null values in some date fields and integer fields, (the data came from a migration from Btrieve).

When I loaded the data in a datagrid the onFlushDirty event triggered, when I debugged and watched the data I saw that on a date field with null value it had a previousState with null and currentState with '0001-01-01 00:00:00'. I changed in the database the nulls with '0001-01-01 00:00:00' in the case of date fields and zero for the integer fields and the onFlushDirty event never triggered again when I loaded the data on the datagrid.

But the question still remains. Why does this happens or is it correct this behaviour?

云胡 2024-09-16 07:41:31

我的猜测是,您已经告诉 Hibernate(在该表的映射或实体类上的注释中)日期字段不应为空,因此 Hibernate 会为您设置它,但由于这与它检索的值不同数据库,它被标记为脏。

我还遇到过 Hibernate 在提交之前多次刷新 Session 的情况,这导致 onFlushDirty 中的任何逻辑运行的次数比我想要的要多。发生这种情况是因为当会话设置为 FlushMode.AUTO 时,会话会在检索之前刷新,以便包含最近未提交的更改。这是设计的,所以我在做出要审核的更改后立即开始提交。

My guess is that you've told Hibernate (in the mapping for that table or an annotation on the entity class) that the date field should not be null, so Hibernate sets it for you, but since this differs from the value it retrieved from the database, it's marked as dirty.

I've also run into the situation where Hibernate flushes the Session several times before committing, which causes any logic in onFlushDirty to be run more times than I wanted. This was happening because when the session is set to FlushMode.AUTO, the session is flushed prior to retrieval in order to include recent uncommitted changes. This is by design, so I began committing immediately after making changes to be audited.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文