gpt4 book ai didi

java - 将 CustomPropertyComparator 与 java.util.List 结合使用

转载 作者:行者123 更新时间:2023-12-02 10:34:08 24 4
gpt4 key购买 nike

我创建了一个 CustomPropertyComparator 来使用它来比较 JAXB 创建的对象。因此,就我而言,我无法使用框架提供的 @DiffIgnore 注释。此外,JAXB 生成的集合基于 java.util.List 而不是 java.util.Collection。不幸的是,我无法让 javers 使用我的 CustomPropertyComparatorList 接口(interface)。

public class Person {    
private String name;
private String ignoreThis;
}

public class Company {
private String id;
private Person owner;
private Collection<Person> clients;
private List<Person> partners;
}

Comparator 仅比较名称,但忽略 ignoreThis 字段:

public class EntityComparator implements CustomPropertyComparator<Person, ValueChange> {
public ValueChange compare(Person left, Person right, GlobalId affectedId, Property property) {
if (left.getName().equals(right.getName()))
return null;
return new ValueChange(affectedId, "entity/name", left.getName(), right.getName());
}
}

我的测试用例如下所示:

此测试有效,因为它比较集合

@Test
public void equalEntityClientTest() {
Person e1 = new Person("james", "ignore this");
Company le1 = new Company("1", null, Arrays.asList(e1), null);

Person e2 = new Person("james", "");
Company le2 = new Company("1", null, Arrays.asList(e2), null);
Diff diff = javers.compare(le1, le2);

System.out.println(diff);
assertEquals(0, diff.getChanges().size());
}

此测试失败,因为它没有使用我的比较器来比较实体,并且被忽略字段的差异为true

@Test
public void equalEntityPartnerTest() {
Person e1 = new Person("james", "ignore this");
Company le1 = new Company("1", e1, null, Arrays.asList(e1));

Person e2 = new Person("james", "");
Company le2 = new Company("1", e2, null, Arrays.asList(e2));
Diff diff = javers.compare(le1, le2);

System.out.println(diff);
assertEquals(0, diff.getChanges().size());
}

在 javers 的引用中,他们解释了如果您有自定义 Collection-Interface,则需要实现自己的比较器,如果您使用不基于 java.util.Collection 的集合,则可以。 。但实际上,我希望 javers 库支持 java.util.List 。另外,我无法弄清楚如何为列表界面添加/创建比较器。

可以在https://github.com/baumgartner/javerstest下找到一个工作示例。

最佳答案

您在这里触及了两个问题。您的第一个测试通过了,因为 Javers 忽略了 Collection 属性,并且仅记录了此警告:

10:19:40.332 [main] WARN  o.j.c.d.a.CollectionChangeFakeAppender - Collections: Field Collection<Person> clients; //declared in Company
are not equals but can't be compared. Raw Collection properties are not supported. Expected Set, List or any of their subclasses. JaVers uses different algorithms for comparing Sets and Lists and needs to know (statically) which one to test.

我认为这不太好,所以我创建了一个问题,请参阅 https://github.com/javers/javers/issues/746

第二个问题涉及 CustomPropertyComparator。它被设计用于比较像 Multimap 这样的大型结构,并且在比较 List 项时 JaVers 不会调用它,因为当您比较 List 项时,您需要 boolean equals(a,b) 方法。这就是 CustomValueComparator 的作用。

尽管如此,CustomPropertyComparator 还可以扩展为具有boolean equals(a,b) 方法。我为此创建了第二期,请参阅 https://github.com/javers/javers/issues/747

关于java - 将 CustomPropertyComparator 与 java.util.List 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53418466/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com