0

I'm making a web app that queries an SQL db. I'm under the impression that I need to use entity classes and facade classes to allow persistence - across the whole site. The entity class templates have hashcodes and 1.) Im not sure if I need them and 2.) If I do, they want int's but all I have are String so, how to convert them to int and then back to String? Because I need the String value to appear on the site and the hash wants int's.

heres the code (imports have been remove to protect the innocent...):

@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+" ]";
    }
}
4

1 回答 1

0

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

在您的 hashCode 方法中,您应该能够连接字符串,然后在它们上调用 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方法调用以检查相等性。最后确保你遵守equals 和 hashCode 之间的约定,否则你可能会遇到一些令人讨厌的惊喜。两个相等的对象也必须具有相同的 hashCode。具有相同 hashCode 的两个对象可能相等也可能不相等。

于 2013-04-01T21:15:13.847 回答