我使用Spring@Transactional在单个函数中插入多个表。
对于我使用EntityManager的每个实体的读/写,让我们假设在我的函数中,有10个表正在用数据更新,然后在这种情况下,所有10个表都被锁定,直到事务还没有结束,这对用户体验来说是不好的,因为这会导致用户等待\延迟,因为他们正在查看使用这些表的少数页面。
那么,在整个插入表过程中,我如何防止锁定表进行读取呢?有没有办法避免使用事务并进行独立于单个表的插入。以下是的代码片段
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_UNCOMMITTED, noRollbackFor = {SQLException.class, IllegalStateException.class, PersistenceException.class})
public BaseImportDtoRoot importData(BaseImportDtoRoot baseDto) throws Exception {
try{
table1.fninsert(); .. call each class to insert entity wise
table2.fninsert();
}
catch(Exception e){
}
}
public class table1(){
fninsert(){
MstTable tb1= new MstTable ();
tb1= modMap.map(MstTableDto,
MstTable.class);
entityManager.persist(tb1);
entityManager.flush();
entityManager.clear();
}
有没有办法避免使用事务
你不能,只要你保存数据,就会创建事务,所以你需要:
-
使用
@Transactional
,它将DML封装在事务中 -
手动创建交易
entityManager.getTransaction((.begin((;entityManager.sistent(数据(;entityManager.getTransaction((.commit((;
并执行单表独立插入
我认为您的意思是为每次插入创建单独的事务。您可以通过创建多个方法来实现这一点,其中注释@Transactional
,并删除importData
方法上的@Transaction
注释。(通过这样做,importData
方法不再是原子的(
如果我误解了什么,请纠正我。