已使用 @Transactional 注释的方法中的 TransactionRequiredException

TransactionRequiredException in a method that is already annotated with @Transactional

public void postPessoa() {
    savePessoa();
    initializePessoa();
}

@Transactional(rollbackOn = {Exception.class})
public void savePessoa() {
    pessoa = getEntityManager().merge(pessoa);
}

如果我调用 postPessoa(),我会在 merge() 中得到 TransactionRequiredException,但是如果我直接从 JSF 调用 savePessoa(),它就可以工作,我不明白为什么会这样行为。

JSF:

<p:commandButton id="btnSalvar" value="Salvar" action="#{pessoasController.savePessoa}"/>

<p:commandButton id="btnSalvar" value="Salvar" action="#{pessoasController.postPessoa}"/>

你必须添加

@Transactional

...class 级或 postPessoa() 级。

来自 spring-doc:

In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional. Also, the proxy must be fully initialized to provide the expected behaviour so you should not rely on this feature in your initialization code, i.e. @PostConstruct.