如何在Entity类哈希代码中使用String?

时间:2013-04-01 21:02:12

标签: java sql persistence entity hashcode

我正在创建一个查询SQL数据库的Web应用程序。我的印象是我需要使用实体类和外观类来允许持久性 - 贯穿整个网站。实体类模板有哈希码和1.)我不确定我是否需要它们和2.)如果我这样做,他们想要int,但我所有的都是String所以,如何将它们转换为int然后再返回串?因为我需要String值出现在网站上,而哈希需要int。

继承人代码(已删除导入以保护无辜者......):

@Embeddable
public class ComputerOwnersPK implements Serializable {
    @Basic(optional=false)
    @NotNull
    @Column(name="Computer_Name")
    private int computerNameId;
    @Basic(optional=false)
    @NotNull
    @Column(name="User_ID")
    private int userId;

    public ComputerOwnersPK() {
    }

    public ComputerOwnersPK(int computerNameId,int userId) {
        this.computerNameId=computerNameId;
        this.userId=userId;
    }

    public int getComputerNameId() {
        return computerNameId;
    }

    public void setComputerNameId(int computerNameId) {
        this.computerNameId=computerNameId;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId=userId;
    }

    @Override
    public int hashCode() {
        int hash=0;
        hash+=(int) computerNameId;
        hash+=(int) userId;
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if(!(object instanceof ComputerOwnersPK)) {
            return false;
        }
        ComputerOwnersPK other=(ComputerOwnersPK) object;
        if(this.computerNameId!=other.userId) {
            return false;
        }
        if(this.userId!=other.userId) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "entity.ComputerOwnersPK[ computerNameId="+computerNameId+", userId="+userId+" ]";
    }
}

1 个答案:

答案 0 :(得分:0)

根据你的评论,我假设你希望你的mapNameId和userId成为你的映射中的字符串,你将它们映射到整数,因为你不知道如何处理哈希码。

在hashCode方法中,您应该能够连接字符串,然后在它们上调用哈希码。与你正在做的非常相似。

private String computerNameId;
private String userId;

@Override
public int hashCode() {
    // concatenate the interesting string fields 
    // and take the hashcode of the resulting String
    return (computerNameId + userId).hashCode();
}

确保在您的equals方法中,您还要从!=运算符更改为!.equals方法调用以检查相等性。最后确保你保留contract between equals and hashCode或者你可能会遇到一些令人讨厌的惊喜。两个相等的对象也必须具有相同的hashCode。具有相同hashCode的两个对象可能相同也可能不相同。