How to efficiently compare two objects of same Class and check which are the fields that differ?

Mohammed Shirhaan :

I want to write a generic function that accepts two objects of same entity class and compares the fields that are different and returns List of all the changes made to particular fields along with time.

One among the many entity classes would be say Member as follows

public class Member {
    String firstName;
    String lastName;
    String driverLicenseNumber;
    Integer age;
    LocalDateTime timestamp;
}

In the DB, I have a table called member_audit that gets populated with old data whenever there is a change in member table using triggers (Similarly for other entities).

The List of resource for each of the entity I would be returning is something like

public class MemberAuditsResource {
    private String field;
    private LocalDateTime on;
    private String changeType;
    private String oldValue;
    private String newValue;
}

I can only think of writing a function for each entity separately like this

private List<MembeAuditsResource> memberCompare(Member obj1, Member obj2) {

    //Compare every field in both the objects using if else and populate the resource.

}

And then calling the above function to compare every pair of record in the entity_audit table. The code would be very large to compare every field and multiplied by different entities. Is there a better and efficient way?

Ken Chan :

If you extend the ideas to compare the object graph , it is not a trivial problem. So, the efficient way is not to re-inventing the wheel but use an existing library such as JaVers :

Member oldMember = new Member("foo" ,"chan" ,"AB12" , 21 ,LocalDateTime.now());
Member newMember = new Member("bar" ,"chan" ,"AB12" , 22 ,LocalDateTime.now());

Diff diff = javers.compare(oldMember, newMember);
for(Change change:  diff.getChanges()) {
    System.out.println(change);
}

Then , you can get something like:

ValueChange{ 'firstName' changed from 'foo' to 'bar' }
ValueChange{ 'age' changed from '21' to '22' }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=98029&siteId=1