简体   繁体   English

如何有效地比较同一类的两个对象并检查哪些是不同的字段?

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

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. 我想编写一个泛型函数,它接受同一实体类的两个对象,并比较不同的字段,并返回对特定字段所做的所有更改的List以及时间。

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). 在DB中,我有一个名为member_audit的表,只要使用触发器在成员表中发生更改,就会使用旧数据填充该表(与其他实体类似)。

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. 然后调用上面的函数来比较entity_audit表中的每对记录。 The code would be very large to compare every field and multiplied by different entities. 代码将非常大,以比较每个字段并乘以不同的实体。 Is there a better and efficient way? 有更好更有效的方法吗?

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 : 因此,有效的方法不是重新发明轮子,而是使用现有的库,如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' }

Convert both object to a Map using JSON objectMapper.convertValue method. 使用JSON objectMapper.convertValue方法将两个对象转换为Map Then you can easily compare the keys/values of the two maps and create a list of differences. 然后,您可以轻松地比较两个地图的键/值并创建差异列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM