用于CompositeKey的Spring JPA @IdClass最低要求

问题描述 投票:0回答:1

嗨,我想对复合​​关键字使用@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(******);
}
java jpa mapping id
1个回答
0
投票

通常,Hibernate需要为主键实现hashCode()equals()。 (我不知道其他JPA实现)。

[文档[1]声称

如果需要,您必须重写equals()hashCode()方法>

  • 打算将持久性类的实例放入Set中(表示多值关联的推荐方法),并且
  • 打算使用分离实例的重新连接

因此,恕我直言,实现它们始终是一个好主意,因为您不知道将来如何使用您的实体。

对于第二个问题,根据[2],您必须实现getter而不是setter。但是,恕我直言,为什么不呢?如果使用诸如Eclipse之类的IDE,则可以轻松同时创建它们两者。

[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/

© www.soinside.com 2019 - 2024. All rights reserved.