简体   繁体   中英

How to Audit two tables with one-to-one relation through hibernate envers?

So I have two entity classes, Subscription and MailDetail . There is a one-to-one relation between them. Here are the classes -

Subscription.class-

@Data
@Entity
@AllArgsConstructor
@Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED)
public class Subscription {

@Id
@GeneratedValue(strategy =`enter code here` GenerationType.SEQUENCE, generator = "subscription_subscription_id_seq")
@SequenceGenerator(initialValue = 1, allocationSize enter code here= 1, name = "subscription_subscription_id_seq", sequenceName = "subscription_subscription_id_seq")
@Column
private Long subscriptionId;

@Column
private String template;

@Column
private String fileFormat;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "mail_id", referencedColumnName = "mail_id")
private MailDetail mailDetail;

}

MailDetail.class -

@Data
@Entity
@Audited
public class MailDetail {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "mail_detail_mail_id_seq")
    @SequenceGenerator(initialValue = 1, allocationSize = 1, name = "mail_detail_mail_id_seq", sequenceName = "mail_detail_mail_id_seq")
    @Column
    private Long mailId;

    @Column
    private String emailId;
}

So this creates two audit tables, subscription_aud and mail_detail_aud . Creation/Updates in mail_detail table is done through Subscription repository only. So my requirement is that whenever there is a change in mail_details table's fields, I need an audit entry in subscription_aud. Or basically i want change in mail_detail table be considered as a change in subscription table.

I am using hibernate envers for auditing. How can i achieve this?

Unfortunately, not with how Envers is currently designed.

Any to-many association that is either had its contents modified or elements in the collection changed will propagate an audit change for the owning side of the relationship by default; however that can even be disabled by setting org.hibernate.envers.revision_on_collection_change to false . When this configuration setting is disabled, only element-collections will propagate a change to the owner because elements in such a collection are not entities, therefore can only be queried through the owning entity.

For to-one associations, this is a completely different story.

The only way to accomplish what you want would be to introduce some column on your Subscription instance that owns the MailDetail and change the value of that column when this use case happens. Based on the fact you only modify MailDetail via the aggregate root Subscription , this should work however I agree that its less than ideal.

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