Search code examples
javajavers

Compare objects of child and parent classes in javers


I have two classes:

class A {
  @org.springframework.data.annotation.Id
  String id;      
  String field;
}
class B extends A {
  @DiffIgnore
  String someOtherField;
}

I want to compare instance of class A and instance of class B. Both instances have the same id.

Please tell if that is possible anyhow with Javers.

I've already did research on Internet, tried to use the same or different @TypeName, tried as @ValueObject and with @Entity - nothing helped.


Solution

  • You need to use @TypeName and give both classes the same name. And then JaVers compares objects but only properties declared in the super type.

    I wrote the test to show it (Groovy):

    class CaseWithInheritance extends Specification{
        @TypeName("A")
        class A {
            @Id
            String id
            String field
        }
        @TypeName("A")
        class B extends A {
            @DiffIgnore
            String someOtherField
        }
    
        def "should compare objects' intersection"(){
          given:
          def a = new A(id:1, field:"aa")
          def b = new B(id:1, field:"bb", someOtherField:"b")
          def javers = JaversBuilder.javers().build()
    
          when:
          def diff = javers.compare(a, b)
    
          then:
          diff.changes.size() == 1
          println diff.prettyPrint()
        }
    }
    

    Output:

    Diff:
    * changes on A/1 :
      - 'field' changed from 'aa' to 'bb'