Transactional annotation on whole class + excluding a single method

后端 未结 2 2051
忘掉有多难
忘掉有多难 2021-01-01 11:47

I have a class with @Transactional annotation (instead of marking it for all of its method).

Although i have a single method inside that class that sho

2条回答
  •  悲&欢浪女
    2021-01-01 12:04

    Sorry to answer a six year old question, but I noticed the accepted answer doesn't actually answer the question. The question was how to have a method behave as though it was not annotated with @Transactional at all. Such a method will take part in a transaction if there is one, or execute non-transactionally if there is not. It will not suspend an existing transaction, or refuse to execute if there is one, one of which would be the result of the accepted answer.

    The propagation to use is Propagation.SUPPORTS (in other words annotate the method with @Transactional(propagation = SUPPORTS). This will take part in the transaction if there is one, or execute non-transactionally if not, just like a non-annotated method would.

    Not that according to the Javadoc it is not exactly the same as having no @Transactional annotation at all. It says:

    Support a current transaction, execute non-transactionally if none exists. Analogous to EJB transaction attribute of the same name.

    Note: For transaction managers with transaction synchronization, 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.

    The only way to have the method behave exacty as if it was not annotated with @Transactional at all is to do as OP suggests: don't annotate the class, but annotate all the other methods, but for most uses that will not be necessary and using Propagation.SUPPORTS will suffice.

提交回复
热议问题