Search code examples
javahibernatehibernate-envers

AuditQuery how to join entites


I got 2 entities:

@Entity
@Getter
@Setter
@SequenceGenerator(name = "SEQ_STORE", sequenceName = "TABLE_A_SEQ", allocationSize = 1)
@Audited
@AuditTable("TABLE_A_ARCH")
@Table(name = "TABLE_A")
public class TableAEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_STORE")
    protected Long id;

    ..some fields

    @AuditJoinTable(name = "TABLE_B_ARCH")
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "tableA", orphanRemoval = true)
    @NotEmpty
    private Set<TableBEntity> dataB = Sets.newHashSet();

}

@Entity
@Getter
@Setter
@SequenceGenerator(name = "SEQ_STORE", sequenceName = "TABLE_B_SEQ", allocationSize = 1)
@Audited
@AuditTable("TABLE_B_ARCH")
@Table(name = "TABLE_B")
public class TableBEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_STORE")
    protected Long id;

    ..some fields

    @ManyToOne
    @JoinColumn(name = "table_a_id", nullable = false)
    private TableAEntity tableA;

}

When i perform operations on this entites all the information about that goes to archive tables. I want to select all history changes even from related entity TableBEntity

AuditReader auditReader = AuditReaderFactory.get(getEntityManager());

AuditQuery auditQuery = auditReader.createQuery()
    .forRevisionsOfEntity(TableAEntity.class, false, true)
    .traverseRelation("dataB", JoinType.INNER, "data_b")
    .addOrder(AuditEntity.revisionNumber().desc());

I tried even diffrent join types, but still I get an error:

org.hibernate.envers.exception.AuditException: This type of relation (..package..TableAEntity.dataB) isn't supported and can't be used in queries.

When i remove .traverseRelation("dataB", JoinType.INNER, "data_b") i only get changes from TableAEntity and changes from TableBEntity are ignored.


Solution

  • That is because the initial pass for relation traversal in Envers was only for to-one association mappings; hence why you're getting that error.

    The plan is to introduce support for to-many associations in Hibernate Envers 6.0, see HHH-11735.