0

SQL データベースにクエリを実行する Web アプリを作成しています。私は、エンティティ クラスとファサード クラスを使用して、サイト全体で永続性を確保する必要があるという印象を受けています。エンティティクラステンプレートにはハッシュコードがあり、1.) 必要かどうかわかりません.2.) 必要な場合は int が必要ですが、私が持っているのは文字列だけなので、それらを 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+" ]";
    }
}
4

1 に答える 1

0

あなたのコメントに基づいて、マッピングで computerNameId と userId を文字列にしたいと思います。ハッシュコードの操作方法がわからないため、それらを int にマップします。

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 の間のコントラクトを維持していることを確認してください。等しい 2 つのオブジェクトは、hashCode も同じでなければなりません。同じ hashCode を持つ 2 つのオブジェクトは、等しい場合と等しくない場合があります。

于 2013-04-01T21:15:13.847 に答える