使用Hibernate SPRING JPA更新所有实体实例,即使使用一个实体调用保存也是如此 [英] SPRING JPA with Hibernate updating all entity instances even if save is called with one entity

查看:92
本文介绍了使用Hibernate SPRING JPA更新所有实体实例,即使使用一个实体调用保存也是如此的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring JPARepository和hibernate并且有一个关于实体更新的问题。
我通过传递一个实体来调用jparepository.save(实体),但是在跟踪日志中,我可以看到为数据库中的其他行发布的更新语句。
在调用save之前,我有一个findAll,一些实体的值正在改变。
但我只传递一个实体进行保存,但仍然保存了所有更新的实体。
您可以提供任何有关这方面的信息。

解决方案

当您从数据库加载实体时,管理实体。
如果您更改管理实体(并稍后提交事务),则不需要明确保存它们。 (这是托管的意思。)

但是Hibernate不会立即更新数据库,而是等到:




  • 您提交交易

  • 您调用 EntityManager.flush

  • 你执行一些数据库查询或通过Hibernate保存! (当你绕过Hibernate并执行查询时,例如通过普通的JDBC / Spring JDBC模板,那么你首先需要调用 EntityManager.flush ,否则你可能看不到不是刷新数据( https://stackoverflow.com/a/29825882/280244 ))



  • 这就是你观察到的结果:


    • 1)你加载一些实体,所以他们成为托管

    • 2)您修改它们,但hibernate仍然不执行sql更新

    • 3)实体或保存一个实体,hibernate刷新更改


    I am using Spring JPARepository with hibernate and have one question on entity update. I am calling jparepository.save(entity) by passing a single entity but in the trace logs i can see update statements issued for other rows in the database also. Before calling save , i have a findAll and the value of some entities are getting changed. but i am passing only one entity for save , but still all the updated entities are getting saved. Can you please provide any info on this.

    解决方案

    When you load entities from the database then this entities are "managed entities". If you change "managed entities" (and submit the transaction later) you do NOT need to save them explicit. (This is what "managed" mean.)

    But Hibernate will not update the database immediately, instead it will wait until:

    • you commit the transaction
    • you invoke EntityManager.flush or
    • you execute some Database Query or Save via Hibernate! (when you bypass Hibernate and execute the query for example by plain JDBC/Spring JDBC Template, then you need to invoke EntityManager.flush first, if not you will may not see the not jet flushed data (https://stackoverflow.com/a/29825882/280244))

    And this is what you observed:

    • 1) you load some entities, so they become managed
    • 2) you modify them, but hibernate still does not execute the sql updates
    • 3) you query for some entity or save one entity, hibernate flush the changes

    这篇关于使用Hibernate SPRING JPA更新所有实体实例,即使使用一个实体调用保存也是如此的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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