Creating an Entity Bean - JSP

Entity Beans represent business data.There are two kinds of entity Bean: those that operate container managed persistence, and those that operate Bean managed persistence.The difference is as follows:

  • Container Managed Persistence (CMP):The interaction with the database is managed by the container. No JDBC code is written by the developer.Transaction management is also managed by the container.
  • Bean Managed Persistence (BMP):The Bean manage its own database access. These Beans are more complex because they need to include all their own database access code. It is generally best to avoid these Beans unless you have to use them. For example, you would use them when the data store being used is not supported by the EJB container, or the data for the Bean comes from multiple data sources.

The focus in this book is on CMP entity Beans.We will begin by looking at an entity Bean for the compact disc products within the shopping-cart application. If you recall, the compact_discs table was created with the following SQL:

The entity Bean will require the home and remote interfaces and the implementation class.

The Entity Bean Remote Interface

First, you’ll see the remote interface class.The remote interface can be seen in Listing 15.2.

This remote interface contains the functional methods of the EJB that are to be available to clients. Notice the following about the remote interface:

  • It extends javax.ejb.EJBObject.
  • Every method throws a java.rmi.RemoteException.

The reason for the remote exceptions is that, if you recall, EJBs are accessed remotely over RMI/IIOP.The EJBObject interface is extended because this contains various methods that the auto-generated implementation class created by the container will have (see Figure to remind you of the class diagram).The methods defined will all get and set the various properties of the compact disc entries in the database when implemented.

The Entity Bean Home Interface

The home interface contains the methods for creating and finding the EJBs. Listing 15.3 contains the home interface for the compact disc EJB.


The home interface contains create methods and a number of what are referred to as finder methods, as well as remove methods:

  • Create methods—These are used by the container to create instances of the entity Bean.You can have more than one create method, or if you do not want to allow users to create data, you cannot have any create methods. A vital point to note here is this: Because entity Beans represent the data, when an entity Bean is created, a new row in the database is also created. Similarly, when an entity Bean is destroyed, the entry is removed from the database. The create methods all throw RemoteExceptions, and they also throw javax.ejb.CreateExceptions.The CreateException is thrown when an entity Bean cannot be created using the create() method selected.
  • Finder methods—If you consider the entity Beans as your data, you need to be able to search your data and locate specific entries. In Chapter 14, you saw how to do this using sql:query tags in your JSP pages.With EJB, you do not need to use these tags, as the finder methods return the data from the database as entity Beans. If you look again at Listing 15.3, you will see that the finder methods defined are as follows:

These methods are the equivalent of SQL queries on the database.We’ll see how they become SQL queries as we look at the deployment process.

  • Remove methods—Although we have not implemented any remove methods, they are used to remove entity Beans and, therefore, entries in the database.

In Listing 15.3, you can see that all the methods throw RemoteExceptions as you saw in the remote interface.What is different is the finder methods because these also throw javax.ejb.FinderExceptions.The FinderException is thrown when a find method fails.

The Entity Bean Implementation

You have seen both the home and the remote interface, so attention now turns to the implementation class for the entity Bean.There may be some things that surprise you in this Listing 15.4.


There are a number of things in this listing that require explanation. For example, the implementation class does not implement the home and remote interface within its class declaration! I am sure that when you first learned Java, from a book or a course, you were taught when you learned about interfaces that implementation classes needed to implement the appropriate interfaces.The clue to why you do not implement the interfaces in this class is in Figure . Notice that your implementation class is wrapped in a class of type EJBObject.This wrapper class is dynamically generated by the container, and it is this class that implements the remote interface. A container-generated EJBHome object then implements the home interface. Here is the class declaration for the EJBObject created by the ATG Dynamo Application Server. Remember, you never write this, and you would normally never see it:

The RemoteImpl class here is an ATG Dynamo implementation of EJBObject. Another thing that you might find surprising about Listing 15.4 is that there is nothing in here to actually access the database.This is because the container is going to interact with the database for us. If this entity Bean used BMP, you would see JDBC code in many of the methods. We will now unpack this implementation Bean somewhat and look at what is present and why. First, note the class declaration. It is an abstract class:

