Search code examples
javahibernate-envers

Prevent Hibernate relation table from ever being audited


I am using Envers for auditing and am trying to prevent an entity from ever being audited. If the entity is a part of a relation, like below, I want the FK field to be persisted on the related audit table (for personId on Receipt_Audit).

@Entity
@Audited
@Table(name = "Receipt")
public class ReceiptModel {
  @Valid
  @ManyToOne
  @JoinColumn(name = "personId")
  private PersonModel person;

  ...
}

The PersonModel is configured as follows:

@Entity
@Audited(targetAuditMode = NOT_AUDITED)
@Table(name = "Person")
public class PersonModel {
  ...
}

Persisting a Receipt works great with the configuration above. But, when trying to persist a Person, it blows up because no audit table exists for that entity.


Solution

  • What you actually want to do is to use the @Audited(targetAuditMode=NOT_AUDITED) on the actual relation inside Receipt and don't mark Person as audited.

    @Entity
    @Audited
    @Table(name = "Receipt")
    public class ReceiptModel {
      @Valid
      @ManyToOne
      @JoinColumn(name = "personId")
      @Audited(targetAuditMode = NOT_AUDITED)
      private PersonModel person;
      ...
    }
    
    @Entity
    @Table(name = "Person")
    public class PersonModel {
    }