You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何JAVERS.compare会抛出JaversException SNAPSHOT_STATE_VIOLATION异常?

解决Javers对比时出现SNAPSHOT_STATE_VIOLATION异常的问题

问题场景

定义类结构如下:

class Parent {
    Integer pozition;
}

class Child extends Parent{
    Integer pozition;
}

@AllArgsConstructor
class Container {
    HashSet<Child> children;
}

编写测试代码进行Javers对比:

private static final Javers JAVERS = JaversBuilder.javers().build();

public static void main(String[] args) {

    Child child1 = new Child();
    child1.pozition = 0;
    ((Parent) child1).pozition = 1;
    Child child2 = new Child();
    child2.pozition = 0;

    HashSet<Child> list1 = new HashSet<>();
    list1.add(child1);
    list1.add(child2);

    try {
        Diff diff = JAVERS.compare(new Container(list1), new Container(new HashSet<>()));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

运行后抛出异常:

JaversException SNAPSHOT_STATE_VIOLATION: attempt to update snapshot state, property 'pozition' already added

异常原因

Child类重定义了父类Parent中的pozition字段,Javers生成对象快照时会扫描类的所有继承层级字段,同名的pozition会被重复识别,导致快照构建时出现属性重复添加的冲突。

解决办法

方式一:移除子类重复字段

直接删除Child类中的pozition字段,复用父类的该字段,从根源避免同名属性冲突:

class Child extends Parent{
    // 删除子类的pozition字段
}

方式二:通过Javers注解忽略重复字段

如果业务上必须保留子类的pozition字段,可以用@DiffIgnore注解标记父类或子类的同名字段,让Javers只处理其中一个版本:

  • 忽略父类字段,只处理子类字段:
class Parent {
    @DiffIgnore
    Integer pozition;
}

class Child extends Parent{
    Integer pozition;
}
  • 忽略子类字段,只处理父类字段:
class Parent {
    Integer pozition;
}

class Child extends Parent{
    @DiffIgnore
    Integer pozition;
}

内容的提问来源于stack exchange,提问作者maybesomename

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 22:00:23