Search code examples
spring-bootforeign-keyshibernate-enversis-empty

Foreign key empty on Envers audit table for relation OneToMany


I have the following relation and the foreign key is always empty in the audit table after the new revision:

@ManyToOne
@Audited(targetAuditMode=RelationshipTargetAuditMode.NOT_AUDITED)
@JoinColumn(name="mail_iid")
@private Mail mail;

...

@OneToMany(cascade=Cascade.ALL, orphan = true, fetch= fetchType.LAZY)
@JoinColumn(name="mail_iid")
private List<Attachments> attachments;

After the insertion of a new register, the original table have the iid but not the revision one.

Somebody knows about this issue.


Solution

  • There is only one way for this to happen, which is not managing bidirectional relationships properly.

    I suspect you are never calling Attachments#setMail to assign the newly created Mail entity to the Attachments entities and instead simply add the Attachments entity to the collection that your Mail entity cascades.

    This type of one-sided maintenance of bidirectional relationships is wrong and can lead to really incorrect results, particularly if entity instances are being inspected from the 1LC and are never being refreshed from the database; which is precisely why you're seeing the audit table with null in your mail_iid field.

    Your code should make sure that both sides of the relationship get set properly

    // setup bidirectional mappings
    attachments.setMail( mail );
    mail.getAttachments().add( attachments );
    

    When you do it this way, you'll end up with mail_iid being populated in your audit table as you would have expected and also avoids any issues when traversing cached instances of an entity's object graph that is already loaded in the 1LC.