Stop Hibernate from updating collections when they have not changed

前端 未结 2 1184
别跟我提以往
别跟我提以往 2021-02-07 23:11

I have two entity beans defined as follows (unrelated stuff removed):

@Entity
@Table(...)
public class MasterItem implements java.io.Serializable {

  private Se         


        
相关标签:
2条回答
  • 2021-02-07 23:52

    try to add a revision column (optimistic locking) to your entities

    @Version
    Date lastModified;
    
    0 讨论(0)
  • 2021-02-07 23:56

    That's the semantical difference between update() and merge().

    From Christian Bauer and Gavin King's Java Persistence with Hibernate (I can't find clear explanation of this behaviour in the Hibernate docs):

    The update() method forces an update to the persistent state of the object in the database, always scheduling an SQL UPDATE.
    ...
    It doesn’t matter if the item object is modified before or after it’s passed to update().
    ...
    Hibernate always treats the object as dirty and schedules an SQL UPDATE., which will be executed during flush.

    On the other hand, merge() queries the database first, and doesn't perform update if state haven't changed.

    So, if you want Hibernate to query the database first, you need to use merge() (though default behaviour of update() can be overriden by specifing @org.hibernate.annotations.Entity(selectBeforeUpdate = true) on your entities).

    0 讨论(0)
提交回复
热议问题