我刚刚开始从事 Spring-data、Hibernate、MySQL、JPA 项目。我切换到 spring-data 这样我就不必担心手动创建查询。
我注意到使用 spring-data 时不需要使用 @Transactional
因为我也尝试了没有注释的查询。
是否有我应该/不应该使用 @Transactional
注释的特定原因?
作品:
@Transactional
public List listStudentsBySchool(long id) {
return repository.findByClasses_School_Id(id);
}
也有效:
public List listStudentsBySchool(long id) {
return repository.findByClasses_School_Id(id);
}
原文由 Byron Voorbach 发布,翻译遵循 CC BY-SA 4.0 许可协议
你的问题实际上是关于什么的?
@Repository
注释或@Transactional
的用法。@Repository
根本不需要,因为您声明的接口将由 Spring Data 基础结构创建并激活异常转换的代理支持。因此,在 Spring Data 存储库接口上使用此注释根本没有任何效果。@Transactional
- 对于 JPA 模块,我们在支持代理的实现类上有此注释(SimpleJpaRepository
)。这有两个原因:首先,持久化和删除对象需要 JPA 中的事务。因此,我们需要确保事务正在运行,我们通过使用@Transactional
注释的方法来做到这一点。Reading methods like
findAll()
andfindOne(…)
are using@Transactional(readOnly = true)
which is not strictly necessary but triggers a few optimizations in the transaction infrastructure (setting theFlushMode
至MANUAL
让持久性提供程序在关闭EntityManager
时可能跳过脏检查)。除此之外,该标志还在 JDBC 连接上设置,这会导致在该级别上进一步优化。根据您使用的数据库,它可以忽略表锁甚至拒绝您可能意外触发的写操作。因此,我们建议使用
@Transactional(readOnly = true)
作为查询方法,您也可以轻松实现将注释添加到存储库界面。确保将普通的@Transactional
添加到您可能已在该接口中声明或重新修饰的操作方法中。