Developing a Container Managed Persistence (CMP) Entity Bean
(To download a zip containing the source files for this article, click here.)
Hopefully, by now you have either read my previous article (What's the Buzz Behind EJB?) or have in some way become convinced that developing distributed enterprise applications using Enterprise JavaBeans is the way to go. No matter what brought you here, this article is going to give you an introduction to developing your first Enterprise JavaBean!
Theory
Enterprise JavaBeans come in two flavors: entity beans and session beans. Entity beans represent data and session beans hold the business logic to manipulate that data. Traditionally, an entity bean provides an interface to data stored in a database, and usually in a single table (although future articles in this column will develop beans that span multiple tables). Both entity beans and session beans live in an EJB container, sometimes referred to as the middleware layer (see Figure 1). Applications request beans from the application server; the application server creates the beans, initializes them with the appropriate database records, and returns them to the application. You may recall from my previous article in this column that the application server that provides the EJB container offers transaction management, distribution, platform independence, scalability, and portability.
EJB container.
Entity beans come in two flavors, differentiated by the party responsible for persisting the data to and from the database:
-
Container managed persistence (CMP) entity beans delegate the responsibility for persisting data to the container that's managing the bean.
-
Bean managed persistence (BMP) entity beans delegate that responsibility to the bean itself, and hence to the programmer.
Like entity beans, session beans come in two flavors: stateless and stateful. A stateless session bean doesn't maintain any information from one method call to another and has no instance variables. Essentially, two instances of the same stateless session bean are equivalent; it wouldn't matter to the application whether subsequent method calls are made on the same bean or on different beans. A stateful session bean, on the other hand, maintains information between method calls and has instance variables.
These four types of beans, and the forthcoming EJB 2.0 specification beans, can be combined to build highly scalable and distributed enterprise applications. This series will follow this schedule for the next four articles:
1. CMP entity beans (this article)
2. Stateless session beans
3. BMP entity beans
4. Stateful session beans