[英]Spring JPA @IdClass for CompositeKey minimum requirements
Hi I want to use @IdClass annatotation for compositeKey but I am little bit confused嗨,我想对 compositeKey 使用 @IdClass 注释,但我有点困惑
For CompositeKey class,some articles says that you have to override equals and hash method is it must or not?对于 CompositeKey class,有些文章说你必须覆盖 equals 和 hash 方法是否必须? My Second question should I put getter and setters to myfields in compositekey class or I already put getter and setters in my main entity which is used MyCompositeKey as @IdClass.
我的第二个问题是我应该将 getter 和 setter 放入 compositekey class 中的 myfields 中,还是我已经将 getter 和 setter 放入我的主要实体中,该实体将 MyCompositeKey 用作 @IdClass。 Can someone share examples of minimum requirements of @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(******);
}
Usually Hibernate requires to implement hashCode()
and equals()
for primary keys.通常 Hibernate 需要为主键实现
hashCode()
和equals()
。 (I don't know for other JPA implementations). (我不知道其他 JPA 实现)。
The documentation [1] claims that文档 [1] 声称
You have to override the
equals()
andhashCode()
methods if you你必须覆盖
equals()
和hashCode()
方法,如果你
- intend to put instances of persistent classes in a Set (the recommended way to represent many-valued associations) and
打算将持久类的实例放在一个集合中(推荐的表示多值关联的方法)和
- intend to use reattachment of detached instances
打算使用分离实例的重新连接
So, IMHO, it's always a good idea to implement them, as you don't know how you will use your entities in the future.因此,恕我直言,实施它们始终是一个好主意,因为您不知道将来将如何使用您的实体。
For the second question, according to [2] you have to implement getters but not setters.对于第二个问题,根据 [2] 你必须实现 getter 而不是 setter。 But, IMHO, why not?
但是,恕我直言,为什么不呢? If you use an IDE such as Eclipse, it's easy to create both of them at the same time.
如果您使用 IDE,例如 Eclipse,则很容易同时创建它们。
[1] https://access.redhat.com/documentation/en-us/jboss_enterprise_application_platform/4.3/html/hibernate_reference_guide/persistent_classes-implementing_equals_and_hashcode [1] https://access.redhat.com/documentation/en-us/jboss_enterprise_application_platform/4.3/html/hibernate_reference_guide/persistent_classes-implementing_equals_and_hashcode
[2] http://www.thejavageek.com/2014/05/01/jpa-idclass-example/ [2] http://www.thejavageek.com/2014/05/01/jpa-idclass-example/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.