简体   繁体   中英

Spring JPA @IdClass for CompositeKey minimum requirements

Hi I want to use @IdClass annatotation for compositeKey but I am little bit confused

For CompositeKey class,some articles says that you have to override equals and hash method is it must or not? 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. Can someone share examples of minimum requirements of @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. (I don't know for other JPA implementations).

The documentation [1] claims that

You have to override the equals() and hashCode() methods if you

  • 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. But, IMHO, why not? If you use an IDE such as Eclipse, it's easy to create both of them at the same time.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM