Rajesh Gupta
Rajesh Gupta

Reputation: 188

What is difference between @Transactional(rollbackFor = Exception.class) and @Transactional(propagation=Propagation.REQUIRED)

@Transactional(rollbackFor = Exception.class) 
public void foo1() {
    `/**Some Code**/`
}

@Transactional(propagation=Propagation.REQUIRED)
public void foo2() {
    `/**Some Code**/`
}

Upvotes: 3

Views: 18572

Answers (3)

ltwonders
ltwonders

Reputation: 1

What propagation and rollbackFor focus on are different, propagation cares the way how transaction needs or creates, rollbackFor cares whether the existed transaction roll back or not while the specified exception occurs.

Please refer to the @Propagation docs to get more details.

As the default propagation level is Propagation.REQUIRED, so the main difference between two annotations in your question is whether rollbacking for Exception(checked Exception) or not.

Upvotes: 0

M. Deinum
M. Deinum

Reputation: 125158

@Transactional(propagation=Propagation.REQUIRED) and @Transactional(rollbackFor = Exception.class) are roughly the same. As propagation=Propagation.REQUIRED is the default. So with that in mind they are equivalent to @Transactional(propagation=Propagation.REQUIRED) and @Transactional(propagation=Propagation.REQUIRED, rollbackFor = Exception.class).

The only difference is that without the rollbackFor = Exception.class it will rollback only for RuntimeExceptions and Error s not for other exceptions that occur. (This is the same for JEE when using EJB and the behavior has been translated to Spring as well).

This is also explained in the javadoc of @Transactional.

Upvotes: 9

Ammar Ali
Ammar Ali

Reputation: 690

Firstly, by default propagation is always present if you write it or not. If you write rollbackFor then the transaction will be rollback if an exception happens.

Here is a link for more help:@Transactional

Upvotes: 1

Related Questions