每当在 中使用
,必须使用Query
注释(insert
、update
或 delete
)实现数据修改逻辑时JpaRepository@Transactional
(不一定在存储库方法上)和@Modifying
。
我的理解如下。 JpaRepository 提供的所有增删改查操作都是事务性的,除非我们覆盖它们。在存储库中实现方法时,我们需要确保它仍然是事务性的。只需使用@Transactional
注释即可实现。 readOnly 的默认值为 false,因此 spring“知道”这是一个修改查询。
问题是:为什么我们需要 @Modifying
注释(与 @Transactional
一起)?也许我遗漏了一些东西?
我知道类似 this 的讨论或that ,但是我缺少一个明确的解释,说明如果 @Transactional
携带了所需的所有信息,为什么必须使用 @Modifying
。
最佳答案
By default, CRUD methods on repository instances are transactional. For read operations, the transaction configuration readOnly flag is set to true. All others are configured with a plain @Transactional so that default transaction configuration applies.
和@Modifying回答了问题为什么我们需要@Modifying注释?
Indicates a query method should be considered as modifying query as that changes the way it needs to be executed. This annotation is only considered if used on query methods defined through a Query annotation). It's not applied on custom implementation methods or queries derived from the method name as they already have control over the underlying data access APIs or specify if they are modifying by their name.
Queries that require a
@Modifying
annotation include INSERT, UPDATE, DELETE, and DDL statements.
The @Modifying annotation is only relevant in combination with the @Query annotation. Derived query methods or custom methods do not require this Annotation.
(与@Transactional一起)
@Transactional
不需要与 @Modifying
一起使用。只是用 @Modifying
注解的方法应该在事务中执行。
关于java - 为什么我必须在 spring data jpa 中将 @Modifying 与 @Transactional 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60328189/