关于事务和事件监听器
让我看看我的理解是否正确。通常,我们应该努力将属于一个“工作单元”的所有操作放在同一个事务下,对吧?这有助于在操作链中的某个地方出现异常时恢复数据库的状态。
然而,在我的特定情况下,我有一个旧的服务,它并不容易插入到我当前的代码中。因此,我必须保持它单独运行,并授予它对当前应用程序存储数据的同一数据库的权限。
当我必须将新项目插入数据库时,问题就出现了。然后我必须打电话给服务人员。如果我在一个事务下执行此操作,该服务将在事务实际提交之前开始在数据库中查找记录。因此,我开始使用事件侦听器,即 PostInsertEventListener 和 PostDeleteEventListener。
现在它工作正常,因为事务是提前提交的,但这完全破坏了我的代码架构。我已经构建了一系列相互注入的服务,现在我必须声明这两个侦听器类。我想,我能做的最好的事情就是让我的协调器服务实现这两个侦听器接口,但通过这种方式我可以将它完全耦合到 Hibernate,对吧?
一般来说,对于像我这样的情况,使用这些侦听器真的是正确的方法吗?
Let me see if I understand this correctly. Normally, we should strive to put all operations which belong to one "unit of work" under the same transaction, right? This helps revert the state of the DB in case of an exception somewhere along the chain of operations.
However, in my particular case, I have an old service, which is not really easy to plug into my current code. Therefore I have to keep it running separately, and give it rights to the same database where my current application stores data.
The problem comes when I have to insert a new item into the DB. Then I have to call the service. If I do this under one transaction, the service will start looking for a record in the DB, before the transaction has actually committed. Thus, I started using event listeners, namely the PostInsertEventListener and the PostDeleteEventListener.
Now it works OK, since the transaction commits beforehand, but this totally disrupts my code architecture. I have built a series of services which inject into each other, and now I have to declare those two listener classes. I guess, the best I can do is to make my coordinator service implement those two listener interfaces, but in this way I totally couple it to Hibernate, right?
In general, is using those listeners really the right way for cases like mine?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不明白您是如何从“我需要在调用外部服务之前提交事务”到“我决定使用侦听器”的。
为什么不直接使用以下代码:
或者
insertThingsInDatabase
使用REQUIRES_NEW
传播类型?I don't see how you came from "I need to have the transaction committed before calling the external service" to "I decided using listeners".
Why don't you simply have the following code:
or
where
insertThingsInDatabase
uses theREQUIRES_NEW
propagation type?