Java 标记为仅回滚且原因未知的事务
我有一些代码如下Java 标记为仅回滚且原因未知的事务,java,spring,transactions,spring-data-jpa,Java,Spring,Transactions,Spring Data Jpa,我有一些代码如下 public class ServiceImpl implements Service { @Transactional public myObject methodOne() { if (myCondition) return methodTwo(); else anotherMethod(); } public myObject methodTwo()
public class ServiceImpl implements Service
{
@Transactional
public myObject methodOne()
{
if (myCondition)
return methodTwo();
else
anotherMethod();
}
public myObject methodTwo()
{
int retryCount = 1;
myObject myObject = null;
while (retryCount <= 10) {
try {
myObject = repository.save();
break;
} catch (DataIntegrityViolationException ignored) {
retryCount++;
}
}
if (myObject == null){
throw new MyException();
}
}
}
公共类ServiceImpl实现服务
{
@交易的
公共myObject methodOne()
{
if(霉菌病)
返回方法二();
其他的
anotherMethod();
}
公共myObject方法二()
{
int-retryCount=1;
myObject myObject=null;
而(retryCount似乎是由于子事务中的回滚规则
如何methodTwo
返回myObject
并在methodOne
public class ServiceImpl implements Service
{
@Transactional
public myObject methodOne()
{
myObject myObject = methodTwo()'
if (myObject == null){
throw new MyException();
}
return myObject;
}
public myObject methodTwo()
{
int retryCount = 1;
myObject myObject = null;
while (retryCount <= 10) {
try {
myObject = repository.save();
break;
} catch (DataIntegrityViolationException ignored) {
retryCount++;
}
}
return myObject;
}
}
公共类ServiceImpl实现服务
{
@交易的
公共myObject methodOne()
{
myObject myObject=methodTwo()
if(myObject==null){
抛出新的MyException();
}
返回myObject;
}
公共myObject方法二()
{
int-retryCount=1;
myObject myObject=null;
而Spring意识到的事务中的(retryCountAnyRuntimeException
)将标记该事务进行回滚
考虑到repository.save()
的事务传播以及对repository.save()
的调用导致了DataIntegrityViolationException
,它是RuntimeException
的子类,即使在methodTwo()处理/捕获事务,也会标记为回滚
/注释的属性可用于控制回滚行为。例如
@Transactional(noRollbackFor=DataIntegrityViolationException.class)
注意:Spring意识到的RuntimeException是,如果一个RuntimeException
被显式抛出并在同一个方法中处理,Spring将不会意识到该异常,也不会将周围的事务标记为回滚是的,这在您的用例中发生了。感谢您的帮助,我只添加了@org.springframework.transaction.annotation.Transactional(norollboor={DataIntegrityViolationException.class})但是仍然抛出上述异常请更新问题的完整堆栈跟踪。将抛出异常,但该异常不会发生回滚,这是我们使用该注释属性所说的。我假设抛出的异常将是不同的异常。另外,请检查这是否对您有帮助。