Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Anchor
top
top

This article will help you migrate applications using Hibernate 3.2 3.1 as the ORM tool from JBoss Application Server 4.2.1 to Apache Geronimo 2.01.4.

Hibernate is a powerful, high performance object/relational persistence and query service. It helps in the development of persistent (POJO) classes which have the getter and setter methods for attributes that are then mapped to fields in the database. You may follow object-oriented idiom - including association, inheritance, polymorphism, composition, and collections. Hibernate allows you to express queries in its own portable SQL extension (HQL), as well as in native SQL, or with an object-oriented Criteria and Example API.

...

This article is organized in the following sections:

Back to Top

Hibernate implementation analysis
Anchor
implementation
implementation

Hibernate can provide the following services:

...

Feature

Apache Geronimo v2.0

JBoss v4.2.1

Container-managed datasource

Supported. Hibernate is able to use a datasource given its JNDI name. This is because it is running in the same thread as the application.

Supported. Hibernate can lookup a datasource from JNDI given its JNDI name.

Automatic JNDI binding

Not Supported.

Supported. Once the property is set the session factory is bound to the JNDI context.

JTA Session binding

This feature is not supported out of the box. We need to write a lookup for the Geronimo Transaction Manager to enable this.

Supported out of the Box. Hibernate provides a lookup class for the JBoss Transaction Manager.

JMX deployment

Not Supported out of the box. Can be implemented by writing a GBean and a Hibernate Connection Provider class.

Supported. Hibernate is distributed with org.hibernate.jmx.HibernateService which can be deployed on JBoss.

Hibernate Archive (HAR)

Not Supported. Hibernate classes are deployed as a part of the J2EE archives.

Supported. A HAR packages the configuration and mapping files enabling extra server support to deployment.

Caching

You can use caching mechanisms provided by hibernate.

You can use caching mechanisms provided by hibernate. Integration with JBoss Cache is also supported.

Session Management

Not Supported. It is required to manually open sessions. Only the transaction needs to be closed.

The Hibernate Session's lifecycle can be automatically bound to the scope of a
JTA transaction. This means you no longer have to manually open and close the Session, this becomes the job of a JBoss EJB interceptor.

Hibernate Mapping Files

We need to specify the locations of the Hibernate mapping files.

If we use HAR deployment JBoss will automatically lookup the Hibernate mapping files.

Back to Top

Sample application
Anchor
sampleApp
sampleApp

This article contains a sample application to demonstrate migrating an application from JBoss to Geronimo, called Online Brokerage . It represents an online trading scenario in which users can buy and sell stocks. The application has the following five pages:

...

The following figure illustrates the application flow:
First, the user accesses the Login page. From the Login page the user enters the user name and password. If the user name or password is not valid the application throws an error message and rejects the user's login attempt. If the user name and password are correct, the user is taken to the Available Stocks page where he/she can view all the stocks that are present for sale at that time.
The user can choose to buy as many stocks as wanted, depending on the available money in the account, by clicking the Buy button. After the transaction completes successfully the user is brought back to the Available Stocks page where he/she can buy more stocks if required. If the user has insufficient funds to buy stocks the application will throw an error and will not process the transaction. The error message is shown at the top of the Available Stocks page. There is a User Info button on this page. By clicking this button the user is taken to the User Info page and shown the user details.
From the Available Stocks page there is a View your Portfolio link that shows all the stocks that the user owns. In that page, the user can select the stocks and quantity to sell. This page also shows the user's available cash in the User Cash field. If the user tries to sell more stocks than he/she has, the application will throw an error. The error message will be displayed on the same page. For each successful sale, the sale amount is added to the user's cash balance. The quantity text box shows the quantity of stocks of a particular company that the user has. The Quantity to Sell field allows the user to enter the quantity of stocks to sell for a specific company. For selling and buying, the radio button should be checked. This should be done after entering the values. If either the quantity to sell textbox is not filled or the selection box is not checked and you press on sell a JavaScript alert will be triggered saying that the required field is empty. On entering non numeric characters for quantity another alert will be triggered. This behavior is similar for the Available Stocks page as well.
New users can register by clicking the Register button in the login page. In the Registration page the user will enter a user id, user name, password, address and available cash.
Back to Top

