Mysql spring boot unit test @Transactional data is not rolled back

The database engine is wrong. Use MYISAM and change it to InnoDB to solve it.

There are several ways to view the database engine, such as using mysql workbench

java sample code

@SpringBootTest
@RunWith(SpringRunner.class)
@Slf4j
@Transactional
public class StudentTest {

    @Autowired
    private StudentDAO StudentDAO;

    @Test
    public void test() {
        Student s = new Student();
        s.setStudentId("0001");
        StudentDAO.save(s);
    }
}

Official description

https://docs.spring.io/spring/docs/5.2.6.RELEASE/spring-framework-reference/testing.html#spring-testing-annotation-rollback

@Rollback indicates whether the transaction for a transactional test method should be rolled back after the test method has completed.

If true, the transaction is rolled back. Otherwise, the transaction is committed (see also @Commit).

Rollback for integration tests in the Spring TestContext Framework defaults to true even if @Rollback is not explicitly declared.

Invalid attempt

At the beginning, I didn’t locate the engine problem, so I checked some information, such as:

https://stackoverflow.com/questions/12626502/rollback-transaction-after-test

“ extends AbstractTransactionalJUnit4SpringContextTests”

或 “adding annotation '@Transactional ' separately for each function“

other

turn on

spring.jpa.show-sql=true

At the same time log level is set to info

<Root level="info">
    <AppenderRef ref="RollingFile"/>
    <AppenderRef ref="Console"/>
</Root>

You can see the log of the transaction and rollback

05-22-2020 14:01:26.204 INFO [main] [] o.s.t.c.t.TransactionContext: Began transaction (1) for test context [DefaultTestContext@1c7f52c8 testClass = StudentTest, testInstance = com.xx.Student.StudentTest@616a370b, testMethod = test@StudentTest, testException = [null], 


05-22-2020 14:01:26.355 INFO [main] [] o.s.t.c.t.TransactionContext: Rolled back transaction for test: [DefaultTestContext@1c7f52c8 testClass = StudentTest, testInstance = com.xx.Student.StudentTest@616a370b, testMethod = test@StudentTest, testException = [null], 

 

Guess you like

Origin blog.csdn.net/wuzhong8809/article/details/106281761