Search code examples
javajavers

Is it possible to deserialise a Javers Diff?


I am trying to implement a simple diff system for an existing legacy system. I am calculating diffs between multiple potential object states using Javers, and persisting them in a serialised version. I do not want to commit the change on my object, just keep track of my diffs.

Is there any way I can recreate the Diff-object given the previously serialised Diff?

Here is my use case:

I have a base Entity that I do not want to change. The system receives new versions of the same entity, and I want to know how they differ from my base entity. I find the difference using Javers Diff and can display them, and obviously persist them by serialising the diff, but not restore them from the DB via the serialised diff.

I guess one way to achieve the same would be to persist the entire changed alternative entities, and then calculate the Diff at run-time, but it seems unnecessary to persist whole new Entities when there are only a few fields that have changed. Persisting the alternative versions of my Entity will also mess with my existing system due to unique keys.


Solution

  • I found the correct way to do this. I had been using Jackson ObjectMapper for serialization/deserialization which was giving me problems.

    To properly serialize and deserialize I had to use Javers' internal JsonConverter:

    Diff diff = javers.compare(myObject1, myObject2)
    
    //Tears and pain :(
    String omDiff = objectMapper.writeValueAsString(diff)
    Diff fromOm = objectMapper.readValue(omDiff, Diff.class)
    
    //yay :)
    String jcDiff = jsonConverter.toJson(diff)
    Diff fromJc = jsonConverter.fromJson(jcDiff, Diff.class)