public abstract class CompactDiscBean implements EntityBean

This class will be extended by a container-generated class, which will implement the various abstract methods. If you look further down the listing, the abstract methods are the methods that were defined in your remote interface.Two of them are shown here:

There are no declared properties in the implementation class. Instead, the get/set methods are provided, but in an abstract form.This frees the container to manage and store the actual properties how it wants in the container-generated class that will extend your implementation. As well as the abstract get/set methods, there are methods used to create new instances.These are the create() methods, and they are next in Listing .They are shown here:

The ejbCreate() method is defined in the home interface.This method is called when an entity Bean of this type is created.This will set all the properties, and the container will then populate the database with the data for you.The return type is always the primary key. In a container-managed Bean such as this, you only need to return null, but in a BMP Bean, you would need to create a primary key object and return it because it will be needed later to persist the data.The ejbPostCreate() method is invoked imme- diately after the create() method. It is here because you do not have a reference to the newly created object until after ejbCreate() returns, and if you wanted to do something with it as soon as it was created, you would need to do it from within the ejbPostCreate() method.The ejbPostCreate() method has to be present, but it rarely contains anything. It always has the void return type and has the same arguments as ejbCreate(). Last, in Listing 15.4 is a raft of empty methods.This also shows the exceptions

Many of the methods declared in the entity Bean are sometimes referred to as the lifecycle methods, and they are there to manage the lifecycle of the entity Bean instances. These methods, and also the create methods you have seen are regarded as the lifecycle methods.The lifecycle of an entity Bean will be discussed next.

The Entity Bean Lifecycle

Entity Bean instances exist within a container in one of two possible states: a pooled state or a ready state. Pooled entity Beans are not tied to a specific item of data from the data store, but are available.The Beans become ready when they are associated with an EJBObject. If you recall, this is the type that is created by the container.The state of an entity Bean is shown in Figure .The benefits of using this pool are performance related.When data is extracted from the data source, an object from the pool can be used to hold it, rather than having to create, and then garbage collect one each time.

The state of an entity Bean.

The state of an entity Bean.

So what does this mean for the lifecycle of an entity Bean? The lifecycle methods from Listing 15.4 are used when the Beans go from one state to the other. Figure summarizes the entity Bean lifecycle, and shows when the different methods are invoked.

The lifecycle of an entity Bean.

The lifecycle of an entity Bean.

The flow chart in Figure shows how the various lifecycle methods are involved in the lifecycle of an entity Bean.To get a Bean from the pooled state to the ready state, for example, the passivate and activate methods are used.The roles of the other methods are listed in Table

The EJB Lifecycle Methods

The EJB Lifecycle Methods

In CMP entity Beans, these methods are frequently left empty, as the container is doing all the hard work of managing all this for us. In BMP, however, these methods can become quite important.

Passivation and Activation

To help the container manage its resources effectively, these Beans can be passivated, which basically means that they can be serialized to disk if the container wants to conserve resources.When required the Bean can be activated so that it can be used again. This means that it is deserialized back to an object again. If there are certain things that need to happen just before passivation or just after activation, these can go into the ejbPassivate()and ejbActivate() methods, respectively.

Deploying an Entity Bean

When the concept of J2EE application development was introduced, you were introduced to deployment descriptors. Particular attention was paid to the familiar web.xml for Web applications. For EJBs, there is an additional deployment descriptor, ejb-jar.xml.This deployment descriptor is part of the J2EE specification. The deployment descriptor describes to the container how the entity Bean is to be handled. When deploying however, there are some application server–dependent deployment descriptors as well. For our example, we’ll use WebLogic 7 from BEA.

  • BEA WebLogic is one of the most popular application servers in use on the market today.
  • WebLogic 7 has full support for EJB 2.0 which we need for this example.

There is no reason why you cannot deploy this application using an alternative application server; you will simply need to check the documentation for the vendor-specific aspects to deployment.

