2014-08-27 53 views
-1

您可以給我一個想法嗎?當它的實體添加到HashSet中時,equals()在POJO中無法正常工作?我檢查和hascode()正常工作,因爲具有相同字段的實體返回相同的哈希碼。但是相同的對象被添加到HashSet中。請看看下面的代碼:實體的equals()在HashSet中無法正常工作

@Entity 
@Table(name = "account") 
public class Account { 
    private int accountID; 
    private String accountNumber; 
    private float amount; 
    private String currency; 
    private Client clientID; 

    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    @Column(name = "account_id") 
    public int getAccountID() { 
     return accountID; 
    } 

    public void setAccountID(int accountID) { 
     this.accountID = accountID; 
    } 

    @Column(name = "account_number") 
    public String getAccountNumber() { 
     return accountNumber; 
    } 

    public void setAccountNumber(String accountNumber) { 
     this.accountNumber = accountNumber; 
    } 

    @Column(name = "amount") 
    public float getAmount() { 
     return amount; 
    } 

    public void setAmount(float amount) { 
     this.amount = amount; 
    } 


    @Column(name = "currency") 
    public String getCurrency() { 
     return currency; 
    } 

    public void setCurrency(String currency) { 
     this.currency = currency; 
    } 

    @ManyToOne(fetch = FetchType.LAZY) 
    @JoinColumn(name = "client_id") 
    public Client getClientID() { 
     return clientID; 
    } 

    public void setClientID(Client clientID) { 
     this.clientID = clientID; 
    } 

    @Override 
    public boolean equals(Object o) { 
     if (this == o) return true; 
     if (!(o instanceof Account)) return false; 

     Account account = (Account) o; 

     if (Float.compare(account.amount, amount) != 0) return false; 
     if (!accountNumber.equals(account.accountNumber)) return false; 
     if (!clientID.equals(account.clientID)) return false; 
     if (!currency.equals(account.currency)) return false; 

     return true; 
    } 

    @Override 
    public int hashCode() { 
     int result = accountNumber.hashCode(); 
     result = 31 * result + (amount != +0.0f ? Float.floatToIntBits(amount) : 0); 
     result = 31 * result + currency.hashCode(); 
     result = 31 * result + clientID.hashCode(); 
     return result; 
    } 
} 
+2

一個可能的問題是,在將其放入HashSet後,某個實體發生了更改 – talex 2014-08-27 10:45:54

+2

提供可重現問題的示例代碼。 – 2014-08-27 10:47:00

+2

'客戶'覆蓋'equals'和'hashcode'方法嗎? – pratZ 2014-08-27 10:47:53

回答

1
result = 31 * result + clientID.hashCode(); 

我覺得跟這行代碼的兩個對象的hashCode不是same.Try刪除這條線和測試

0

謝謝對於一些建議,但我意識到我的錯誤是什麼。我沒有說明該應用程序是用Hibernate將對象保存到數據庫的。在特定的Hibernate會話期間,對象被添加到HashSet中。當我將一個平等的對象添加到已經在數據庫中的對象時,它會在新的Hibernate會話中發生,並帶有新的空HashSet。

相關問題