简体   繁体   中英

JPA/Hibernate: how to automatically update fields on entity update

I'm using Camel and JPA to persist entities to a Postgres DB. In each entity I have a field called "history" which contains all the old values of the given entity. I'm looking for a way to populate this field automatically before each update operations. Surfing the web, I've found the JPA interceptors, but I've seen that they are used for auditing/logging purposes. Am I wrong? What's the best way to do this?

JPA/Hibernate interceptors (which one depends on the version you're using) are one way to do this. Auditing/logging are similar to what you want to do, ie automatically update some column/property when the entity itself is updated (any property). Just note that manual update queries circumvent those interceptors so those should be avoided.

How you use those interceptors depends on how you want to implement that history functionality though. If you're doing it by generating some string/byte representation and storing it in a column it should work. If you're planning to create another entity etc. you might have to collect the changes/old values in the interceptor and upon successful commit you store the collected values. AFAIK it's not possible (at least not easy) to create a new entity when the interceptors have been invoked.

@Entity
@Table(name = "entities")    
public class Entity {
  ...

  private Date created;
  private Date updated;

  @PrePersist
  protected void onCreate() {
    created = new Date();
  }

  @PreUpdate
  protected void onUpdate() {
    updated = new Date();
  }
}

You can use @EntityListeners and provide your entity Listener class to it, and you can also reuse this whenever you want

In your entity Listener class, you can provide callback methods with @PrePersit, @PostPersist, @PreUpdate, @PostUpdate, @PreDelete, @PostDelete annotations. These methods will get called automatically for their respective actions.

You can read Spring Data JPA Auditing: Saving CreatedBy, CreatedDate, LastModifiedBy, LastModifiedDate automatically for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM