简体   繁体   中英

Hibernate - Entity audit

I have one entity and I want to track all changes therefore I created new Entity for audit. Below is my primary entity:

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@EntityListeners(AuditingEntityListener.class)
@Table(name = "primary")
public class PrimaryEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "primary_id")
    private Long id;

    private String name;

    @LazyCollection(LazyCollectionOption.FALSE)
    @ElementCollection
    @CollectionTable(
            name = "primary_attachments",
            joinColumns = @JoinColumn(name = "primary_id")
    )
    private List<String> attachments;

    @CreatedDate
    @Temporal(TemporalType.DATE)
    private Date createDate;

    @LastModifiedDate
    @Temporal(TemporalType.DATE)
    private Date lastModifiedDate;
}

And below is my entity for audit:

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@EntityListeners(AuditingEntityListener.class)
@Table(name = "primary_audit")
public class PrimaryEntityAudit {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "audit_id")
    private Long id;

    @NotNull
    @Column(name = "primary_entity_id")
    private Long primaryId;

    private String name;

    @LazyCollection(LazyCollectionOption.FALSE)
    @ElementCollection
    @CollectionTable(
            name = "primary_attachments_audit",
            joinColumns = @JoinColumn(name = "primary_entity_id")
    )
    private List<String> attachments = new ArrayList<>();

    @CreatedDate
    @Temporal(TemporalType.DATE)
    private Date createDate;

    public PrimaryEntityAudit(PrimaryEntity primaryEntity) {
        this.primaryId = primaryEntity.getId();
        this.attachments.addAll(primaryEntity.getAttachments());
        this.createDate = new Date();
    }
}

And before update primary entity I create new PrimaryEntityAudit and save this object and then update the primary entity. And operation is successful and object PrimaryEntityAudit is saved, but attachments from PrimaryEntityAudit aren't saved.

I tried also in constructor of ProjectEntityAudit do setAttachments, but then I got an Exception: HibernateExcpetion: Found shared references to collection.

How should I map the collections of audit for saving old state of PrimaryEntity attachments?

You should look at the following hibernate module Envers

It provides features for versioning and auditing

It is preferable to not reinvent the wheel except if you have technicals constraints which prevent you to use some frameworks or others.

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