Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does @Transactional automatically rollback transaction in Spring 3?

I'm running as unit test and it automatically goes back even if I don't use the@rollback in spring 3.1. My test looks like

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:application-context.xml" })
public class PersonServiceTest {

    @Test
    @Transactional
    public void savePerson() {
            Person person = createPerson();
            personService.savePerson(person);
    }
}

Is Rollback behavior is set by default?

like image 852
fastcodejava Avatar asked Aug 05 '12 00:08

fastcodejava


People also ask

Does @transactional rollback?

The @Transactional annotation makes use of the attributes rollbackFor or rollbackForClassName to rollback the transactions, and the attributes noRollbackFor or noRollbackForClassName to avoid rollback on listed exceptions. The default rollback behavior in the declarative approach will rollback on runtime exceptions.

How does Spring @transactional really work?

So when you annotate a method with @Transactional , Spring dynamically creates a proxy that implements the same interface(s) as the class you're annotating. And when clients make calls into your object, the calls are intercepted and the behaviors injected via the proxy mechanism.

What types of exception does Spring automatically rollback a transaction?

Note however that the Spring Framework's transaction infrastructure code will, by default, only mark a transaction for rollback in the case of runtime, unchecked exceptions; that is, when the thrown exception is an instance or subclass of RuntimeException. (Errors will also - by default - result in a rollback.)

Which of these by default will cause a rollback of the Spring transaction?

By default, the only exceptions that cause a transaction to roll back are the unchecked exceptions (like RuntimeException ).


1 Answers

By default SpringJUnit4ClassRunner will rollback transactions automatically.

To negate the effect, use @TransactionConfiguration(defaultRollback=false) on your test class or @Rollback(false) on each test.

like image 138
jeff Avatar answered Oct 19 '22 05:10

jeff