Application classes and JSP pages

The Online Brokerage sample application consists of the following packages:

...

  • login.jsp - The login page of the application.
  • error.jsp - The default error page of the application.
  • register.jsp - The user registration page.
  • stocks.jsp - The Available Stocks page from where the user can buy stocks.
  • userstocks.jsp - The user portfolio page which shows the user's stocks. The user can sell stocks from this page.

Back to Top

Tools used

The tools used for developing and building the sample application are:

Apache Ant

Ant is a pure Java build tool. It is used for building the war files and populating the database for the Online Brokerage application. Ant can be downloaded from the following URL:

http://ant.apache.org

Hibernate

At the time of writing this article, Hibernate 3.2 is the latest version available and can be downloaded at the following URL:
http://www.hibernate.org

...

Download and install Hibernate, the installation directory will be later referred as <hibernate_home>.

Back to Top

Sample database

The database used for demonstrating this application is MySQL. The sample database name is adi and it consists of the following three tables, STOCKS, USERS and USERSTOCKS. The fields for each of these tables are described below.

...

The DDL file used for populating this database is db.sql and it is located in the <brokerage_home>\sql directory.

Back to Top

The JBoss environment
Anchor
JBoss
JBoss

This section shows you how and where the sample JBoss reference environment was installed so you can map this scenario to your own implementation.

...

  1. Download and install JBoss v4.2.1 as explained in the product documentation guides. From now on the
    installation directory will be referred as <jboss_home>
  2. Create a copy of the default JBoss v4.2.1 application server. Copy recursively <jboss_home>\server\default to <jboss_home>\server\<your_server_name>
  3. Start the new server by running the run.sh -c <your_server_name> command from the <jboss_home>\bin directory.
  4. Once the server is started, you can verify that it is running by opening a Web browser and pointing it to this URL: http://localhost:8080. You should see the JBoss Welcome window and be able to access the JBoss console.
  5. Once the application server is up and running, the next step is to install and configure all the remaining prerequisite software required by the sample application. This step is described in the following section.

Install and configure prerequisite software

In order to build and run the Library application included in this article, you need to install and configure the build tool and the database that is used by the application.

Install the database

As mentioned earlier in the article, this application is using the MySQL database that can be downloaded from the following URL:

...

Note: During the instance configuration I modified the security settings and specified "password" as the password for the root user. This user ID and password will later be used for accessing the database from the sample application.

Create sample database

Once the MySQL instance is configured you need to create the sample database that will be used by the Library application. From a command line, type the following command to start the MySQL monitor:

...

mysql> create database adi;

Configure Ant

As mentioned before, Apache Ant is used to build the binaries for the Online Brokerage application. If you do not have Ant installed this is a good time for doing it and make sure that <ant_home>\bin directory is added to the system's path variable.

Apache Ant can be downloaded from the following URL:

http://ant.apache.org

Configure Hibernate

JBoss comes bundled with Hibernate so there is no need to download separate jars for hibernate.

Back to Top

Build the sample application

The Online Brokerage application included with this article provides an Ant script that you will use in order to build the application and populate the database. Download the sample application by cliking on Online Brokerage.

...

Code Block
xml
xml
borderStylesolid
titleweb.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>brokerage</display-name>
    <servlet>
        <display-name>Trade-Dispatcher</display-name>
        <servlet-name>TradeDispatcher</servlet-name>
        <servlet-class>com.dev.trade.servlet.TradeDispatcherServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>TradeDispatcher</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>TradeDispatcher</servlet-name>
        <url-pattern>/stocks</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>TradeDispatcher</servlet-name>
        <url-pattern>/userstocks</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>TradeDispatcher</servlet-name>
        <url-pattern>/buy</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>TradeDispatcher</servlet-name>
        <url-pattern>/sell</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>TradeDispatcher</servlet-name>
        <url-pattern>/register</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
  <welcome-file>/login.jsp</welcome-file>
    </welcome-file-list>
    <error-page>
     <exception-type>javax.servlet.ServletException</exception-type>
     <location>/error.jsp</location>
    </error-page>

    <resource-ref>
        <res-ref-name>jdbc/HibernateDB</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
        <res-sharing-scope>Shareable</res-sharing-scope>
    </resource-ref>
