审计:修改子实体的父实体(Javers / Envers / ... + Hibernate)

时间:2019-03-30 02:14:51

标签: java hibernate audit hibernate-envers javers

我的应用程序中有一个父对象,需要对它进行版本控制(审核),这意味着:每次对它的更改或对它的n个较深子对象的任何持久化都存在时,就会进行新的修订必须创建。

@Entity class Document {
    @Id String name;
    // some props ...
    @OneToMany List<Page> pages;
    // getters and setters ...
}

@Entity class Page {
    @Id Long number;
    @ManyToOne Document document;
    // some props ...
    String header;
    // getters and setters ...
}

在上面的示例中,如果我要更改页面的页眉,则应为整个Document实体保留新的修订版本:

// retrieve document
Document document = documentRepository.findById(myBookId);
// change something on first found page
document.getPages().iterator().next().setHeader("Hello World");
// persist the document
documentRepository.save(document);
// new revision of the document!

我当时正在考虑使用JaversEnvers,但似乎他们都做不到。

你们中有人知道如何在这些库上执行类似的操作吗?还是知道我可以为此目的使用的任何图书馆?

1 个答案:

答案 0 :(得分:1)

如果将Page类映射为ValueObject,然后使用Shadow查询,则可以在Javers中实现。另外,您应该一直提交Document

    @Entity
    class Document {
        @Id String name
        @OneToMany List<Page> pages

        @Override
        String toString() {
            "Document $name, pages:$pages"
        }
    }

    @org.javers.core.metamodel.annotation.ValueObject
    @Entity
    @ToString
    class Page {
        @Id Long number
        @ManyToOne Document document
        String header

        @Override
        String toString() {
            "Page $number, $header"
        }
    }

    def "should treat Document as aggregate"(){
      given:
      def javers = JaversBuilder.javers().build()

      def doc = new Document(name:"1", pages: [new Page(header:"a"), new Page(header:"b")])
      javers.commit("author", doc)

      when:
      doc = new Document(name:"1", pages: [new Page(header:"a"), new Page(header:"ccc")])
      javers.commit("author", doc)

      def shadows = javers.findShadows(QueryBuilder.byClass(Document).build())

      then:
      shadows

      shadows.forEach{s -> println(s.commitMetadata.commitDate.toString() + " " + s.get())}
    }

输出:

23:25:47.297 [main] INFO  org.javers.core.Javers - Commit(id:1.0, snapshots:3, author:author, changes - NewObject:3), done in 56 millis (diff:45, persist:11)
23:25:47.315 [main] INFO  org.javers.core.Javers - Commit(id:2.0, snapshots:1, author:author, changes - ValueChange:1), done in 17 millis (diff:17, persist:0)
23:25:47.337 [main] DEBUG org.javers.JQL - SHALLOW query: 4 snapshots loaded (entities: 1, valueObjects: 3)
23:25:47.358 [main] DEBUG org.javers.JQL - queryForShadows executed: 
2019-04-08T23:25:47.298618 Document 1, pages:[Page null, a, Page null, ccc]
2019-04-08T23:25:47.275570 Document 1, pages:[Page null, a, Page null, b]