比较子实体列表时,获取父实体ID

时间:2019-08-25 19:49:11

标签: java javers

Javers v5.6.3

我有一个父实体,其中包含一个子实体列表。当我比较2个父母列表并且在一个孩子中发现一个更改时,我需要知道哪个父母包含更改后的孩子。

我的实体

@TypeName("Parent")
class Parent {
    @Id
    private String parentId;
    private Set<Child> children;
}

@TypeName("Child")
class Child {
    @Id
    private String childId;
    private String someProp;
}

我要比较的内容:

为了简洁起见,切换到Groovy:

def list1 = [
      new Parent(parentId:'p1', children: [new Child(childId: 'c1')]),
      new Parent(parentId:'p2', children: [new Child(childId: 'c2', someProp: 'fig')])
]
def list2 = [
      new Parent(parentId:'p1', children: [new Child(childId: 'c1', someProp: 'apple')]),
      new Parent(parentId:'p2', children: [new Child(childId: 'c2', someProp: 'fig')])
]

我如何与众不同:

Javers javers = JaversBuilder.javers()
                  .withListCompareAlgorithm(ListCompareAlgorithm.AS_SET)
                  .build();

Diff diff = javers.compareCollections(list1, list2);
System.out.println(diff);

输出:

Diff:
* changes on Child/c1 :
  - 'someProp' value changed from '' to 'apple'

我的问题:

我如何发现哪个父级包含Child / c1?

这类似于shouldDetectSalaryChange() example,除了我有很多老板。使用该示例,给定具有不同下属的老板列表,那么如何找出Great Developer的老板?

我是否需要创建一个自定义的Parent比较器,还是有一种从内置比较器中找出答案的方法?

1 个答案:

答案 0 :(得分:1)

具有此映射,您无法发现哪个Parent包含Child / c1,因为Child类被映射为Entity。因此Javers不知道这种亲子关系。

您可以更改Child类到ValueObject的映射以使此关系明确:

    @TypeName("Parent")
    class Parent {
        @Id
        private String parentId
        private Set<Child> children
    }

    @TypeName("Child")
    class Child {
        private String childId
        private String someProp
    }

然后:

        Javers javers = JaversBuilder.javers()
                .withListCompareAlgorithm(ListCompareAlgorithm.AS_SET)
                .wi
                .build()

        Diff diff = javers.compareCollections(list1, list2, Parent)

        println(diff)

打印:

Diff:
* new object: Parent/p1#children/5f6ade8312fb0c5d60f756841e23af65
* object removed: Parent/p1#children/9de1d946eab394f971263c33e297f86d
* changes on Parent/p1 :
  - 'children' collection changes :
    . 'Parent/p1#children/9de1d946eab394f971263c33e297f86d' removed
    . 'Parent/p1#children/5f6ade8312fb0c5d60f756841e23af65' added