Listing below is the ejb-jar.xml deployment descriptor for the entity Bean used in the example for BEA WebLogic.This deployment descriptor would be the same, regardless of application server that supports J2EE 1.3 you choose to use. Note that in the sample application there is additional content in this file because it also contains references to the other EJBs discussed later in the chapter.The file ejb-jarEntityOnly.xml contains exactly what is shown in Listing below.

Listing ejb-jar.xml

Although it might appear a little daunting when you see the size of it, it is not as complex as you might think. Figure below shows a visual view of the XML, as shown by XML Spy 4.3.The diagram helps to show the structure of the document, and you might want to refer to this diagram as the roles of the various parts of the deployment descriptor are explained.

Structure of ejb-jar.xml as shown in XML Spy 4.3.

Structure of ejb-jar.xml as shown in XML Spy 4.3.

The deployment descriptor shown is in two discrete sections. One contains the EJBs themselves (enterprise-beans), and the other describes how transactions within the Beans are supposed to be handled (application-descriptor).We will look at the Bean definition first.

Describing the Entity Bean in the Deployment Descriptor

The Bean is defined using the <entity> element, and there will be one for each entity Bean that is deployed.The implementation class, and the two interfaces are described, and then the <persistence-type>.This is a CMP entity Bean so the value of this element is Container: For the <persistence-type>, the alternative value is Bean for BMP entity Beans. No other value is valid.The primary key class is also defined using the <prim-key-class> element.

The reentrant should always be false, and the version is set to 2.x in our case. Lastly, we set what is called the abstract schema name. In EJB 2.0, relationships between entity Beans can be defined within the deployment descriptor, and this is the name of the schema. Our example does not require relationships because none are required for our application; however, the schema name will be used when we define the finder methods.The container-managed fields are then defined using elements of the following construct:


The mapping of these field names to the data source is then completed using an additional deployment descriptor that is application server vendor specific.We’ll see this later. We’ll now turn our attention to the finder methods. If you recall, so far, the finder methods have had nothing but a method signature defined.The finder methods are defined here within the deployment descriptor. Remember, entity Beans basically represent your data, and this is coming from a database. If you were doing a query on the database, you would use SQL. Because the container does all the database interaction when using CMP, you somehow need to inform the container what kind of query to execute. In EJB 1.1, this was done in a vendor-specific way. In EJB 2.0, there is a new query language called EJB QL. It is very similar to SQL. Each finder method is defined within the deployment descriptor with the following format:

Each finder method is defined within the XML using a <query> element.This element then consists of a <query-method> and an <ejb-ql> element.The <query-method> contains the name of the method from the home interface along with any parameters, and the <ejb-ql> element contains the query that the finder method corresponds to. This query language does appear a little cryptic, but essentially the queries can contain three types of clause: SELECT, WHERE, and FROM.The OBJECT is the instance, and (a)is a variable declared that can be used to refer to the instance.The ?1 syntax should look familiar as it refers to the first parameter. It is also used in JDBC for prepared statements. The previous query states the following: Select all the CompactDiscBean instances where the title of the Bean is the value of the String parameter passed in. A detailed description of EJB QL can be found as a part of the specifications for EJB2.0, at Communityprocess/final/jsr019/index.html. The second part of the deployment descriptor is the <assembly-descriptor>.This informs the container how transactions should be managed for the various methods involved. In the example we have, all the methods are set to require a transaction.The use of the * denotes all methods:

The Deployment Folder Structure

We have seen a number of classes, interfaces, and now, a deployment descriptor, but where do we put all these files? There is a standard layout that J2EE applications often adhere to, just as we have seen for Web applications. An example J2EE folder structure is shown in Figure .

J2EE application folder structure.

J2EE application folder structure.

The folder structure shown in Figure is for a complete J2EE application.The toplevel folder has been called jsphandbook.This will be the name of our application.The beans folder contains all the EJB deployment information and the EJB classes.The webapp folder will contain all the Web application structure, and the META-INF folder will contain another deployment descriptor, application.xml, which will be discussed later. For now, you only need to look at the top half of Figure , the folder structure underneath the beans folder.

