当事务只读取数据时,是否应该避免使用注解@Transactional?

Should I avoid using the annotation @Transactional when the transaction only reads data?

我已经从使用 TransactionProxyFactoryBean 的旧式事务管理迁移到 Spring 推荐的声明式事务管理,以避免不时出现的事务异常。

对于交易 save update delete 我添加了注释:

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)

对我来说效果很好。

问题是:

Should I avoid using the annotation @Transactional when the transaction only reads data?

示例:

public TradeData getTrade(long tradeId) throws Exception {
   return em.find(TradeData.class, tradeId);
}

阅读 this 文章后,其中说:

"Better yet, just avoid using the @Transactional annotation altogether when doing read operations, as shown in Listing 10:"

有点懵,不太明白

如果您服务的某个特定方法只是从数据库中读取信息是的,您可以将其设置为只读

    @Transactional(readOnly = true)
    public Object yourReadOnlyMethod(){}

对于 JDBC 的只读操作,您不需要 @Transactional,因为它不需要事务,Hibernate 需要!所以你可以使用@Transactional(readOnly = true)。那你确定你没有不小心更新,删除,插入东西。