Update LastModifiedDate of owned entity

55 Views Asked by At

I have two objects. Workflow and Task. Task does contain workflow.

@Entity
public class Workflow {

  @Column(name = "last_modified_date")
  private Date lastModifiedDate;
...}


@Entity
@EntityListeners(TaskAuditListener.class)
public class Task {

  @ManyToOne
  @JoinColumn(name = "workflow_id")
  private Workflow workflow;
...}

On any update of Task object, I want to update lastModifiedDate value on Workflow. To avoid repetitive code, I would like to use TaskAuditListener with @PreUpdate.

@Component
public class TaskAuditListener {

  private static WorkflowRepository workflowRepository;

  @Autowired
  public void TaskAuditListener(WorkflowRepository workflowRepository) {
    TaskAuditListener.workflowRepository = workflowRepository;
  }

  @PreUpdate
  void beforeUpdate(Task task) {
    workflowRepository.updateCreatedByTaskId(task.getId(),
        new Date(System.currentTimeMillis()));
  }

My repository method is this:

  @Modifying
  @Transactional
  @Query("UPDATE Workflow w SET w.lastModifiedDate = :lastModifiedDate WHERE w.id = :workflowId")
  void updateLastModifiedDateById(String workflowId, Date lastModifiedDate);

The error I am receiving is java.lang.StackOverflowError: null and is triggered by the workflowRepository.updateLastModifiedDateById() method.

Why is @PreUpdate cyclically triggered, when in my @Query I update Workflow object, not Task?

Or is there any better to achieve this?

2

There are 2 best solutions below

1
Ananta On

JPA already have annotation for it:

@Column(name = "last_modified_date")
@LastModifiedDate
private Date lastModifiedDate;

Or you can create method to run before updating:

@PreUpdate
protected void onUpdate() {
    lastModifiedDate = new Date(System.currentTimeMillis());
}
1
Andrei Lisa On

What about: @UpdateTimestamp on field lastModifiedDate