java - 为什么我必须在 spring data jpa 中将 @Modifying 与 @Transactional 一起使用?

标签 java spring spring-data-jpa

每当在 中使用 Query 注释(insertupdatedelete)实现数据修改逻辑时JpaRepository,必须使用@Transactional(不一定在存储库方法上)和@Modifying

我的理解如下。 JpaRepository 提供的所有增删改查操作都是事务性的,除非我们覆盖它们。在存储库中实现方法时,我们需要确保它仍然是事务性的。只需使用@Transactional注释即可实现。 readOnly 的默认值为 false,因此 spring“知道”这是一个修改查询。

问题是:为什么我们需要 @Modifying 注释(与 @Transactional 一起)?也许我遗漏了一些东西?

我知道类似 this 的讨论或that ,但是我缺少一个明确的解释,说明如果 @Transactional 携带了所需的所有信息,为什么必须使用 @Modifying

最佳答案

来自reference docs

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.

also

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/

相关文章:

java - Spring 数据 jpa @query 和可分页

java - 按下按钮后 android studio 中的 Activity 不会切换

java - 将 applicationContext.xml 中定义的 beans 移动到 jboss 配置

java - 从 Spring Boot 应用程序中排除 @Configuration

spring - 处理Grails服务中的错误和消息的最佳方法

spring - 如何将自定义查询参数添加到分页 hatoas 结果中的下一个/上一个链接?

java - 如何在 Spring Boot 的 Spring Security 级别启用 CORS

java - 尝试在 hibernate 中获取结果集时抛出异常 "Cannot cast ' java.lang.Object[ ]' to"

java.util.zip.ZipException : error in opening zip file

java - Spring JPA Repository保存不插入数据库