java - 如何保持一对一关系的一致性

标签 java relationship consistency

考虑 Lecturer.java 中的以下代码。 Lecture.java 中的 setter 具有完全相同的形式。另请注意,感兴趣的属性是 private

public void setLecture(Lecture lecture) {
    if (this.lecture == lecture) return;

    if (this.lecture != null) {
        this.lecture.setLecturer(null);
    }

    this.lecture = lecture;

    if (this.lecture != null) {
        this.lecture.setLecturer(this);
    }
}

当尝试设置以前不是 nullnull 值时,这会导致无限循环。

我不敢相信保持 1:1 关系的一致性如此困难 - 但我就是不知道如何做到这一点。如何解决这个问题?

最佳答案

最后,这是您的解决方案:

public class A {
    private B b;

    public void setB(B b) {
        if(this.b != null) {
            this.b.unsetA();
        }
        this.b = b;
        if(b != null && b.getA() != this) {
            this.b.setA(this);
        }
    }

    public void unsetB() {
        this.b = null;
    }

    public B getB() {
        return b;
    }

}

public class B {
    private A a;

    public void setA(A a) {
        if(this.a != null) {
            this.a.unsetB();
        }
        this.a = a;
        if(a != null && a.getB() != this) {
            this.a.setB(this);
        }
    }

    public void unsetA() {
        this.a = null;
    }

    public A getA() {
        return a;
    }

}

我的测试类:

public class Test {

    public static void main(String ... args) {
        A a1 = new A();
        B b1 = new B();
        A a2 = new A();
        B b2 = new B();

        checkForZeroOrTwoRelations(a1, a2, b1, b2);
        a1.setB(b1);
        checkForZeroOrTwoRelations(a1, a2, b1, b2);     
        b1.setA(a2);
        checkForZeroOrTwoRelations(a1, a2, b1, b2);
        b2.setA(a2);
        checkForZeroOrTwoRelations(a1, a2, b1, b2);
        b2.setA(null);
        checkForZeroOrTwoRelations(a1, a2, b1, b2);
    }

    private static void checkForZeroOrTwoRelations(A a1, A a2, B b1, B b2) {
        int i = 0;
        if(a1.getB() != null) i++;
        if(a2.getB() != null) i++;
        if(b1.getA() != null) i++;
        if(b2.getA() != null) i++;
        if(i != 0 && i != 2) {
            throw new IllegalStateException();
        }
    }
}   

关于java - 如何保持一对一关系的一致性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27093660/

相关文章:

python - 与 GAE 数据库进行强一致性查询以进行注册验证

java - 如何从 json 数组获取 Json 对象并将其与模型类一起使用

java - 从麦克风或扬声器绘制图形波形

java - TFS 和 TestiNG - 可以在 TFS 2015 中执行 TestNG 测试吗?

java - Selenium java 。无法定位元素

Azure Data Lake Store 的一致性

php - 删除商店标签之前的所有标签

php - Laravel - Eloquent self 关系

php - 在 yii 中按关系 STAT 排序

.net - HttpClient - .net 4 或 .net 4.5