Deployment in WebLogic

We now need to look at the vendor-specific deployment information. As stated earlier, we will be using BEA WebLogic 7. For WebLogic, we’ll require two additional deployment descriptors, and we will need to configure WebLogic to work with our MySQL database because this contains the compact_discs table.

The two deployment descriptors for WebLogic are shown in Listing .


This deployment descriptor describes the entity Bean to WebLogic. It informs WebLogic about the kind of persistence being used, and also has a <type-storage> element.This points to the other WebLogic-specific deployment descriptor, and this contains the mappings between the CMP fields of the Bean, and the actual datasource.This is shown in Listing .

Listing weblogic-cmp-rdbms-jar.xml

This deployment descriptor maps all the entity Bean fields to individual columns in the database. In Chapter 14, we demonstrated how to set the data source up in WebLogic 7. In fact, Listing 15.7 relates directly to the data source.As you can probably appreciate, the building and deployment of EJBs can be a very tedious process, and increasingly, tools exist to aid you in their completion.Tools such as JBuilder Enterprise Edition or IBM Visual Age for Java both have utilities to help in the creation of these deployment files. Even some application server vendors themselves provide visual tools to help you to create these XML files.

Deploying the EJBs with the Web Application

A JavaServer Page can be used to interact with an EJB, but we have not seen how to deploy a complete J2EE application with both the EJBs and the JSPs together. Revisit Figure, and remind yourself how a J2EE application fits together.You have seen how a Web application is deployed with the web.xml deployment descriptor.You have seen how an EJB is built and then deployed with the ejbjar. xml deployment descriptor.You have also seen how the EJBs are deployed in WebLogic using the two WebLogic-specific deployment descriptors.To deploy them together as a J2EE application, the web.xml file is modified so that it knows about the EJBs, and one more deployment descriptor is created, application.xml. The web.xml deployment descriptor for our J2EE application is shown in Listing 15.8. If you look at the solution, you will also see additional entries. Don’t worry about those for now because they are discussed later.

Listing web.xml

You can see that the entity Bean is also referred to from web.xml. It has the <ejb-ref> element, which defines the EJB that is being used from our Web application. Most of it is self explanatory, but the <ejb-ref-name> and the <ejb-link> elements require some explanation.The <ejb-ref-name> element declares the JNDI name used by the JSP to locate the EJB, which it does if you look at the JSP line that locates the EJB, repeated here:

Object obj = context.lookup(“java:comp/env/ejb/CompactDisc”);

EJB lookups are always prefixed java:comp/env/. It is the last part of the lookup name that is determined by the <ejb-ref-name> element.The <ejb-link> element defines the name of the EJB that is being referred to, as defined in the ejb-jar.xml deployment descriptor.This <ejb-link> element is not mandatory however. You can see where application.xml goes from Figure below , and Listing below shows what it would look like for our J2EE application.

Listing application.xml

As you can see, it is nowhere near as complex as the other deployment descriptors. It describes each part of the application as a module, and specifies the folder in which it lives. So the Web application is in a folder called web-app, since the <web-uri> element has that value.The EJBs are in a folder called beans, and this is specified by the <ejb> element. Note that both the <web-uri> element and the <ejb> element could also refer to war files or jar files respectively.The <context-root> specifies the root folder of the application when visited through a Web interface, so with this value of jsphandbook, the URL for the JSP in Listing 15.1 in WebLogic would be http://<servername>:7001/jsphandbook/ejbClient.jsp We are almost there.To see the application working in WebLogic, you will need to put all the listings together in the directory structure shown in Figure below. I suggest that you put it directly under your <bea-install> directory for now, which is typically something such as c:bea. Don’t forget you can download the application from the book Web site ( to save some typing.

Running the J2EE Application

