Reputation: 4830
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?
Upvotes: 1
Views: 205