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?