Search code examples
hibernatejpa

Hibernate @UpdateTimestamp not change in cascade manner


I have this Hibernate Dao classes.

@Table(name = "entity1")
public class Entity1 {
  //...other fields...

  @UpdateTimestamp
  private Date updateDate;

  @OneToMany(cascade = {CascadeType.ALL}, orphanRemoval = true)
  @JoinColumn(name = "entity1_id")
  private Set<Entity2> entity2Set;
}


@Table(name = "entity2")
public class Entity2 {
  //...other fields...

  @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
  private Entity1 entity1;
}

Value of updateDate field changes if values of Entity1 change.

In case when values of Entity1 fields not change and values of Entity2 fields change - value of updateDate field not change.

Is there any way to force Hibernate to change it in this case?

I've tried to add cascade = CascadeType.ALL but it have no effect.

Of course I can set value of updateDate to null during update but in this case updateDate change even when no one field of Entity1 and Entity2 changed.


Solution

  • Finally I've found the solution with javax.persistence.PreUpdate:

    @Getter
    @Setter
    @Entity
    @Table(name = "entity1")
    public class Entity1 {
    
      @UpdateTimestamp
      private Date updateDate;
    
      @OneToMany
      @JoinColumn(name = "entity1_id")
      private Set<Entity2> entity2Set;
    }
    
    
    @Getter
    @Setter
    @Entity
    @Table(name = "entity2")
    public class Entity2 {
    
      @PreUpdate
      public void preUpdate() {
        if (entity1 != null) {
          entity1.setUpdateDate(new Date());
        }
      }
    
      @ManyToOne(fetch = FetchType.LAZY)
      private Entity1 entity1;
    }