同步spring事务

发布于 2024-11-30 01:31:26 字数 181 浏览 0 评论 0原文

我们在项目中使用 Spring 和 Hibernate,并具有分层架构。控制器->服务->经理->道。事务从管理者层开始。服务层中更新数据库中对象的方法被许多线程调用,这导致抛出过时的对象期望。所以我使这个方法同步,但仍然看到抛出陈旧对象异常。我在这里做错了什么?有更好的方法来处理这个案子吗?

感谢您提前的帮助。

We use Spring and Hibernate in our project and has a layered Architechture. Controller -> Service -> Manager -> Dao. Transactions start in the Manager layer. A method in the service layer which updates an object in the db is called by many threads and this is causing to throw a stale object expection. So I made this method Synchronized and still see the stale object exception thrown. What am I doing wrong here? Any better way to handle this case?

Thanks for the help in advance.

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

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

发布评论

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

评论(2

白日梦 2024-12-07 01:31:26

当实体在读取时间和更新时间之间被修改时,会引发陈旧对象异常。这可能发生在单个事务内,但也可能发生在您读取事务中的对象、修改它(例如在控制器层中),然后启动另一个事务并合并/更新它时(在这种情况下,几分钟或几小时)可以将读取和更新分开)。

抛出异常是为了帮助您避免用户之间的冲突。

如果您不关心冲突(即最后的更新总是获胜并替换之前的更新内容),那么就不要使用乐观锁定。如果您担心冲突,那么就会发生 StaleObjectExceptions,您应该向最终用户弹出一条有意义的消息,要求他重新加载数据并尝试再次修改它。没有办法避免它们。你必须保持乐观并希望它们不会经常发生。

进行时才发生异常时,您的同步技巧才会起作用

  • 请注意,只有当在同一事务中读取和写入
  • 实体的更新仅由该服务
  • (您的应用程序未集群)

。它还可能会显着降低吞吐量,因为您禁止任何并发更新,无论并发事务更新哪些实体。就像您在整个事务期间锁定了整个表一样。

The stale object exception is thrown when an entity has been modified between the time it was read and the time it's updated. This can happen inside a single transaction, but may also happen when you read an object in a transaction, modify it (in the controller layer, for example), then start another transaction and merge/update it (in this case, minutes or hours can separate the read and the update).

The exception is thrown to help you avoid conflicts between users.

If you don't care about conflicts (i.e. the last update always wins and replaces what the previous ones have written), then don't use optimistic locking. If you're concerned about conflicts, then StaleObjectExceptions will happen, and you should popup a meaningful message to the end user, asking him to reload the data and try to modify it again. There's no way to avoid them. You must just be optimistic and hope that they won't happen often.

Note that your synchronized trick will work only if

  • the exception happens only when reading and writing in the same transaction
  • updates to the entity are only made by this service
  • your application is not clustered.

It might also reduce the throughput dramatically, because you forbid any concurrent updates, regardless of which entities are updated by the concurrent transactions. It's like if you locked the whole table for the duration of the whole transaction.

辞慾 2024-12-07 01:31:26

我的猜测是,您需要配置Hibernate 端的乐观锁定

My guess is that you would need to configure optimistic locking on the Hibernate side.

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