【问题标题】:What are advantages of using @Transactional(readOnly = true)?使用@Transactional(readOnly = true) 有什么好处?
【发布时间】:2017-12-12 13:53:11
【问题描述】:

我是初学者,据我了解@Transactional 只需确保使用@Transactional 注释的类或方法的所有内部工作都将包含在一个事务中,并且来自外部源的所有调用都将创建一个新事务但是为什么我们实际上需要在下面的存储库中使用这些注释,以及在常见情况下将其与readOnly = true 一起使用有什么好处?这是使用 SpringHibernate (https://github.com/spring-projects/spring-petclinic) 的 Spring 宠物诊所示例应用程序。

/**
 * Repository class for <code>Pet</code> domain objects All method names are compliant with Spring Data naming
 * conventions so this interface can easily be extended for Spring Data See here: http://static.springsource.org/spring-data/jpa/docs/current/reference/html/jpa.repositories.html#jpa.query-methods.query-creation
 *
 * @author Ken Krebs
 * @author Juergen Hoeller
 * @author Sam Brannen
 * @author Michael Isvy
 */
public interface PetRepository extends Repository<Pet, Integer> {

    /**
     * Retrieve all {@link PetType}s from the data store.
     * @return a Collection of {@link PetType}s.
     */
    @Query("SELECT ptype FROM PetType ptype ORDER BY ptype.name")
    @Transactional(readOnly = true)
    List<PetType> findPetTypes();

    /**
     * Retrieve a {@link Pet} from the data store by id.
     * @param id the id to search for
     * @return the {@link Pet} if found
     */
    @Transactional(readOnly = true)
    Pet findById(Integer id);

    /**
     * Save a {@link Pet} to the data store, either inserting or updating it.
     * @param pet the {@link Pet} to save
     */
    void save(Pet pet);

}

【问题讨论】:

  • 这能回答你的问题吗? stackoverflow.com/questions/1614139/…
  • 您好,如果回答对您有帮助,别忘了接受/点赞。
  • 请注意,@Transactional(readOnly = true) 注释可以放在类/接口上,而不是每个方法上。比在“也写”方法上只放@Transactional,就像在SimpleJpaRepository 中一样。

标签: spring hibernate transactions spring-data spring-transactions


【解决方案1】:

来自 Spring Data 作者 Oliver Gierke 的explanation

使用 findAll() 和 findOne(...) 等读取方法 @Transactional(readOnly = true) 这不是绝对必要的,但 触发交易基础设施的一些优化 (将 FlushMode 设置为 MANUAL 以让持久性提供程序 关闭 EntityManager 时可能会跳过脏检查)。超过 该标志也设置在 JDBC 连接上,这会导致 在该级别上进一步优化。

根据您使用的数据库,它可以省略表锁,甚至可以省略 拒绝您可能意外触发的写入操作。因此我们 推荐使用 @Transactional(readOnly = true) 作为查询方法 好吧,您可以轻松地向您添加该注释 存储接口。确保将一个普通的 @Transactional 添加到 操作您可能已经声明或重新装饰的方法 界面。

进一步阅读:

【讨论】:

    猜你喜欢
    • 2017-11-08
    • 2017-06-06
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    • 1970-01-01
    相关资源
    最近更新 更多