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

问题描述 投票:0回答:1

我的应用程序中有一种父对象需要进行版本控制(审计),我的意思是:每次对其进行更改或者对其任何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,但似乎没有人能够做到这一点。

你们中的任何人都知道如何在这些库中做类似的事吗?或者知道我可以用于此目的的任何库?

java hibernate audit hibernate-envers javers
1个回答
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]
© www.soinside.com 2019 - 2024. All rights reserved.