A business key is a property, or combination of properties, that uniquely identifies a domain instance according to meaningful business data. Users recognize it as the record’s identity, while the application and database may rely on a surrogate primary key. section 10.3.2
Use a business key when implementing entity equality:
- Choose required, unique, rarely changing properties; username is a candidate for User. section 10.3.2
- Implement equals() and hashCode() from the same business-key properties, rather than relying on database identifiers assigned later by Hibernate. section 10.3.2
- Constrain the business-key property or properties as UNIQUE in the database schema. section 10.3.2
- Prefer keys that change rarely; absolute immutability is not required, but changing hash values can disrupt Set membership. section 10.3.2
Listing 10.3 Custom implementation of User equality
@Entity
@Table(name = "USERS",
uniqueConstraints =
@UniqueConstraint(columnNames = "USERNAME"))
public class User {
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null) return false;
if (!(other instanceof User)) return false;
User that = (User) other;
return this.getUsername().equals(that.getUsername());
}
@Override
public int hashCode() {
return getUsername().hashCode();
}
// . . .
}
Concrete User equality implementation using username and a matching database uniqueness constraint. section 10.3.2
