3

I have two audited entities, A and B. Entity A holds a collection of entity B (annotated as One-to-many relationship). When inserting a new instance of A into the database, all rows of A and B are at the same revision (let's say revision 1). Then, there is an update on A which only affect the instances of entity B (cascade type is merge). So after the update, the entity A is still at revision 1, whereas the entities of B are at revision 2 (new MOD entry in the audit table).

The problem is when I retrieve all the revisions of A, I would expect to get 2 revisions in return : one for the creation, one for the modification of the owning collection of B. I can get this behaviour in case of ManyToMany but I can't get it work the same way with a OneToMany relation.

(I'm using Hibernate 3.6.10-Final)

user639466
  • 103
  • 1
  • 6
  • related to http://stackoverflow.com/questions/10529982/how-to-retrieve-the-audited-revision-of-relations – Jean Jun 28 '12 at 09:22

1 Answers1

2

I solved my problem by adding a hidden lastUpdated date field on my equivalent of your A entity.

@Entity
public class A {
    private Date lastModified;
    @OneToMany(mappedBy = "a", cascade = CascadeType.ALL )
    private List<B> blist;
    public void touch(){
        lastModified=new Date();
    }
}

In the related entities (like you B field), I added the following :

public class B {
    @ManyToOne
    private A a; 
    
    @PreUpdate
    public void ensureParentUpdated(){
        if(a!=null){
            a.touch();
        }
    }
}

This ensures that a revision is added to A whenever a revision is added to B.

sjakovac
  • 124
  • 8
Jean
  • 21,329
  • 5
  • 46
  • 64