In database design, some entities have a one-to-one relationship (e.g., Order has one Shipment, Person has one Address). EJB entity beans need to navigate and persist these relationships, but Java objects use references while databases use foreign keys.
A one-to-one relationship means each entity instance is related to at most one instance of another entity. In EJB, this is implemented via CMR (Container-Managed Relationships) in CMP, or via foreign key lookups in BMP using JNDI and Home interfaces.
Ordertable has columns:[OrderPK, OrderName, ShipmentPK (FK)]Shipmenttable has columns:[ShipmentPK, City, ZipCode]- Foreign key in Order table points to Shipment primary key
ejbLoad(): After loading order data (including FK), do JNDI lookup ofShipmentHome, callfindByPrimaryKey(shipmentFK)→ get Shipment stubejbStore(): Callshipment.getPrimaryKey()to get FK, then SQL UPDATE with FK value- Store stub in bean field:
private Shipment shipment;
- Define abstract getter/setter:
public abstract Shipment getShipment(); - Container manages relationship via
<cmr-field>inejb-jar.xml ejbLoad()andejbStore()are empty — container handles everything
- Each Order has at most one Shipment (1:1 cardinality)
- In BMP: foreign key ↔ object stub conversion in ejbLoad/ejbStore
- In CMP: container manages the relationship automatically via CMR
- Database schema can have FK in either direction (Order→Shipment or Shipment→Order)
getPrimaryKey()is critical in BMP to convert stub back to FK for SQL
- Built from: Entity Bean — relationships exist between entity beans
- Built from: CMP — uses CMR fields for relationships
- Built from: BMP — manual JNDI lookup for relationships
- Related: One-to-Many Relationship — next cardinality level
- Related: Bidirectional vs Unidirectional — directionality applies to 1:1
- Related: getPrimaryKey() — used in BMP to get FK from stub
- Persisting a stub directly would create a bit-blob in the FK column (BMP)
- BMP requires JNDI lookup + findByPrimaryKey in ejbLoad (extra code/overhead)
- CMP relationships are defined in deployment descriptor, not Java code
- Wrong directionality (unidirectional when you need bidirectional) limits navigation