所以我是 Spring 新手,目前对
@Transactional
注释感到困惑,我已经阅读了很多关于这个主题的问题和答案,但似乎我仍然不明白。
这是我的问题:
执行插入更新删除时需要
@Transactional
注解吗?当我试图证明这一点时,我仍然可以执行插入和更新。你知道为什么会这样吗?
如果您使用或不使用
@Transactional
注释,是否会带来任何性能优势或问题?就像连接管理一样。
如果我的程序中不使用
@Transactional
注解会发生什么?
根据我使用
@Transactional
的经验,更新查询将在方法完成后刷新并提交,在某些情况下我不希望发生这种情况。例如:
@Transactional
private void doSomething() {
TransactionEntity te = te.findById("");
try {
//fetch using feign and throw customTimCustomTimeoutException
} catch (CustomTimeoutException e) {
te.workflowFailure("doSomething");
repository.save(te);
}
//validation
//business logic
//save this save that
//end of the method and changes will be flushed and committed
}
如果在方法结束时,数据库脱机,它会回滚,你会失去所有进度,对吗?即使在 catch 块语句中的
repository.save(te)
中,数据库可能没问题,并且您不想失去该进度。有什么解决办法或想法吗?
@Transactional
接口时,不需要 CrudRepository
进行 CRUD 操作。默认情况下,所有这些方法都是事务性的。我猜你用的是这个。查看https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#transactions@Transactional(readOnly = true)
时,就会出现性能优势。例如,查看 SimpleJpaRepository。@Transactional
否则你会得到“java.lang.IllegalStateException: No transactional EntityManager available”。