數據庫引擎不對,使用提 MYISAM ,改成InnoDB 後解決。
查看數據庫引擎的方式有好幾種,比如 用 mysql workbench
java 示例代碼
@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);
}
}
官方說明
@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.
無效的嘗試
一開始沒有定位到是引擎的問題,查閱了一些資料,比如:
https://stackoverflow.com/questions/12626502/rollback-transaction-after-test
“ extends AbstractTransactionalJUnit4SpringContextTests”
或 “adding annotation '@Transactional ' separately for each function“
其它
打開
spring.jpa.show-sql=true
同時log level 定爲info
<Root level="info">
<AppenderRef ref="RollingFile"/>
<AppenderRef ref="Console"/>
</Root>
可以看到事務及回滾的日誌
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],