Using UUID as business key and equals/hashmethod

2019-05-04 19:50发布

问题:

I am working on a new application and I need some help on how to implement the equals method and the hashCode method. I have been reading many questions already asked here on SO, and I have also read several blog posts that has lead me to this question.

A little technical information first: I am using JPA (EclipseLink) and the application is for Java EE.

After what I have read you should use immutable values for hashCode and equals, but since the fields in the class is usually modifiable you can't use them. Nor can you use the primary key (JPA) because you won't have one before you have persisted it. So what I am thinking about is to use UUID. Both for equals and hashCode, but I have never done that before so I wonder if somebody thinks this is bad (why?) and possible downsides (apart from the tiny tiny tiny chance of getting the same ID)? Using a UUID and asign it in the constructor will give all objects a business ID from the very start. And I will make it immutable and save it to the database.

Is this approach bad?

回答1:

IMO the UUID will work just fine and i would recommend doing so.

I can't find any drawbacks to this approach since the possibility of hitting 2 same values is infinitely small.



标签: java uuid