An entity bean is intended to represent the business logic for an entity existing in persistent storage, such as a relational database. Entity beans share some of the same qualities that you would find in a relational database, for example:
- Entity beans are persistentAn entity bean's state exists beyond the lifetime of the application in which it is created, or for that matter, beyond the lifetime of the EJB container. This implies that the entity bean can be restored to its original state by the EJB container.
- Entity beans allow shared accessBeans may be shared by multiple clients and the concurrency is handled by the container.
- Entity beans have primary keysPrimary-key classes exist to identify an instance of an entity bean. The primary key contains all the information needed to find a persistent entity.
- Entity beans may participate in relationshipsLocal interfaces have been introduced to manage relationships between beans.
- Entity beans can participate in transactionsBecause data can be accessed and changed by multiple clients, it is important for entity beans to be able to specify the transactional properties for their interaction. Transaction properties are specified declaratively in deployment descriptors, and transaction boundaries are handled by the container.
The object-relational mapping implied by entity beans requires that an entity bean be responsible for inserting, updating, selecting, and removing data within the data source. This process of managing the communication between the component and the data source is called persistence. In other words, persistence is this process of writing the information to an external data source. There are two types of persistence for entity beans: bean-managed persistence (BMP) and container-managed persistence (CMP).
Bean-Managed Persistence (BMP)
|Figure 1. Session Bean and Entity Bean Relationships: The figure shows how an EJB container acts as a proxy between the EJB client and the action EJB instance. This gives the container freedom to make invocations on EJB instances and to control the lifecycle of each EJB instance.|
With bean-managed persistence (BMP), a programmer is responsible for writing all of the code within the entity bean to access the data source. BMP typically gives the programmer more flexibility because all access to the data source is controlled by the programmer.
Container-Managed Persistence (CMP)
With container-managed persistence the EJB container handles all database access required by the entity bean. As a result, the bean's data-access code is not programmatically coupled to a specific data source. This frees the programmer from writing the data-access code and allows the entity bean to be deployed in different containers and/or against different data sources.
Figure 1 illustrates the relationships that exist between a client, an EJB container, session beans, and entity beans.