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?
JPA already have annotation for it:
Or you can create method to run before updating: