Update auditing fields of entity when @OneToMany relation updates

Hi, I’m trying to update lastModifedAt and lastModifiedBy fields when trying to add or update child from parent entity, but it does not trigger modification of parrent. How can i achive this?

My Entities:

public class Term {

    @Id
    @Column(name = "id", nullable = false)
    @GeneratedValue(strategy = GenerationType.UUID)
    private UUID id;

    @CreatedDate
    @Column(name = "created_at", nullable = false)
    private Instant createdAt;

    @CreatedBy
    @Column(name = "created_by", nullable = false)
    private String createdBy;

    @LastModifiedDate
    @Column(name = "updated_at", nullable = false)
    private Instant updatedAt;

    @LastModifiedBy
    @Column(name = "updated_by", nullable = false)
    private String updatedBy;

    @OneToMany(mappedBy = "term", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
    private Set<TermContent> contents = new HashSet<>();

    public void addContent(TermContent content) {
        contents.add(content);
        content.setTerm(this);
    }
}

And how i am adding new content to term:

public TermContent addContent(UUID termId, AddContentRequest request) {

        Term term = termRepository.findEagerlyById(termId)
                .orElseThrow(() -> new EntityNotFoundException(Term.class, termId));

        TermContent termContent = new TermContent();
        termContent.setTerm(term);
        termContent.setName(request.getName());
        termContent.setLanguage(languageService.findById(request.getLanguageId()));
        termContent = termContentRepository.save(termContent);

        term.addContent(termContent);
        termRepository.save(term);

        return termContent;
    }

This was recently asked in the chat.

1 Like

Thanks, I’ll check it!