liveBook · Manning

Business key

As explained in Java Persistence with Spring Data and Hibernate epub

A business key is a property or combination of properties that uniquely identifies a domain instance according to meaningful business data.

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

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Explains selection, uniqueness, stability, and equals/hashCode consequences, with a User implementation; it does not enumerate composite-key code.
Examples
Uses User.username, a USERS UNIQUE constraint, and equality checks across entity-manager sessions and HashSet membership.
What it assumes
Assumes Java entity, equals(), hashCode(), Hibernate persistence, and database uniqueness concepts.
What you can do after
Implement entity equals() and hashCode() from a stable business key and enforce its uniqueness in the schema.
How it connects
Connects business keys to surrogate primary keys, natural keys, entity equality, Hibernate persistence, database constraints, and Set collections.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Java Persistence with Spring Data and Hibernate epub. The section links point to the parts of the book it draws on.