First, we will need to set up the connection pool and data source in WebLogic 7 for our application.This process is as follows. To set up WebLogic, you will need to complete the following steps:

  1. Install WebLogic 7 from. A typical install will be sufficient because this will include a very comprehensive set of examples. Detailed instructions for installation for your platform will be available on the BEA Web site. If you are using a Windows platform, it is a straightforward executable.
  2. Ensure that the .jar file containing the JDBC driver for MySQL is in the classpath for your machine. See the section called “Setting Up a JDBC Driver” in Appendix I,“Installing MySQL and WebLogic Server,” for more information.
  3. Start the WebLogic server with the examples.This can be done from the Start menu on Windows:
    Start / Programs / BEA WebLogic Platform 7.x /WebLogic Server 7 / Server Tour and Examples / Launch Examples Server
  4. This should result in the server starting in a console window, and then a browser showing you the home page for the WebLogic examples.This can be seen in Figure . From this page, launch the Administration Console via the hyperlink. This will open a page asking for a username and password (precompleted with weblogic/weblogic). Submit this form. If the browser does not start for whatever reason, you can launch one separately and navigate to the following URL:
    http://<servername>:7001/examplesWebApp/index.jsp.You will need to put your server name in the placeholder.The value localhost should suffice if the browser is running on the same machine as WebLogic.
  5. WebLogic examples server welcome page.

    WebLogic examples server welcome page.

  6. You should now be presented with the Administration Console for WebLogic, as shown in Figure below From here, select Connection Pools from the main screen, which is under the heading Services Configurations. It has been highlighted in Figure .
  7. WebLogic 7 administration console.

    WebLogic 7 administration console.

  8. Now you are in a position to create your own connection pool for the MySQL database. Select the option to Configure a New JDBC Connection Pool and a screen as shown in Figure appears.The URL, driver, and username information all have to be completed on this page.The values are:
  9. Driver Classname: com.mysql.jdbc.Driver Properties: user=root
  10. After the connection pool is set up, click the Targets tab, as shown in Figure , and select the examplesServer from the available list and move it over to the chosen server.This will make your connection pool available to the examples server. If any errors occur at this point, double-check that the MySQL driver classes are in the classpath. Also check that your URL and driver name are completed correctly.
  11. You are nearly done! You can now create a DataSource that uses your new connection pool. Go back to the main page, which is shown in Figure below, and select TX DataSources from the menu this time.You can also navigate to this from the left applet–based menu.
  12. Configure a new JDBC connection pool.

    Configure a new JDBC connection pool.

  13. From the page showing the XA DataSources, select that you want to Configure a New XA Datasource. Provide the name MySQLDataSource.
  14. Now set up the data source, as shown in Figure . It is very important that the name you provide for the connection pool is the same as the name you provided when you created the connection pool.
  15. Now click the Targets tab again, as you did for the Connection Pool, and choose the examplesServer. If this gives any errors, it’s probably because the names are not completed correctly; most importantly the connection pool name must match.

After you have done that, it is time to run the application in WebLogic (at last)! Within the Administration Console, select the Applications link, which is under the heading Your Deployed Resources, and then choose the option to Configure a New Application. Assuming that you created your J2EE application in a folder called jsphandbook, directly under your <bea-install> folder, then navigate to it, and click the [select] button next to it.This can be seen in Figure .

Configure a new XA DataSource.

Configure a new XA DataSource.

Deploying the J2EE application in WebLogic

Deploying the J2EE application in WebLogic

After you have clicked [select] for the jsphandbook folder, you will be able to activate it on your target server, which is the examplesServer. Do this now, leaving the name in Step 4 unchanged, and then select the Configure and Deploy button in Step 5. See Figure .

Configure and Deploy in WebLogic.

Configure and Deploy in WebLogic.

Figure is a full screen browser view, and you can see the appropriate settings filled in already.You should now have a screen informing you that the application is deployed.

You should see a basic Web page showing all the CDs. If you are having problems, carefully revisit the steps above to ensure that you have done everything correctly.Any stack traces in the WebLogic console provide vital clues as to what you may have done incorrectly.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

JSP Topics