简体   繁体   English

实体的@Override Equals方法处的对象为null

[英]Object null at Entity's @Override Equals Method

I'm currently developing one of my company's project. 我目前正在开发公司的项目之一。 I use JSF and PrimeFaces. 我使用JSF和PrimeFaces。 According to the project requirements, I use PrimeFaces SelectOneMenu to show the employee list like the following... 根据项目要求,我使用PrimeFaces SelectOneMenu来显示员工列表,如下所示...

<p:selectOneMenu id="employee" value="#{employeeBean.employee}"
converter="employeeConverter">
    <f:selectItem itemLabel="" itemValue="" />
    <f:selectItems value="#{employeeBean.employeeList}" var="emp"
    itemLabel="#{emp.name}" itemValue="#{emp}" />
</p>

Here is my Employee Object's Equals Method... 这是我的员工对象的等于方法...

@Override
public boolean equals(Object obj) {
    if (!(obj instanceOf Employee)) {
        return false;
    }
    Employee employee = (Employee) obj;
    return this.id.equals(employee.getId());
}

If I create the employee object Employee employee = new Employee(); 如果创建雇员对象Employee employee = new Employee(); at Employee Bean init Method @PostConstruct public void init(){} , the employee object represented by this becomes null. 在雇员豆初始化方法@PostConstruct public void init(){}由表示的雇员对象this变为零。 If I don't create the employee object, everything works fine. 如果我不创建员工对象,那么一切都会很好。 Why? 为什么? I have no idea. 我不知道。 Thank you so much for your help! 非常感谢你的帮助!

This line, 这条线

return this.id.equals(employee.getId());

is not null safe. 不是null安全的。 It will still throw NPE when id is null , which may be the case when you create the entity instance manually using new operator without setting any of its properties instead of obtaining an instance from the DB by JPA means. idnull ,它仍将抛出NPE,这可能是您使用new运算符手动创建实体实例而不设置其任何属性,而不是通过JPA方式从数据库获取实例的情况。 Fix it accordingly: 相应地修复它:

return id != null ? id.equals(employee.id) : employee == this;

Note that I also improved the reflexivity of the comparison by adding employee == this . 请注意,我还通过添加employee == this提高比较的反射性。 See further also the first point of the contract of equals() . 另请参见equals()合约的第一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM