为什么我们必须在 Data Jpa 中使用 @Modifying 注解进行查询 [英] why do we have to use @Modifying annotation for queries in Data Jpa

查看:27
本文介绍了为什么我们必须在 Data Jpa 中使用 @Modifying 注解进行查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我的 CRUD 接口中有一个方法可以从数据库中删除用户:

for example I have a method in my CRUD interface which deletes a user from the database:

public interface CrudUserRepository extends JpaRepository<User, Integer> {

    @Transactional
    @Modifying
    @Query("DELETE FROM User u WHERE u.id=:id")
    int delete(@Param("id") int id, @Param("userId") int userId);
}

此方法仅适用于注解@Modifying.但是这里的注解有什么必要呢?为什么spring无法分析查询并理解为修改查询?

This method will work only with the annotation @Modifying. But what is the need for the annotation here? Why cant spring analyze the query and understand that it is a modifying query?

推荐答案

这将触发注释到方法的查询为更新查询而不是选择查询.由于执行修改查询后 EntityManager 可能包含过时的实体,我们会自动清除它(详见 EntityManager.clear() 的 JavaDoc).这将有效地删除 EntityManager 中所有未刷新的更改.如果您不希望 EntityManager 被自动清除,您可以将 @Modifying 注解的 clearAutomatically 属性设置为 false;

This will trigger the query annotated to the method as updating query instead of a selecting one. As the EntityManager might contain outdated entities after the execution of the modifying query, we automatically clear it (see JavaDoc of EntityManager.clear() for details). This will effectively drop all non-flushed changes still pending in the EntityManager. If you don't wish the EntityManager to be cleared automatically you can set @Modifying annotation's clearAutomatically attribute to false;

有关更多详细信息,您可以点击此链接:-

for further detail you can follow this link:-

http://docs.spring.io/spring-data/jpa/docs/1.3.4.RELEASE/reference/html/jpa.repositories.html

这篇关于为什么我们必须在 Data Jpa 中使用 @Modifying 注解进行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