我是 Spring(Boot)Data JPA 的新手。我正在尝试使用具有事务注释的方法中的 repo1.saveAll 和 repo2.saveAll 将数据插入到 2 个不同的表中。
@Autowired
Table1Repo repo1; //corresponding to Table1; interface extending JPA's CRUDRepository
@Autowired
Table2Repo repo2; //corresponding to Table2; interface extending JPA's CRUDRepository
@Transactional
void saveMyData(List<Table1Entity> dataForTable1,List<Table2Entity> dataForTable2){
//i want the commit to happen AFTER both statements have been completed
repo1.saveAll(dataForTable1)
repo2.saveAll(dataForTable2)
}
我希望通过 @Transactional 注释将数据一起提交到两个表,或者不提交任何内容。
但是当我检查表时,我发现saveAll到table1完成后,数据在数据库中的table1中可用(从SQL Developer studio检查),然后是saveAll继续进行table2。这违反了事务的原子性。我期待 @Transactional 注释来处理这个问题。
当我深入研究时,我发现SimpleJPARepository的save/saveAll/delete/deleteAll等方法也已经用@Transactional注释进行了注释。这就是为什么我在方法中使用的 @Transactional 注释被忽略,并且由于 saveAll 方法的 @Transactional 注释,在我的方法中每次进行 saveAll 调用时都会提交数据这意味着每个 saveAll 调用都在其自己的事务中执行。这是否意味着在像 saveMyData 这样的自定义方法上使用 @Transactional 在从该方法内调用存储库上的 saveAll 方法时没有任何意义?