嗨,我想对复合关键字使用@IdClass annatotation,但我有点困惑
对于CompositeKey类,有些文章说您必须重写equals和hash方法,是否必须这样做?我的第二个问题是我应该将getter和setters放置在Compositekey类的myfields中,还是已经将getter和setters放置在使用MyCompositeKey作为@IdClass的主实体中。有人可以分享@IdClass的最低要求的示例
public class MyCompositeKey implements Serializable {
public MyCompositeKey (){}
private String Name; //Is it necessary to add getter setter to fields
private String UserName; //Is it necessary to add getter setter to fields
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
....
}
@Override
public int hashCode()
return Objects.hash(******);
}
通常,Hibernate需要为主键实现hashCode()
和equals()
。 (我不知道其他JPA实现)。
[文档[1]声称
如果需要,您必须重写
equals()
和hashCode()
方法>
- 打算将持久性类的实例放入Set中(表示多值关联的推荐方法),并且
- 打算使用分离实例的重新连接
因此,恕我直言,实现它们始终是一个好主意,因为您不知道将来如何使用您的实体。
对于第二个问题,根据[2],您必须实现getter而不是setter。但是,恕我直言,为什么不呢?如果使用诸如Eclipse之类的IDE,则可以轻松同时创建它们两者。
[2] http://www.thejavageek.com/2014/05/01/jpa-idclass-example/