Search code examples
javajavers

Javers retrieve the added object to a list


In javers, is it possible to retrieve the added object of a list (or any Container) ?

I don't want the GlobalId but the real object instance.

getAddedValues seem to return a GlobalId instead of the real object.

Note: I won't know in advance what object type I will be comparing. This is an example object.

MyTestObject obj1 = //Initialise it
MyTestObject obj2 = //Initialise it

Diff diff = javers.compare(obj1, obj2);

List<ContainerChange> containerChanges = diff.getChangesByType(ContainerChange.class);

for (ContainerChange containerChange : containerChanges) {
    for (Object addedValue : containerChange.getAddedValues()) {
        containerChange.getAffectedObject() //Returns the affected object
        addedValue //Returns an GlobalId but I want the real object added. (in this case the subObject added) Like the getAffectedObject() but with the other object.
    }
}

@TypeName("MyTestObject")
private static class MyTestObject {
    @Id
    private int id;
    private String value;
    private List<SubObject> subObjects;

    private MyTestObject() {

    }

    private MyTestObject(int id, String value, List<SubObject> subObjects) {
        this.id = id;
        this.value = value;
        this.subObjects = subObjects;
    }
}

@TypeName("SubObject")
private static class SubObject {
    @Id
    private int id;
    private String value;

    private SubObject() {

    }

    private SubObject(int id, String value) {
        this.id = id;
        this.value = value;
    }
}

Solution

  • I found a solution with some other changeType. I was able to build a map with the getChangesByType of NewObject and ObjectRemoved. The object is present in the affected object in those changes.

    Something like this:

         map = Stream.of(NewObject.class, ObjectRemoved.class)
                    .flatMap(type -> diff.getChangesByType(type).stream())
                    .collect(
                            Collectors.toMap(change -> change.getAffectedGlobalId().toString(), 
                                             change -> change.getAffectedObject().get()));
    

    And retrieve the object with the addedValue

    addedAndRemovedObjects.get(containerChange.getAddedValues().get(1).toString());
    

    Note 1 : I would probably change the toString key for something else but it was working for my test example. There was GlobalId and IdentityId that was not equals but the toString was.

    Note 2: getAddedValues().get(1) is only for the example.