Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring disable transactions for a single class method

In my Spring application, I have a class annotated with org.springframework.transaction.annotation.Transactional annotation.

Is it possible to discard transactions for a specific single method of this class without removing @Transactional from class level declarations? If so, please show an example

like image 858
alexanoid Avatar asked Nov 23 '17 20:11

alexanoid


People also ask

Can @transactional annotation only be used at class level?

Annotation Type Transactional. Describes a transaction attribute on an individual method or on a class. When this annotation is declared at the class level, it applies as a default to all methods of the declaring class and its subclasses.

Does @transactional work on protected methods?

When using proxies, you should apply the @Transactional annotation only to methods with public visibility. If you do annotate protected, private or package-visible methods with the @Transactional annotation, no error is raised, but the annotated method does not exhibit the configured transactional settings.

Can we use @transactional on class?

2.2. How to Use @Transactional. We can put the annotation on definitions of interfaces, classes, or directly on methods. They override each other according to the priority order; from lowest to highest we have: interface, superclass, class, interface method, superclass method, and class method.


1 Answers

According to Transactional documentation:

public @interface Transactional

Describes a transaction attribute on an individual method or on a class.

So additionally to the class-level annotation just define the correct attribute at your method to disable the default transaction handling.

example:

@Transactional(propagation=Propagation.NEVER)
public long notInTransaction(AnythingData anythingData) throws Exception {
   //JDBC code...
}

Will throw an exception if this method is called inside an active transaction. Whereas Propagation.NOT_SUPPORTED will "suspend" the current transaction and make sure that the method is called non transactional.

like image 132
aschoerk Avatar answered Sep 22 '22 14:09

aschoerk