</web-app>

Back to Top

Populate sample data

As we mentioned before, the db.sql script is provided to populate the sample data. The location of this file is already defined in the build.properties by the tag sql.file. To populate the sample data simply run the following command from the <brokerage_home> directory.

ant populateDB

Back to Top

Deploy the sample application

Before you deploy the sample application you need to configure the datasource required by this application. To deploy the datasource configuration in JBoss copy the mysql-ds.xml file located in the <brokerage_home>\plan directory to the following directory:

...

If JBoss is already started, it will automatically deploy and start the application; otherwise, the application will be deployed and started at the next startup.

Back to Top

Test the sample application

To test the application, open a Web browser and access the following URL:

...

This brings up the login screen of the Online Brokerage application. Enter j2ee as the user name and password as the password and click on login. This takes you to the available stocks page illustrated in the following figure. The application is now configured and running.
Back to Top

The Geronimo environment
Anchor
Geronimo
Geronimo

Download and install Geronimo from the following URL:

...

The release notes available there provide clear instructions on system requirements and how to install and start Geronimo. Throughout the rest of this article we will refer to the Geronimo installation directory as <geronimo_home>.

Back to Top

Configure Resources

For running the Online Brokerage application in Geronimo, you will be using the same MySQL database that was used with JBoss. So the first task you need to do in order to prepare the Geronimo environment is to configure the data source.

Configure the datasource

You need to copy the MySQL database driver into the Geronimo repository so that you can refer to it in the data source deployment plan. The Geronimo repository is located in the <geronimo_home>/repository directory. Inside this directory, create a new directory called mysql/jars and copy the mysql-connector-java-3.1.14-bin.jar file into it.

...

No Format
bgColor#FFFFFF
borderStylesolid
C:\geronimo-2.0\bin>deploy --user system --password manager deploy \brokerage\plan\mysql-geronimo-plan.xml
..\repository\org\tranql\tranql-connector-ra\1.3\tranql-connector-ra-1.3.rar
    Deployed user/database-pool-HibernateDS/2.0/car

 

Back to Top

Step-by-step migration
Anchor
migration
migration

Apache Geronimo does not support HAR archives so we will be having all the classes inside a WAR archive. We need to write two classes for making the application work on Geronimo. One is a TransactionManagerLookup class for Geronimo and the other is a utility class HibernateUtil to get the SessionFactory. In addition to this we will need to make some changes to the TradeDispatcherServlet and TradeDAO classes.

As a first step we will see the changes that need to be made to the application as illustrated in the following list.

#TradeDAO
#HibernateUtil
#TradeDispatcherServlet

TradeDAO
Anchor
TradeDAO
TradeDAO

In JBoss the HibernateMBean will create and bind the SessionFactory to the Global JNDI Context. So we can obtain the SessionFactory through a simple lookup. We can then get the session from the SessionFactory.

...

This difference in obtaining the session will be the main change in the codebase for the application to run in Apache Geronimo.

HibernateUtil
Anchor
HibernateUtil
HibernateUtil

As mentioned above we will use this class to create the SessionFactory and provide the application with Hibernate sessions. The source code for the class is given below

...

HibernateUtil.java is located in the <brokerage_home>/src/com/dev/trade/util directory. For your convenience, a copy of this file is already provided with the sample application.

TradeDispatcherServlet
Anchor
TradeDispatcherServlet
TradeDispatcherServlet

In this class there will also be a difference in getting the SessionFactory. In JBoss we get it from the JNDI Context but in Geronimo we will get it through the utility class.

