Entity beans represent persistent data in EJB. The key architectural decision is who handles the persistence: the container (CMP) or the bean itself (BMP).
| Feature | Container-Managed Persistence (CMP) | Bean-Managed Persistence (BMP) |
|---|---|---|
| Developer writes JDBC? | No | Yes |
| O/R Mapping | Defined at deployment time | Hand-coded |
| Portability | High (storage-independent) | Lower (DB-specific code) |
| Code Size | Smaller bean | More code to maintain |
| Control | Less control over SQL | Full control over SQL |
| Complexity | Simpler for developers | More error-prone |
- Developer writes entity bean with no persistence logic
- Using vendor tools, developer defines how fields map to database columns
- At deployment, container generates the SQL code
- Container handles all INSERT, UPDATE, DELETE, SELECT automatically
- Developer writes JDBC code in ejbCreate(), ejbRemove(), finder methods
- Developer handles all SQL statements manually
- Container calls the methods but doesn’t generate SQL
- More flexibility but more responsibility
- Simple persistence needs
- Portability across databases is important
- Want to minimize code
- Standard CRUD operations suffice
- Need complex SQL queries
- Require fine-grained control over database operations
- Using legacy or unusual data sources
- Specific database optimizations needed
CMP is the EJB “magic”—the container does the heavy lifting. BMP gives you the keys to the car. Choose based on your team’s expertise and the complexity of your data access needs.