Java 如何在实体类哈希代码中使用字符串?

Java 如何在实体类哈希代码中使用字符串?,java,sql,persistence,entity,hashcode,Java,Sql,Persistence,Entity,Hashcode,我正在制作一个查询SQL数据库的web应用程序。我的印象是,我需要使用实体类和门面类来实现整个站点的持久性。实体类模板有hashcode和1。)我不确定是否需要它们,2。)如果需要,它们需要int,但我只有String,那么如何将它们转换为int,然后再转换回String?因为我需要字符串值出现在站点上,而散列需要int 以下是代码(已删除进口以保护无辜者…): 根据您的评论,我假设您希望computerNameId和userId在映射中成为字符串,并且您将它们映射到int,因为您不知道如何执行

我正在制作一个查询SQL数据库的web应用程序。我的印象是,我需要使用实体类和门面类来实现整个站点的持久性。实体类模板有hashcode和1。)我不确定是否需要它们,2。)如果需要,它们需要int,但我只有String,那么如何将它们转换为int,然后再转换回String?因为我需要字符串值出现在站点上,而散列需要int

以下是代码(已删除进口以保护无辜者…):


根据您的评论,我假设您希望computerNameId和userId在映射中成为字符串,并且您将它们映射到int,因为您不知道如何执行hashcode

在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
用于检查相等性的方法调用。最后,确保你一直保持着良好的状态,否则你可能会遇到一些令人不快的惊喜。两个相等的对象也必须具有相同的哈希代码。具有相同哈希代码的两个对象可能相等,也可能不相等。

要将对象用作
hashCode()
的一部分,请使用它们自己的
hashCode()
,例如
hash+=str.hashCode()字符串
在哪里?我只是看到
int
对,它们是字符串,但在代码中-为了消除错误-它们是int的,但实际上它们是字符串…@miorel像这样???hash+=str.hashCode(computerNameId);好。。然而,第一部分似乎起作用,正在改变!=到equals不是…而且,我想知道我是否能够保留两个字符串的原始值?有没有另一种方法可以在没有实体类的情况下使用持久性!。equals
我的意思是类似于
if(!computeNameId.equals(other.computerNameId)
。您不必使用实体。您可以使用纯JDBC,在纯JDBC中发出纯SQL并自己处理结果集,手动将结果中的列映射到您想要的任何java属性/变量。
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();
}