Spring Transactions With Supports Propagation

拥有回忆 提交于 2019-11-30 03:35:42

问题


I would like to understand the use of having a spring transaction with Propagation Supports. The java docs mention that if the method which has @Transactional(propagation = Propagation.SUPPORTS) is called from within a transaction it supports the transaction but if no transaction exists, the method is executed non-transactionally.

Isn't this already the behavior of spring transactions irrespective of Propagation.SUPPORTS?



public class ServiceBean {

    @Transactional(propagation = Propagation.SUPPORTS)
    public void methodWithSupportsTx() {
        //perform some database operations
    }
}

public class OtherServiceBean {

    @Transactional(propagation = Propagation.REQUIRED)
    public void methodWithRequiredTx() {
        //perform some database operations
        serviceBean.methodWithSupportsTx();
    }
}


In the above code example, irrespective of whether methodWithSupportsTx() has @Transactional(propagation = Propagation.SUPPORTS) annotation it would be executed in a transaction depending on whether methodWithRequiredTx() has @Transactional annotation, right?

So what's the need/use of having a propagation level SUPPORTS?


回答1:


From javadoc:

Note: For transaction managers with transaction synchronization, PROPAGATION_SUPPORTS is slightly different from no transaction at all, as it defines a transaction scope that synchronization will apply for. As a consequence, the same resources (JDBC Connection, Hibernate Session, etc) will be shared for the entire specified scope. Note that this depends on the actual synchronization configuration of the transaction manager.

So, it means that, for example, multiple invocations of Hibernate's SessionFactory.getCurrentSession() inside methodWithSupportsTx() would return the same session.




回答2:


A required transaction will create a new transaction if none exists. Therefore a new transaction would be made when you call serviceBean.methodWithSupportsTx(). If your method is truly transactional you will see an error from spring if no transaction exists.



来源:https://stackoverflow.com/questions/6437828/spring-transactions-with-supports-propagation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!