Domanda

I like to use a BaseDomain class for all my JPA domain entities. In the base class, I have an object ID, stored as a String, generated from UUID.random(). The object ID is assigned at object creation. The entity class also has a primary key, assigned by the database when persisted.

Up until this point, I've always persisted the String based object ID. This adds an additional column to each table, but that doesn't bother me.

I was wondering - Is there any reason to persist the object id (the generated UUID)? Or should the random UUID stay in the Java space?

I always base my domain class hashCode() and equals() methods on the UUID, not the primary key. This is fine because the UUID stays the same for a given entity for its entire life, both in the JVM and in the database.

If I stopped persisting the UUID, what would the hashCode() and equals() methods look like? Would it be like a two tier comparison, first using the primary key if it's not null, then using the object id, if the primary key is null?

È stato utile?

Soluzione

The proper implementation of equals and hashCode is indeeed quite an issue for entities.

You do not have to persist an extra business key value if you have a 'natural' primary key, like a social security number for a person. It can be a single value or a combination of values - like a combination of name, surname, birthdate and address. If you have such a natural PK, please use it. If you do not have it, using UUID is a fine way to create one.

If you are using UUID for equals and hashCode, you should also persist it, so two instances of the same record are considered to be equal.

Your equals and hashCode should be based on this business key and not on the DB-provided id. If using the DB-provided id, all new entities are considered equal. This can lead to unexpected behaviour, especially when working with Collections.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top