In databases, we need a way to uniquely identify each row/record. Without a unique identifier, we can’t reliably update, delete, or reference specific records. Multiple records might have identical data but represent different entities.
A primary key is a column (or set of columns) whose values uniquely identify each row in a database table. In EJB entity beans, the primary key is wrapped in a PrimaryKeyClass object that the container uses for identity management.
In relational databases:
- Uniqueness — no two rows can have the same primary key value
- Non-null — primary key cannot be NULL
- Immutable — once set, primary key shouldn’t change
In EJB Entity Beans:
- PrimaryKeyClass — wrapper class implementing Serializable and optionally hashCode/equals
- getPrimaryKey() — method to retrieve current entity’s primary key
- Finder methods — return primary keys to locate entities
- Container uses PK — for pooling, identity, and relationship management
- Unique identification — each entity instance has distinct primary key
- Serializable — PrimaryKeyClass must implement java.io.Serializable
- Simple or composite — single field or multiple fields combined
- Container-managed — EJB container tracks entities by primary key
- Built from: Entity Bean — entity beans use primary keys for identity
- Built from: Entity Bean Identity — PK defines entity identity
- Builds into: Finder Methods — return primary keys
- Builds into: getPrimaryKey() — method to retrieve PK
- Builds into: Primary Key Class — wrapper class for PK
- Related: JDBC — SQL uses primary keys for WHERE clauses
- Composite keys — need custom PrimaryKeyClass with proper equals() and hashCode()
- Auto-generated keys — database can generate (e.g., AUTO_INCREMENT), must sync to bean
- Changing PK — don’t change primary key after creation; it breaks identity