Search code examples
javadatejpacollectionspersist

How to set modifiedDate on an Entity when a dependent property changes


Assume the JPA-Entity Foo. By adding annotations, i can handle updating the createdDate and modifiedDate properties. After changing name and persisting Foo, createdDate is updated correctly. But this does not work for bars which is a List of Bar Entities

@Entity
class Foo {
  ...

  String name;

  @OneToMany(cascade = CascadeType.PERSIST)
  List<Bar> bars;

  Date modifiedDate;
  Date createdDate;

  @PrePersist
  public void updateCreatedDate() {
    dateCreated = new Date();
  }

  @PreUpdate
  public void updateModifiedDate() {
    lastModified = new Date();
  }

  ...
}

@Entity
class Bar {
  ...
}

Is it possible to update Foo if one Item in bars changes and is persisted?


Solution

  • You might encapsulate every modification to the list of bars, and mark the entity as dirty (by setting the modification date to another value, for example) each time the list is modified:

    public List<Bar> getBars() {
        return Collections.unmodifiableList(this.bars);
    }
    
    public void addBar(Bar b) {
        this.bars.add(b);
        this.modifiedDate = new Date(0L);
    }
    
    ...
    

    Note that this will generate more queries, because adding a bar normally needs just one insert in the bar table (and one in the join table if a join table is used). Now every bar addition will also cause an update in the Foo table.