繁体   English   中英

使用@Transactional(readOnly = true) 有什么好处?

[英]What are advantages of using @Transactional(readOnly = true)?

我是初学者,据我所知,@ @Transactional @Transactional的类或方法的所有内部工作都将包装在一个事务中,并且来自外部源的所有调用都将创建一个新事务,但为什么我们实际上在下面的存储库中需要这些注释,在常见情况下将它与readOnly = true一起使用有什么好处? 这是使用Spring & Hibernate ( 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);

}

来自 Spring Data 作者 Oliver Gierke 的解释

findAll() 和 findOne(…) 之类的读取方法使用 @Transactional(readOnly = true) 这不是绝对必要的,但会触发事务基础结构中的一些优化(将 FlushMode 设置为 MANUAL 以让持久性提供程序在关闭时可能跳过脏检查实体管理器)。 除此之外,该标志还在 JDBC 连接上设置,这会导致在该级别上进一步优化。

根据您使用的数据库,它可以忽略表锁甚至拒绝您可能意外触发的写操作。 因此,我们建议使用 @Transactional(readOnly = true) 作为查询方法,这样您就可以轻松地将注释添加到存储库界面。 确保将普通的 @Transactional 添加到您可能已在该接口中声明或重新修饰的操作方法中。

延伸阅读:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM