Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @Transactional on class vs on method

I'm using Spring Boot and Spring Data JPA.

Having following class:

import org.springframework.transaction.annotation.Transactional;

@Transactional(propagation = Propagation.REQUIRED)
public class Foo{

    public void bar(){}

}

will bar() and any other member method be also transactional?

I also have second question. On many tutorials people tend to do something like this:

import org.springframework.transaction.annotation.Transactional;

@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public class Foo{

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public void bar(){}

}

Why? Is using readOnly true and false a it matter of security?

like image 251
ex3v Avatar asked Dec 25 '14 13:12

ex3v


People also ask

Can we use @transactional on class?

5.1. At a high level, Spring creates proxies for all the classes annotated with @Transactional, either on the class or on any of the methods. The proxy allows the framework to inject transactional logic before and after the running method, mainly for starting and committing the transaction.

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.

When @transactional is used on top of a class?

@Transactional can be used on top of class or method, in classes or interfaces. If used on top of class, it applies to all public methods in this class.

What is the function of the @transactional annotation at the class level?

Transactional annotation provides the application the ability to declaratively control transaction boundaries on CDI managed beans, as well as classes defined as managed beans by the Java EE specification, at both the class and method level where method level annotations override those at the class level.


1 Answers

The annotation at the method level completely overrides the annotation at the type-level.

The @Transactional annotation on the class level will be applied to every method in the class.

However, when a method is annotated with @Transactional, this will take precedence over the transactional settings defined at the class level.

like image 98
Ankur Singhal Avatar answered Oct 03 '22 18:10

Ankur Singhal