简体   繁体   中英

How to audit class that has OneToMany unidirectional relationship?

I'm using Spring Data JPA for Auditing. There's a unidirectional relationship between classes Article and File . The Article class looks like this:

@Getter
@Entity
@SuperBuilder(toBuilder = true)
@Table(name = "article")
public class Article extends AuditEntity {
    ...

    @Builder.Default
    @OneToMany(fetch = FetchType.LAZY, orphanRemoval = true)
    @JoinTable(name = "article_additional_file",
            joinColumns = @JoinColumn(name = "article_id"),
            inverseJoinColumns = @JoinColumn(name = "additional_file_id"))
    private List<File> additionalFiles = new ArrayList<>();

   ...
}

The problem is, when changes occur in the file list (owned files get deleted or added), the modifiedDate field (which is in AuditEntity class and it's annotated with @LastModifiedDate annotation) is not updated (it works with all other fields). And I cannot make it a bidirectional relationship since other classes own the File class as well. So my question is, how to trigger the update of field modifiedDate when changes occur in the file list?

EDIT I'd prefer not to use Enver, if that's possible. I need to use as little additional libraries as possible

Instead of using @JoinTable use @AuditJoinTable

Info from the hibernate documentation:

When a collection is mapped using these two annotations (@OneToMany + @JoinColumn), Hibernate doesn't generate a join table. Envers, however, has to do this, so that when you read the revisions in which the related entity has changed, you don't get false results.

To be able to name the additional join table, there is a special annotation: @AuditJoinTable, which has similar semantics to JPA's @JoinTable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM