保存业务的修改记录(对象字段差异对比)

一 概述

我们在做一些修改业务时候,可能需要对修改记录留痕迹,包括修改人、修改时间、修改前后的值。今天抛砖引玉,告诉大家适用于这种场景如何处理。

二 原理

使用Java反射机制获取新旧对象的值,并获取字段的中文字段名称,组装成一个差异对象的集合。 

三 实践

需求:修改学生记录时并保存修改记录到数据库,并可以通过学生ID查询所有修改内容。

1. 自定义注解(字段比较)【在实体类字段上使用: 字段中文名称,字段字典映射】

package com.wtao;

import java.lang.annotation.*;

/**
 * @author wtao
 */
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface FieldCompare {

    /** 字段对应的中文 */
    String chineseName();

    /**
     * 类型映射
     * 使用方式 1:男,0:女
     */
    String properties() default "";

}

2. 创建字段差异实体类(修改的字段名称,修改前值,修改后值)

package com.wtao;

/**
 * ChangeLog 对比差异
 *
 * @auto wtao wangtao
 */
public class FieldDiffent {

    private String fieldName;
    private String before;
    private String after;

    public FieldDiffent() {
    }

    public FieldDiffent(String fieldName, String before, String after) {
        this.fieldName = fieldName;
        this.before = before;
        this.after = after;
    }

    public String getFieldName() {
        return fieldName;
    }

    public void setFieldName(String fieldName) {
        this.fieldName = fieldName;
    }

    public String getBefore() {
        return before;
    }

    public void setBefore(String before) {
        this.before = before;
    }

    public String getAfter() {
        return after;
    }

    public void setAfter(String after) {
        this.after = after;
    }

    @Override
    public String toString() {
        return "FieldDiffent{" +
                "fieldName='" + fieldName + '\'' +
                ", before='" + before + '\'' +
                ", after='" + after + '\'' +
                '}';
    }
}

3.(核心)字段对比工具类(反射比较对象字段差异, 封装成差异对象集合)

package com.wtao;

/**
 * SerializableFieldCompare TODO
 *
 * @author wangtao
 * @date 2022/9/29 11:36
 */

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 对比对象属性差异工具类
 */
public class FieldCompareUtil {

    public static <T> List<FieldDiffent> compare(Class<T> type, T newObject, T oldObject) throws Exception {
        // 变更的记录列表
        List<FieldDiffent> changeLogFields = new ArrayList<>();

        Class<?> newObj = newObject.getClass();
        Field[] newFields = type.getDeclaredFields();
        for (int i = 0; i < newFields.length; i++) {
            FieldCompare newAnnotation = newFields[i].getAnnotation(FieldCompare.class);
            if (null != newAnnotation) {
                PropertyDescriptor newPd = new PropertyDescriptor(newFields[i].getName(), newObj);
                Method getMethodNew = newPd.getReadMethod();
                Object oldVal = getMethodNew.invoke(oldObject);
                Object newVal = getMethodNew.invoke(newObject);
                boolean eq = false;
                if (oldVal instanceof String) {
                    String s1 = String.valueOf(oldVal).trim();
                    String s2 = String.valueOf(newVal).trim();
                    eq = !s1.equals(s2);
                } else if (oldVal instanceof Integer) {
                    int i1 = (Integer) oldVal;
                    int i2 = (Integer) newVal;
                    eq = i1 != i2;
                } else if (oldVal instanceof Double) {
                    double d1 = (Double) oldVal;
                    double d2 = (Double) newVal;
                    eq = d1 != d2;
                } else if (oldVal instanceof BigDecimal) {
                    BigDecimal b1 = (BigDecimal) oldVal;
                    BigDecimal b2 = (BigDecimal) newVal;
                    eq = b1.compareTo(b2) != 0;
                } else if (oldVal instanceof Long) {
                    long l1 = (Long) oldVal;
                    long l2 = (Long) newVal;
                    eq = l1 != l2;
                } else {
                    eq = !oldVal.equals(newVal);
                }
                String s1 = oldVal == null ? "" : oldVal.toString().trim();
                String s2 = newVal == null ? "" : newVal.toString().trim();
                if (eq) {
                    Map<String, String> map = codeToNameMap(newAnnotation);
                    if (map.size() > 0) {
                        changeLogFields.add(new FieldDiffent(newAnnotation.chineseName(), map.get(s1), map.get(s2)));
                    } else {
                        changeLogFields.add(new FieldDiffent(newAnnotation.chineseName(), s1, s2));
                    }
                }
            }
        }
        return changeLogFields;
    }

    /**
     * 字典映射 使用方式:
     * @param newAnnotation
     * @return
     */
    private static Map<String, String> codeToNameMap(FieldCompare newAnnotation) {
        Map<String, String> map = new HashMap<>();
        String properties = newAnnotation.properties();
        if (properties != null && properties.length() > 0) {
            String[] propertiesArr = properties.split(",");
            for (String propertie : propertiesArr) {
                String[] split = propertie.split(":");
                map.put(split[0], split[1]);
            }
        }
        return map;
    }
}

4. 学生实体类(业务)(在需要对比的字段上添加注解,不加注解不对比)

package com.wtao;

import java.util.Date;

/**
 * Student TODO
 *
 * @author wangtao
 * @date 2022/11/4 14:33
 */
public class Student {

    @FieldCompare(chineseName = "姓名")
    private String name;
    @FieldCompare(chineseName = "年龄")
    private Integer age;
    @FieldCompare(chineseName = "性别", properties = "1:男,0:女")
    private Integer sex;
    @FieldCompare(chineseName = "时间")
    private Date time;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    public Date getTime() {
        return time;
    }

    public void setTime(Date time) {
        this.time = time;
    }
}

5. 创建学生修改记录表(主要字段:主键ID,学生ID,修改差异Json数组,修改人,修改时间)大家自己创建,这里不做数据库操作

6. 测试

public class Test {

    public static void main(String[] args) throws Exception {
        Student student = new Student();
        student.setName("张三");
        student.setAge(18);
        student.setSex(1);
        student.setTime(new SimpleDateFormat("yyyy-MM-dd").parse("2022-10-11"));

        Student newStudent = new Student();
        newStudent.setName("李四");
        newStudent.setAge(33);
        newStudent.setSex(0);
        newStudent.setTime(new SimpleDateFormat("yyyy-MM-dd").parse("2022-10-11"));

        List<FieldDiffent> compare = FieldCompareUtil.compare(Student.class, student, newStudent);

        System.out.println(compare);

    }
}

输出是差异字段的列表(ps: 因为当时测试时新旧对象传反了,导致before和after反了)

[

ChangeLogField{fieldName='姓名', before='李四', after='张三'},

ChangeLogField{fieldName='年龄', before='33', after='18'},

ChangeLogField{fieldName='性别', before='女', after='男'}

]

数据库保存大致样子(数据表里answer_id相当于业务的id)diff字段差异保存本次修改的修改内容,根据业务ID查询出所有修改的记录,前端根据每次修改记录,解析diff 的json数组来做页面展示。

 页面可以渲染成这样

 整体效果如下

 (完~)

  • 8
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值