jpa 保存/saveAll上的@ translation注解与调用saveAll的自定义方法上的@ translation注解

dauxcl2d  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(84)

Commit multiple tables at once in spring boot没有帮助
我是Spring( Boot )Data JPA的新手。我正在尝试从具有transactional annotation的方法中使用 repo1.saveAllrepo2.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)
}

字符串
我希望数据一起提交到两个表中,或者使用 @ transmitting * 注解不提交任何数据。
但是当我检查表时,我发现在 saveAlltable 1完成之后,数据在数据库 * 中的table 1中可用(从SQL Developer studio检查)
,然后 saveAlltable 2继续进行。这违反了事务的原子性。我希望 @ translation * annotation能解决这个问题。
当我挖进去的时候,我发现 SimpleJPARepository 的 * 保存/saveAll/delete/deleteAll
等方法也已经用 *@ translation * annotation进行了注解。这就是为什么我为我的方法使用的 *@ translation * annotation被忽略,并且由于 saveAll 方法的 *@ translation *,数据在我的方法中的每个 saveAll 调用时都被提交的原因吗annotation意味着每个 saveAll 调用都是在它自己的transaction中执行的。这是否意味着在自定义方法(如 saveMyData)上使用 *@ transaction *,当从该方法内部调用repo上的 saveAll 方法时,没有任何意义?

wkyowqbh

wkyowqbh1#

Transaction annotation作为方法开始的单个工作单元执行,并保证All or Nothing,即原子性。换句话说,即使@ transaction附加到方法,除非附加了requires_new选项,否则它不会被分离到单独的transaction中。可疑的问题是,当用@ transaction注解的方法从内部类中未用@注解的方法调用时,在这种情况下,@ transmitting将无法按预期工作,因为spring bean充当代理。

相关问题