【问题标题】:Openpojo throws BusinessException when a POJO references another POJO当 POJO 引用另一个 POJO 时,Openpojo 抛出 BusinessException
【发布时间】:2013-07-29 14:11:53
【问题描述】:

我正在使用 OpenPojo 对我的 JPA 实体进行自动化测试。我在处理引用其他实体的实体时遇到问题。

例子:

public class Person {
    @BusinessKey
    private Integer id;

    ...getters/setters

    @Override
    public boolean equals(Object obj) {
            return BusinessIdentity.areEqual(this, obj);
    }

    @Override
    public int hashCode() {
            return BusinessIdentity.getHashCode(this);
    }
} 


public class Employee {
    @BusinessKey
    private Integer id;

    private Person person;

    ...getters/setters

    @Override
    public boolean equals(Object obj) {
            return BusinessIdentity.areEqual(this, obj);
    }

    @Override
    public int hashCode() {
            return BusinessIdentity.getHashCode(this);
    }
}

这是我的测试用例:

    // Create Rules to validate structure for POJO_PACKAGE
    pojoValidator.addRule(new NoPublicFieldsRule());
    pojoValidator.addRule(new NoPrimitivesRule());
    pojoValidator.addRule(new NoStaticExceptFinalRule());
    pojoValidator.addRule(new GetterMustExistRule());
    pojoValidator.addRule(new SetterMustExistRule());
    pojoValidator.addRule(new NoNestedClassRule());

    // Create Testers to validate behaviour for POJO_PACKAGE
    pojoValidator.addTester(new DefaultValuesNullTester());
    pojoValidator.addTester(new SetterTester());
    pojoValidator.addTester(new GetterTester());

    for (PojoClass pojoClass : pojoClasses) {
        pojoValidator.runValidation(pojoClass);
    }

我收到以下异常:

com.openpojo.business.exception.BusinessException: Field required and can't be null [PojoFieldImpl

如果我从 Employee 类中删除对 Person 的引用,则测试不会引发任何异常。

【问题讨论】:

    标签: unit-testing jpa


    【解决方案1】:

    除非您使用注释“@BusinessKey”,否则OpenPojo 不会抛出此异常,您正在列出@BusinessIdentity。此外,您没有显示您的 equals 和 hashCode 或 toString 实现,“BusinessIdentity”在哪里被引用?

    另外需要注意的是,@BusinessKey 应该用于注释实际业务字段,而不是您的数据库代理 ID(又名主键)。

    【讨论】:

    • Osman,@BusinessIdentity 是一个错字,我已经修正了我的问题。我还包括了 equals 和 hashCode 方法。
    • 如果你注释你的代理键(即主键),并将 POJO 交给你的框架来持久化,框架将尝试去重复条目,它会通过调用 hashCode()和 equals(),这些调用将强制 BusinessIdentity 尝试了解如何进行相等 - 这在空对象上是不可能的。最好在数据库中注释不能为空的内容,例如人的名字/姓氏,或其他定义唯一性的内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    • 1970-01-01
    • 2017-01-07
    • 2020-02-24
    • 2021-07-19
    相关资源
    最近更新 更多