A database table may have a simple primary key (single column like productID) or a composite primary key (multiple columns like ID + RegionCode). If a primary key changes from simple to composite, entity bean code that assumed a single String key would break. There needs to be a flexible way to represent primary keys in EJB.
A Primary Key Class is a custom Java class that wraps one or more primary key fields. It is used as the return type of ejbCreate() and the parameter type for findByPrimaryKey(). Using a wrapper class makes the bean future-proof against schema changes.
- Option 1 (Direct Field): Use a simple type like
Stringorintas the primary key, declared inejb-jar.xmlvia<primkey-field>productID</primkey-field> - Option 2 (Wrapper Class): Create a class like
ProductPK.javathat holds the key fields as instance variables - The wrapper class must implement
Serializableand overrideequals()andhashCode()(so the container can compare keys) - If the database schema changes to a composite key, you just add fields to the wrapper class — bean code doesn’t break
- The container uses the primary key to identify entity bean instances in the pool
- Must be Serializable for EJB container to pass keys between JVMs
- Must override
equals()andhashCode()for proper key comparison - Wrapper class protects against database schema changes (composite key evolution)
- Used by
ejbCreate(),ejbPostCreate(), and all finder methods - Can be shared across beans that have the same key structure
- Built from: Entity Bean — Primary key classes are used exclusively with entity beans
- Builds into: ejbCreate() — create method returns the primary key type
- Builds into: Finder Methods — findByPrimaryKey uses the PK class
- Related: getPrimaryKey() — runtime method to retrieve the current bean’s primary key
- Contrasts with: Direct Field Primary Key — simpler but less flexible approach
- Forgetting to override
equals()andhashCode()causes container to fail at finding beans by primary key - Wrapper class must have a no-arg constructor (container instantiates it via reflection)
- Changing from simple to composite key requires updating
ejbPostCreate()and home interface method signatures - The PK class must be available in the EJB jar’s classpath