Home > Back-end >  Hibernate: Envers does not work with derived classes with no member fields
Hibernate: Envers does not work with derived classes with no member fields

Time:08-30

Given the following base class...

...
import org.hibernate.envers.Audited;

@Audited
@Entity
@Table(
    name = "account",
    indexes = {
      @Index(name = "account_currency_id_idx", columnList = "currency_id")
    })
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "account_type")
public class Account {

  @Id
  @GeneratedValue
  @Setter(AccessLevel.NONE)
  @NotNull
  private Long id;

  @Audited
  @LastModifiedDate
  @Column(name = "last_modified_date_time")
  @Setter(AccessLevel.NONE)
  private LocalDateTime lastModifiedDateTime;

  @Audited
  @LastModifiedBy
  @Setter(AccessLevel.NONE)
  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "last_modified_by_user_id", referencedColumnName = "id")
  @Audited(targetAuditMode = NOT_AUDITED)
  private User lastModifiedByUser;

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "currency_id", referencedColumnName = "id")
  @ApiFieldMappingProperty("currencyId")
  @Audited(targetAuditMode = NOT_AUDITED)
  private Currency currency;

  @NotNull
  @Column(name = "open_date", nullable = false)
  private LocalDate openDate;

  @Column(name = "close_date")
  private LocalDate closeDate;

  ...
}

... I defined two derived classes with no member fields but with a discriminator value that let me differentiate account types automatically. Here's the first derived class...

...
@Entity(name = "domestic_account")
@DiscriminatorValue("DOMESTIC")
public DomesticAccount extends Account {
}

... and here's the second one:

@Entity(name = "offshore_account")
@DiscriminatorValue("OFFSHORE")
public OffshoreAccount extends Account {
}

In the code I never use class Account directly; instead, I always instantiate (and save) either a DomesticAccount or a OffshoreAccount.

The problem is that even if I enabled auditing with @Audited, changes get never logged and table ACCOUNT_AUD remains empty.

Am I missing something? Any help is really appreciated.

CodePudding user response:

In the end, annotating the derived classes with @Audited fixed the issue:

...
import org.hibernate.envers.Audited;

@Audited
@Entity(name = "domestic_account")
@DiscriminatorValue("DOMESTIC")
public DomesticAccount extends Account {
}

Also many thanks to Christian Beikov for his support.

  • Related