社区,
我有一个问题是在同一个事务中的entitymanager#save之后计算实体。问题是,我总是得到一个不可思议的计数。我想在实体管理器保存后计算实体的当前行,但结果始终是当前行计数+保存的实体(尚未提交)。它看起来像一个经典的脏读问题。 出于这个原因,我使用Propagation.REQUIRES_NEW和Isolation.REPEATABLE_READ来仅计算提交的实体。 如果我使用h2数据库,结果是我预期的结果,但是如果我使用MYSQL则会有另一个结果。
这里有一些代码片段:
服务:
@Service
public class MyTestService {
@Autowired
private EntityRepository entityRepository;
@Transactional
public void doSomeLogic() {
entityRepository.save(new Entity());
final long count = count();
if (count != 0) {
throw new IllegalStateException("Entity count should be 0 but is " + count);
}
}
@Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.REPEATABLE_READ)
public long count() {
return entityRepository.count();
}
}
回购:
public interface EntityRepository extends PagingAndSortingRepository<Entity, Long>, JpaSpecificationExecutor<Entity> {
// @Override
// @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW,
// isolation = Isolation.REPEATABLE_READ)
// long count();
}
测试:
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Autowired
private MyTestService myTestService;
@Test
public void testEntityCounterWithMultiThreads() {
myTestService.doSomeLogic();
}
}
如果我取消注释存储库代码,一切正常,但我不明白其中的区别。
有人知道我的想法错误在哪里吗?