Help create AspectJ equivellent to @PrePersist and @PreUpdate for audit use case

851 Views Asked by At

In JPA, there is @PrePersist and @PreUpdate annotations that allow operations before CRUD operations. I am trying to find out the ApsectJ equivalent to this.

My use case is a JPA application that was built by one team, now would like to add an Audit Aspect to each Pre-Persist and Pre-Update that occurs, without adding a lifecycle listener to the original Entity.

1

There are 1 best solutions below

0
On BEST ANSWER

If the entities don't have @PrePersist and @PreUpdate methods, you can use AspectJ intertype declarations (ITDs) to introduce those methods.

public aspect Audit {
    declare parents: @Entity * implements AuditedEntity;

    public interface AuditedEntity {}

    @PrePersist
    public void AuditedEntity.prePersistAuditing() {
       ... auditing logic
    }

    ... similar code for @PreUpdate
}

If the entities already have the methods, you can advise those to perform auditing.