更新对比修改前后数据

需求:页面进行跟新时,对更新的数据和原有数据进行对比,将修改的字段添加到操作记录

这里我不想使用aop的日志记录,这个功能其他修改也不会用,所有我就单独写了个循环

//你的实体对象
public class Test{
    @ApiModelProperty(value = "姓名")
	private String name;
    
    @ApiModelProperty(value = "年龄")
	private Integer age;
}

这里我直接写方法

	public static void main(String[] args) {
        //创建两个对象,这个就是你要对比的,一个是你原有对象的数据,一个是你更新的数据
		Test test1 = new Test();
		test1.setName("name");
		test1.setAge(18);
		Test test2 = new Test();
		test2.setName("test");
		test2.setAge(20);
        //将对象变成数组,这里的实体对象一定要用同一个否则就会报错,使用更新的或者原对象那个都可以
		Field[] fields = test1.getClass().getDeclaredFields();
		for (Field field : fields) {
            //这里假设对象的属性是私有的,因此使用了 field.setAccessible(true) 来设置访问权限。
			field.setAccessible(true);
			try {
				Object value1 = field.get(test1);
				Object value2 = field.get(test2);
                //对比数据,条件可以看业务需求增加或删除
				if (value1 != null && value2 != null && !"".equals(value2) && !value1.equals(value2)) {
					ApiModelProperty annotation = field.getAnnotation(ApiModelProperty.class);
					System.out.println("Difference in field " + field.getName() + ":");
					System.out.println("Value in obj1: " + value1);
					System.out.println("Value in obj2: " + value2);
					System.out.println("Swagger annotation value in obj: " + annotation.value());
				}
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
	}

运行结果

posted @ 2024-07-18 16:44  Dshzs月  阅读(3)  评论(0编辑  收藏  举报