HomeDocumentation > Developer's guide > Tutorials > EJB applications > Bean Managed Persistence with JPA

The Java Persistence API is a new programming model under EJB3.0 specification (JSR220) for the management of persistence and object/relational mapping with Java EE and Java SE. With JPA, developers can easily develop java applications that perform operations on relational database management systems using java objects and mapping. In that way, java applications developed using JPA are not only portable across different platforms, but also applications can be easily developed using simple yet powerful programming model provided by JPA. This greatly improves application maintainability against ever changing database world. JPA insulates applications from all the complexity and non-portable boilerplate code involved in database connectivity and operations.

Apache geronimo uses OpenJPA for providing Java Persistence API to Java EE applications deployed in the server. Even though JPA is a part of EJB3.0 spec, it is independent of it. Hence, JPA can be used in JavaSE, web and ejb applications in the same uniform way.

Below tutorial illustrates the use of application managed entity manager object. The EntityManager object is created from EntityManagerFactory. The EntityManagerFactory object is injected by the container when @PersistenceUnit(unitName="<PersistentUnitName>") annotation is used. The persistence context of the entity manager is not propagated along with any transaction that is currently active. If the transaction spans across components, all the entity manager object references that point to same persistence unit will have a different persistence context. Thus, any changes made to the entities through any entity manager reference, are not seen through other entity manager references. The persistence scope of the application managed entity manager is Extended by default. The transaction-type can be either JTA or RESOURCE_LOCAL. If the transaction-type is JTA the EntityManager can join the transaction by calling joinTransaction() method. The transaction-type of RESOURCE_LOCAL is used in when the EntityManager is not interested to join the global transaction. This is typically used in non-JEE environments. In summary, the life cycle of the entity manager and the associated persistence context is not managed the container. It is the application's responsibility to close the EntityManager object explicitly. The persistence context spans beyond transactions by default.

The tutorial creates an enterprise application that has an ejb module and a web module. The ejb module uses Account entity and Person entity. The Account entity has accountNumber, personId and balance attributes. The Person entity has personId, personName and address attributes. The personId in Account entity refers to personId in Person entity. The AccountBean injects EntityManagerFactory from which it creates EntityManager object. It is a stateful session bean which has Account entity object, corresponding Person entity object, EntityManager object and EntityManagerFactory object as state fields. The bean has updateAllValues(String address, String personName, double balance) method that updates Account and Person entity attributes. It has also deposit(double amount) and withdraw(double amount) methods for withdrawing and depositing the amounts to the account. In all the above mentioned methods, the EntityManager object joins the active transaction using joinTransaction() method as the its transaction-type is JTA and bean's transaction is managed by the container. The initialize(integer accountNumber) initializes the bean with Account and Person entity objects corresponding to the accountNumber sent as the parameter. Finally, the EntityManager object is closed in the destroy() method.

The web module allows user to update the Account entity and Person entity attributes and transfer amount from one account to another using AccountBean. The RetrieveAccount.jsp performs update and the TransferAmount.jsp performs transfer of amount in a JTA transaction.

In order to develop, deploy and run the application, the following environment is required.

  • Sun JDK 5.0+ (J2SE 1.5)
  • Eclipse 3.3.1.1 (Eclipse Classic package of Europa distribution), which is platform specific
  • Web Tools Platform (WTP) 2.0.1
  • Data Tools Platform (DTP) 1.5.1
  • Eclipse Modeling Framework (EMF) 2.3.1
  • Graphical Editing Framework (GEF) 3.3.1

The tutorial is divided into the following sections.

  • Setting the Eclipse environment
  • Creating ejb application with entities
  • Creating web application
  • Setting up the database tables and the Datasource.
  • Deploying the (ear) application
  • Running the application

The entire application can be downloaded from this link.

Setting the Eclipse environment

1. Download Apache Geronimo2.1 and install it on the server. Look into the geronimo documentation for
instructions.

2. Install the eclipse IDE and download geronimo eclipse plugin and install it on top of eclipse. Look into the
geronimo eclipse plugin documentation for instructions.

3. Create a runtime environment for Apache Geronimo2.1 in the eclipse. Look into the geronimo eclipse plugin
documentation for instructions to install a runtime for Apache Geronimo2.1.

Creating ejb application with entities

1. Open the eclipse tool and change the perspective to Java EE by clicking on
Windows => Open Perspective => Other. It will open up Open Perspective wizard. Select Java EE from the
list and click OK button.

2. Right click on the Package Explorer and select EJB Project.

3. This will open up the New EJB Project wizard. Provide the values for Project Name, Target Runtime as given in the screen shot below. Click on Next button.

If target runtime is not setup, create a new target runtime pointing to geronimo installation directory. For more information, look at the geronimo documentation that explains setting up eclipse plugin for geronimo and setting up runtime environment. This setup is required to resolve class dependencies during compilation.

4. Select the check boxes as given in the screen shot below and click on the Next button.

5. Select the checkboxes as given in the below screen shot and click on the Next button.

6. Provide the following values in textboxes and click on the Finish button.

7. Right click on the BeanManagedJPA-EJB project and navigate to New => Class option. Provide the
following values in the New Java Class wizard and click on Finish button.

8. Copy the following contents into Account.java.

Account.java

9. Similarly, as given in the previous step, create Person.java and add the following contents to it.

Person.java

9. Similarly, create AccountInterface.java and copy the following contents.

AccountInterface.java

10. Similarly, create AccountBean.java.java and copy the following contents.

AccountBean.java

