I have a domain Class named Subscriber and its definition is something like this:
public class Subscriber {
private long id;
private String email;
private String subscriberName;
private Topic subscribingTopic;
//other attributes and getters setters.
}
public class Topic{
private long id;
private String topicName; //unique
}
My problem is I need to override the equal() and hashCode() methods of this Subscriber class.
Overriding equal() is somewhat easy task (just comparing basic attributes, in this case there are three of them). But I am facing problems while overriding hashCode() method. How I can write hashCode() that I can trust to be used by hibernate safely, while managing my domains. Can I trust IDE generated one?
Any help will be appreciated and thanks in advance!
You can use IDE like Eclipse to generate
hashCodemethod for you. One samplehashCodemethod is below:You need to create a similar
hashCodemethod inTopicclass as well.Per
Object#hashCodeAPI:Its general practice to use prime number 31 and combine the attribute values in a*31^(x)+b*31^(x-1)+..c to achieve the unique number for the object. In the process, you can use the
hashCodemethod of underline object. The above method also does the same.