The accepted answer of using propogation of NOT_SUPPORTED
or NEVER
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.
@Transactional(propagation=NOT_SUPPORTED)
? – Hexosan@Transactional(propagation = Propagation.NOT_SUPPORTED)
– Acrocarpous