...

Code Block
java
java
borderStylesolid
titleGeronimoTransactionManagerLookup
package org.hibernate.transaction;

import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

import javax.transaction.TransactionManager;
import org.hibernate.HibernateException;
import org.hibernate.transaction.TransactionManagerLookup;

import org.apache.geronimo.gbean.AbstractName;
import org.apache.geronimo.gbean.AbstractNameQuery;
import org.apache.geronimo.kernel.Kernel;
import org.apache.geronimo.kernel.KernelRegistry;
import org.apache.geronimo.kernel.proxy.ProxyManager;

public class GeronimoTransactionManagerLookup implements
        TransactionManagerLookup {

    public Object getTransactionIdentifier(Transaction arg0) {
		return null;
    }

    public static final String UserTransactionName = "java:comp/UserTransaction";

    public TransactionManager getTransactionManager(Properties props) throws HibernateException {
       /*
         * try { Kernel kernel = KernelRegistry.getSingleKernel(); ProxyManager
         * proxyManager = kernel.getProxyManager(); AbstractNameQuery query =
         * new AbstractNameQuery(TransactionManager.class.getName()); Set names =
         * kernel.listGBeans(query); AbstractName name = null; for (Iterator it =
         * names.iterator(); it.hasNext();) name = (AbstractName) it.next();
         * Object transMg = (Object) proxyManager.createProxy(name,
         * TransactionManager.class); return (TransactionManager)transMg; }catch
         * (Exception e) { e.printStackTrace(); System.out.println(); throw new
         * HibernateException("Geronimo Transaction Manager Lookup Failed", e); }
         */
       try {
       Kernel kernel = KernelRegistry.getSingleKernel();
       AbstractNameQuery query = new AbstractNameQuery(TransactionManager.class.getName ());
       Set<AbstractName> names = kernel.listGBeans(query);
       if (names.size() != 1) {
           throw new IllegalStateException("Expected one transaction manager, not " + names.size());
       }
       AbstractName name = names.iterator().next();
       TransactionManager transMg = (TransactionManager)
       kernel.getGBean(name);
       return (TransactionManager)transMg;
       } catch (Exception e) {
           e.printStackTrace();
           System.out.println();
           throw new HibernateException("Geronimo Transaction Manager Lookup Failed", e);
       }
   }

    public String getUserTransactionName() {
        return UserTransactionName;
    }
}

...

The <hidden-classes> element is for preventing certain classes that come with Apache Geronimo from being visible to the war classloader which may result in version problems.

Back to Top

Build the migrated sample application

To build the application run the following commands

  • Add the hibernate jar to the classpath. You will now need to build hibernate with the GeronimoTransactionManagerLookup class. If you have not downloaded the hibernate source you can compile the class after putting the hibernate jar in the classpath and then manually add that class to the hibernate jar file.
    set CLASSPATH=%CLASSPATH%;<hibernate_home>/lib/hibernate3.jar
  • Add the Geronimo kernel to your classpath
    set CLASSPATH=%CLASSPATH%;<geronimo_home>/lib/geronimo-kernel-2.01.14.jar
  • To add the class manually, although not needed for this particular sample, you can use the tool of your preference and add the GeronimoTransactionManagerLookup.class to the org\hibernate\transaction directory in the hibernate_home>/lib/hibernate3.jar file.

...

The <brokerage_home>/solutions directory has the source files already migrated to compile for and run in Apache Geronimo.

Back to Top

Deploy the migrated sample application

To deploy the migrated Online Brokerage application, make sure the Geronimo server is up and running and run the following command:

...

Login with the same user name and password you used when testing the application from JBoss.

Back to Top

Summary
Anchor
summary
summary

This article has shown you how to migrate a sample application that uses Hibernate as its O/R mapping layer, from JBoss to the Apache Geronimo application server. Some of the features/functionalities already provided by JBoss may not yet be implemented in Geronimo, as a consequence some minor additional coding may be required but the overall migration complexity is low.

Back to Top