比较两个包含数组列表的对象

时间:2019-12-08 08:30:14

标签: javers

首先,只需检查四个模型所有者,所有者,地址(与您的不同),CodeInfo 从这里 https://github.com/rckr20/javers/tree/master/javerscore/src/test/java/org/javers/core/examples/model

现在我正在用LEVENSHTEIN_DISTANCE算法比较两个Owners对象。

/*Comparing List */
Owners Owners1 = new Owners();
Owners1.add(new Owner(1,new Addresss("Delhi",null,new CodeInfo(null))));

Owners Owners2 = new Owners();
Owners2.add(new Owner(2,new Addresss("Noida","SEZ",new CodeInfo("abc"))));

Diff diff = JaversBuilder.javers().withListCompareAlgorithm(ListCompareAlgorithm.LEVENSHTEIN_DISTANCE).build().compare(Owners1, Owners2);

现在,您将问为什么我不使用列表而不是使用所有者(扩展了所有者的ArrayList)。其次,我不能在这里使用compareCollection()。我目前的项目架构就是这样,我无法更改。

因此,在比较中,我需要的是值更改,但返回列表更改。

Diff:

changes on org.javers.core.graph.LiveGraphFactory$ListWrapper/ :
'list' collection changes :
0. 'org.divik.javers.JaversBasic.Owner@3f0846c6' changed to 'org.divik.javers.JaversBasic.Owner@77a98a6a'
And just for solving this i just tried to convert the Owners object into the JsonNode.

您也可以检查此 https://easyupload.io/aez105

仅通过将所有者映射为Entity尝试过,但结果相同。 但是得到了解决方案 我们可以像这样比较它。

Diff diff = JaversBuilder.javers().withListCompareAlgorithm(ListCompareAlgorithm.LEVENSHTEIN_DISTANCE).build().compareCollections(((List)Owners1), (List)Owners2,Owner.class);

但是如果我将Owners(即扩展数组列表的类)嵌套在某些模型中,则会再次遇到问题

   Example:--
    class Car{
  @Id
   int id;
   Owners owners;

   public Car(int id, Owners owners) {
     this.id= id;
     this.owners = owners;
    }
   }

我再次得到嘈杂的结果。

2 个答案:

答案 0 :(得分:0)

您的问题是您使用Owners.class

的想法
class Owners extends ArrayList<Owner> implements Serializable {        
}

扩展了ArrayList而未添加任何内容。在这种情况下,javers无法识别类型参数,因此将Owners视为List<Object>,从而简化了diff。

在比较顶级集合时,应该使用正确的方法比较集合,命名为compareCollections,并且在javers的API中对此进行了详细说明:

    /**
     * Deeply compares two top-level collections.
     * <br/><br/>
     *
     * Introduced due to the lack of possibility to statically
     * determine type of collection items when two top-level collections are passed as references to
     * {@link #compare(Object, Object)}.
     * <br/><br/>
     *
     * @see <a href="http://javers.org/documentation/diff-examples/#compare-collections">
     *     Compare top-level collections example</a>
     */
    <T> Diff compareCollections(Collection<T> oldVersion, Collection<T> currentVersion, Class<T> itemClass);

用法:

Diff diff = javers.compareCollections(Owners1, Owners2, Owner.class)

答案 1 :(得分:0)

  1. 我可以做的任何事情使javer理解所有者的类型。

  2. 由于我的实际用例中有多个列表,因此使用compareCollection比较每个列表都不是很有效,因为它们不在顶层。

  3. 我可以实现CustomList或Property比较器之类的东西,并使用itemType.class

  4. 为每个此类列表注册它吗?

示例:- javers = JaversBuilder.javers().registerCustomType(Owners,new CustomListComparator())

并重写CustomListComparator方法并调用compareCollection并在其中传递类型,即本例中的Owner。