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"));
}
}
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.
@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 ...
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".
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With