11. As outlined above, right click on the META_INF directory of BeanManagedJPA-EJB project and
create persistence.xml. Copy the following contents into persistence.xml.

persistence.xml

12. Since we are going to use EJB annotations, the META-INF/ejb-jar.xml will not have any declarations. The contents of the META-INF/openejb-jar.xml file should be as below. Otherwise, modify it accordingly.

openejb-jar.xml

13. Finally the project BeanManagedJPA-EJB should like as below.

Creating web application

1. Right click on the Project Explorer and select New => Project. This will popup New Project wizard.
Select Dynamic Web Project under option Web. Click on the Next button.

2. Provide the values as given in the screen shot below on the New Dynamic Web Project wizard. Please note that Add project to an EAR checkbox is check to add this web project to BeanManagedJPA-EAR created during the creation of BeanManagedJPA-EJB project.

3. In the next screen, select the Version values as given in the below figure and click on the Next button.

4. Check on the Generate Deployment Descriptor checkbox and click on the Next button. On the next screen, configure the deployment plan as follows. After this, click on the Finish button to complete creating web project

5. Right click on the WebContent folder of the web project and navigate to New => HTML to create the index.html file as given in the screen shot. Click on the Next button and on the next screen click on the Finish button. The contents of the index.html is provided below the screen shot.

index.html

6. Right click on the WebContent folder of the web project and navigate to New => HTML to create the ViewAccount.html file as given in the screen shot. Click on the Next button and on the next screen click on the Finish button. The content of the ViewAccount.html is provided below the screen shot.

ViewAccount.html

9. Similarly, as illustrated in the previous steps, create RetrieveAccount.jsp. The contents of the of the jsp is as follows.

RetrieveAccount.jsp

10. Similarly, as illustrated in the previous steps, create TransferAmount.jsp. The contents of the jsp is as follows.

TransferAmount.jsp

11. Right click on the BeanManagedJPA-WEB project and click on Properties to open Properties for BeanManagedJPA-WEB wizard. Click on the Java Build Path and Projects tab. Click on the Add button and add BeanManagedJPA-EJB project. Finally, click on the OK button on Properties for BeanManagedJPA-WEB wizard. This is required because, BeanManagedJPA-WEB projects looks up AccountInterface ejb in the BeanManagedJPA-EJB project. To resolve the dependency during compilation, the EJB project has to be added to the build path of the WEB project.

Setting up the database tables and the Datasource

1. Start the geronimo server and open the admin console on a browser window with the url
http://localhost:8080/console.

2. Click on the Embedded DB => DB Manager on the Console Navigation portlet.

3. On the Run SQL portlet on the right side, enter AccountDB in the Create DB textbox and click on the
Create button.

4. The above step will create AccountDB database. On the same screen, enter the below SQL command on the SQL Command/s textarea and select AccountDB in the Use DB combo box and click on the Run SQL button. This will create ACCOUNTCME table in the AccountDB database.

5. Similarly, enter the below SQL command on the SQL Command/s textarea and select AccountDB in the Use DB combo box and click on the Run SQL button. This will create PERSONBME table in the AccountDB database.

6. Insert the two rows using the below SQL command.

After inserting the rows, table will look like the below screen shot.

7. We need to deploy datasource over AccountDB database for JPA. This datasource will be used by JPA to connect to database and perform DML operations. Admin console can be used to deploy a datasource over AccountDB. Click on the services => Database Pools in the Console => Navigation portlet. This will display the list of database pools currently running in the server.

8. Click on the Using the Geronimo database pool wizard link. This will open up the Database pools portlet as follows. Provide the value for Name of the Database pool as AccountDS and select Derby embedded as below and click on the Next button.

9. On the next screen, select the JAR file listed in the Driver JAR select box and provide AccountDB as the value for Database Name and click on the Deploy button at the bottom. This will deploy the data source and display the list of datasources currently deployed on the server.

10. In the eclipse, open the openejb-jar.xml and provide the dependency to the AccountDS. Finally, the openejb-jar.xml should be as below. This configuration is already done in the step 12 of Creating ejb application with entities above.

Deploying the (ear) application

1. Deploy the EAR file as follows

C:\Geronimo-2.1\bin>deploy.bat --user system --password manager deploy c:\temp\BeanManagedJPA-EAR.ear
Using GERONIMO_BASE:   C:\Geronimo-2.1
Using GERONIMO_HOME:   C:\Geronimo-2.1
Using GERONIMO_TMPDIR: var\temp
Using JRE_HOME:        C:\SDK-May-31-2007\jre
    Deployed default/BeanManagedJPA-EAR/1.0/car
      `-> BeanManagedJPA-WEB.war @ /BeanManagedJPA-WEB
      `-> BeanManagedJPA-EJB.jar

Running the application

1. Open a browser window and hit the URL as http://localhost:8080/BeanManagedJPA-WEB/. This brings upthe screen shot below. Click on the View Account Details link.

2. On this page, enter 10 in the Account Number text box as below and click on the button

3. This will bring up the screen shot below. You can update the Person Name, Address and Balance values.

4. Enter the values given in the screen shot below and click on the Update button.

5. Once the Update button is pressed, the below screen shot is displayed with the updated values. Click on the Cancel button to go back to the main page.

6. Click on the Transfer Amount link on the main page. This will bring up the page as given in the screen shot below. Enter the values for Debit Account Number, Credit Account Number and Amount to be Transferred as given in the screen shot and click on the Transfer button. This will transfer the specified amount from debit account to the credit account. You can verify this either in the database or use the View Account Details link shown earlier.