首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用@Transactional(readOnly = true)有哪些优点?

问使用@Transactional(readOnly = true)有哪些优点?
EN

Stack Overflow用户
提问于 2017-07-08 09:46:55
回答 1查看 14.4K关注 0票数 20

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

代码语言:javascript
复制
/**
 * 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);

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-08 12:30:52

来自Oliver的解释 -- Spring数据作者:

像findAll()和findOne(…)这样的阅读方法正在使用@ transaction (readOnly= true),这不是绝对必要的,但会在事务基础结构中触发一些优化(将FlushMode设置为手动,使持久性提供程序在关闭EntityManager时可能跳过脏检查)。除此之外,还在JDBC连接上设置了标志,这将导致在该级别上进一步优化。 根据您使用的数据库,它可以省略表锁,甚至拒绝您可能意外触发的写操作。因此,我们还建议对查询方法使用@Transactional(readOnly = true),您可以轻松地将该注释添加到存储库接口中。请确保在该接口中可能已经声明或重新修饰的操作方法中添加了一个普通的@Trans手记。

进一步读:

票数 30
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44984781

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档