Mike Cantrell
Mike Cantrell

Reputation: 726

Hibernate Envers throwing EntityNotFoundException when fetching deleted parent objects

I have the following simple data structure (details omitted for brevity):

@Audited
@Entity
class SettingsGroup implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Integer id

    @OneToMany(mappedBy = "group", cascade = [CascadeType.ALL])
    @OrderBy("key")
    List<SettingsEntry> entries = []

}



@Audited
@Entity
class SettingsEntry implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Integer id

    @ManyToOne
    SettingsGroup group

}

I've set the org.hibernate.envers.store_data_at_delete=true flag. Upon fetching the revisions for SettingsEntry, it will throw an EntityNotFoundException while trying to lazy fetch the associated group from the _aud table.

def reader = AuditReaderFactory.get(manager)
def query = reader.createQuery().forRevisionsOfEntity(SettingsEntry, false, true)
audits = query.resultList.collect {
    //noinspection GroovyAssignabilityCheck
    new AuditRevision<T>(entity:it[0], revision: it[1], type: it[2])
}   

I took a look at the SQL generated and it appears to be filtering out delete revision types while trying to fetch the parent record which causes no records to show up:

select *
from settings_group_aud sg 
where sg.rev=(
  select max(sg2.rev) from settings_group_aud sg2 where sg2.rev<=3 and sg.id=sg2.id
) and sg.revtype<>2 and sg.id=1

There are records in the table.. it just that the most recent is a delete:

select * from SETTINGS_GROUP_AUD;
ID      NAME    ENVIRONMENT     KEY_NAME    REV     REVTYPE  
1   test    prod    Default Key 2   0
1   test    prod    Default Key 3   2
(2 rows, 1 ms)

Is there a way to tweak the lazy initialization within Envers to prevent the filtering of deleted rev types? That would fix my problem. I'm just not seeing anything which is configurable.

My other option is to just off org.hibernate.envers.store_data_at_delete again but I'd prefer to keep it on if possible. This seems a little like a bug but I'm new to Envers so maybe I'm just looking at this all wrong :-)

Upvotes: 2

Views: 1568

Answers (1)

adamw
adamw

Reputation: 8636

Unfortunately that looks like a bug when navigating a deleted entity's graph. Please report to https://hibernate.onjira.com/secure/Dashboard.jspa.

The solution probably would be not to select the deleted entities in the query: forRevisionsOfEntity(SettingsEntry, false, false). The last element of the list will then be the entity as it was when it was deleted.

Upvotes: 2

Related Questions