本文介绍了Spring Transactional注释,隔离不适用于READ_UNCOMMITTED的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中有一个方法,它由 spring Transactional 注释包装。

I have a method in Java which is wrapped by a spring Transactional annotation.

我有2个操作在里面,一个是删除,另一个是 insert 。我的插入语句必须依赖于第一个操作(即 delete ),但是由于第一个操作尚未提交,我的插入失败(唯一约束)。但有趣的是,通常在同一个事务中,我应该能够在同一个事务中读取/查看未经授权的操作(我的旧专有框架能够做到这一点),但这不适用于我的场景,第二个插入仍然失败,因为它看到数据尚未删除。

I have 2 operations inside, one is delete, another one is insert. My insertion statement have to rely on the first operation (which is the delete), but now because of the first operation is not committed yet, my insertion fail (unique constraint). But this is funny that, usually within the same transaction, I should be able to read/see the uncommited operation in the same transaction (my old proprietary framework are able to do that), but this is not happening for my scenario, the second insertion still fail because it see the data is not yet deleted.

我尝试使用隔离 READ_UNCOMMITTED ,但它不行。

I try to use isolation READ_UNCOMMITTED, but it doesn't work.

我必须把这两个操作放在同一个事务中,因为任何一个失败都应该回滚这两个操作,我不能提交第一个操作然后继续第二个。

I have to put these two operation in same transaction, because any of the failure should rollback both operations, I can't commit the first operation then proceed to the second one.

我怎样才能在Spring框架中做到这一点?

How can I do that in Spring framework?

推荐答案

一般在Hibernate中,在同一个事务中,在刷新(提交)时,它总是遵循特定的顺序。

Generally in Hibernate , in the same transaction , while flushing(committing) it always follows a particular order.

首次执行插入,然后在刷新时执行删除

Inserts are first executed and then deletes are executed while flushing.

理想情况下,你的c ase,因为你之前删除插入只需调用 enitityManager.flush()之后显式删除

So ideally in your case , since you are deleting before insert just call enitityManager.flush() explicitly after delete .

或者也可以查看 EntityManager。 setFlushMode()方法,您可以将模式类型设置为 commit auto

Alternatively also have a look at EntityManager.setFlushMode() method where you can set to flush mode type to either commit or auto

这篇关于Spring Transactional注释,隔离不适用于READ_UNCOMMITTED的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 06:51
查看更多