Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force transaction commit in Spring Boot test?

How can I force a transaction commit in Spring Boot (with Spring Data) while running a method and not after the method ?

I've read here that it should be possible with @Transactional(propagation = Propagation.REQUIRES_NEW) in another class but doesn't work for me.

Any hints? I'm using Spring Boot v1.5.2.RELEASE.

@RunWith(SpringRunner.class)
@SpringBootTest
public class CommitTest {

    @Autowired
    TestRepo repo;

    @Transactional
    @Commit
    @Test
    public void testCommit() {
        repo.createPerson();
        System.out.println("I want a commit here!");
        // ...
        System.out.println("Something after the commit...");
    }
}

@Repository
public class TestRepo {

    @Autowired
    private PersonRepository personRepo;

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void createPerson() {
        personRepo.save(new Person("test"));
    }
}
like image 507
flash Avatar asked May 19 '17 22:05

flash


People also ask

How do I force a commit in Spring Boot?

Commit a transaction by calling the commit() method on the Connection interface. This tells your database to perform all required consistency checks and persist the changes permanently. Rollback all operations performed during the transaction by calling the rollback() method on the Connection interface.

When and where do you use @transactional in testing?

@Transactional spans the transaction for entire test method, so if you use some dao (like in your case) that transaction will be rolledback also, however if some method uses transaction propagation type other than REQUIRED , for example REQUIRED_NEW , call to db can be performed anyway, because REQUIRED_NEW suspends ...

What does @transactional mean in Spring Boot?

The @Transactional annotation is metadata that specifies that an interface, class, or method must have transactional semantics; for example, "start a brand new read-only transaction when this method is invoked, suspending any existing transaction".

What is use of @transactional annotation in Spring?

One of the most essential parts of Spring MVC is the @Transactional annotation, which provides broad support for transaction management and allows developers to concentrate on business logic rather than worrying about data integrity in the event of system failures.


1 Answers

Use the helper class org.springframework.test.context.transaction.TestTransaction (since Spring 4.1).

Tests are rolled back per default. To really commit one needs to do

// do something before the commit 

TestTransaction.flagForCommit(); // need this, otherwise the next line does a rollback
TestTransaction.end();
TestTransaction.start();

// do something in new transaction
like image 174
LazyProphet Avatar answered Sep 20 '22 14:09

LazyProphet