Using UUID as a business key and equals / hashmethod

I am working on a new application, and I need help on how to implement the equals method and the hashCode method. I read a lot of questions already asked here on SO, and I also read some blog posts that led me to this question.

Some technical information: I use JPA (EclipseLink), and the application is for Java EE.

After what I read, you should use immutable values ​​for hashCode and equals, but since the fields in the class are usually mutable, you cannot use them. Also, you cannot use the primary key (JPA), because you will not have it until you save it. So what I'm thinking about is to use a UUID. Both for equals and hashCode, but I have never done this before, so I wonder if anyone thinks this is bad (why?) And possible flaws (except for the tiny tiny tiny probability of getting the same ID)? Using the UUID and assigning it in the constructor will give all objects a business identifier from the very beginning. And I will make it immutable and store it in the database.

Is this approach bad?

+4
source share
1 answer

IMO UUID will work fine and I would recommend doing this.

I can not find any drawbacks of this approach, since the possibility of hitting two identical values ​​is infinitely small.

+4
source

Source: https://habr.com/ru/post/1433361/


All Articles