Hibernate Envers: Retrieving the right revisions of an entity with a collection property

前端 未结 3 617
醉话见心
醉话见心 2021-01-27 06:18

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

相关标签:
3条回答
  • 2021-01-27 06:24

    In Hibernate we could control the loading of children by specifying lazy. So, you need to add the below line to your class definition in hibernate configuration for it to load all the associations in both read/write cases.

    <cache usage="read-write"/>
    

    If you have marked CacheMode.REFRESH then it will write items to the second-level cache. Do not read from the second-level cache.

    If you don't have issues in loading the children at the time of parent you could turn of lazy which will return the updated information.

    0 讨论(0)
  • 2021-01-27 06:27

    I solved a similar 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();
        }
    }
    

    Then 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 even though it requires custom code in many entities.

    In your case this will ensure that A's history actually contains the revisions of B. this way you only need one query to get all the revisions for the whole A, Bs graph

    0 讨论(0)
  • 2021-01-27 06:32

    If you read entity A at revision 2, you will get the right data.

    There is no way currently to get a list of revisions where an entity or related entities changed (as is your case - rev 2 is a change only in B, not in a).

    0 讨论(0)
提交回复
热议问题