【发布时间】:2017-10-05 10:51:27
【问题描述】:
如果我在 Jpa 实体 (MyEntity) 中有组合键,是否需要在 IdClass(本例中为 ID)中添加 equals() 和 hashCode()?它被视为重复?或者在 MyEntity “equals and hashCode()”中,我必须调用那些 ID 类 [return new MyEntity.ID(id1,id2).hashCode();在 MyEntity] 的 hashCode() 中?
@Entity
@IdClass(MyEntity.ID.class)
public class MyEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private long id1;
@Id
private long id2;
private String otherField;
public static class ID implements Serializable {
private static final long serialVersionUID = 1L;
private long id1;
private long id2;
public ID() {
super();
}
public ID(long id1, long id2) {
super();
this.id1 = id1;
this.id2 = id2;
}
public long getId1() {
return id1;
}
public void setId1(long id1) {
this.id1 = id1;
}
public long getId2() {
return id2;
}
public void setId2(long id2) {
this.id2 = id2;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (id1 ^ (id1 >>> 32));
result = prime * result + (int) (id2 ^ (id2 >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ID other = (ID) obj;
if (id1 != other.id1) {
return false;
}
if (id2 != other.id2) {
return false;
}
return true;
}
}
public MyEntity() {
super();
}
public long getId1() {
return id1;
}
public void setId1(long id1) {
this.id1 = id1;
}
public long getId2() {
return id2;
}
public void setId2(long id2) {
this.id2 = id2;
}
public String getOtherField() {
return otherField;
}
public void setOtherField(String otherField) {
this.otherField = otherField;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (id1 ^ (id1 >>> 32));
result = prime * result + (int) (id2 ^ (id2 >>> 32));
result = prime * result + ((otherField == null) ? 0 : otherField.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
MyEntity other = (MyEntity) obj;
if (id1 != other.id1) {
return false;
}
if (id2 != other.id2) {
return false;
}
if (otherField == null) {
if (other.otherField != null) {
return false;
}
} else if (!otherField.equals(other.otherField)) {
return false;
}
return true;
}
}
【问题讨论】:
-
我会在两个课程中都说