Developing Applications with JBoss and Hibernate: Part 1

JBoss AS 5 Development

December 2009


Develop, deploy, and secure Java applications on this robust, open source application server

Introducing Hibernate

Hibernate provides a bridge between the database and the application by persisting application objects in the database, rather than requiring the developer to write and maintain lots of code to store and retrieve objects.

The main configuration file, hibernate.cfg.xml, specifies how Hibernate obtains database connections, either from a JNDI DataSource or from a JDBC connection pool. Additionally, the configuration file defines the persistent classes, which are backed by mapping definition files.

This is a sample hibernate.cfg.xml configuration file that is used to handle connections to a MySQL database, mapping the com.sample.MySample class.

<property name="connection.username">user</property>
<property name="connection.password">password</property>
<property name="connection.url">
<property name="connection.driver_class">
<property name="dialect">
<mapping resource="com/sample/MyClass.hbm.xml"/>

From our point of view, it is important to know that Hibernate applications can coexist in both the managed environment and the non-managed environment. An application server is a typical example of a managed environment that provides services to hosting applications, such as connection pooling and transaction.

On the other hand, a non-managed application refers to standalone applications, such as Swing Java clients that typically lack any built-in service.

In this article, we will focus on managed environment applications, installed on JBoss Application Server. You will not need to download any library to your JBoss installation. As a matter of fact, JBoss persistence layer is designed around Hibernate API, so it already contains all the core libraries.

Creating a Hibernate application

You can choose different strategies for building a Hibernate application. For example, you could start building Java classes and map files from scratch, and then let Hibernate generate the database schema accordingly. You can also start from a database schema and reverse engineer it into Java classes and Hibernate mapping files. We will choose the latter option, which is also the fastest. Here's an overview of our application.

In this example, we will design an employee agenda divided into departments. The persistence model will be developed with Hibernate, using the reverse engineering facet of JBoss tools. We will then need an interface for recording our employees and departments, and to query them as well.

The web interface will be developed using a simple Model-View-Controller (MVC) pattern and basic JSP 2.0 and servlet features.

The overall architecture of this system resembles the AppStore application that has been used to introduce JPA. As a matter of fact, this example can be used to compare the two persistence models and to decide which option best suits your project needs. We have added a short section at the end of this example to stress a few important points about this choice.

Setting up the database schema

The overall architecture of this system resembles the AppStore application that has been used to introduce JPA. As a matter of fact, this example can be used to compare the two persistence models and to decide which option best suits your project needs. We have added a short section at the end of this example to stress a few important points about this choice.

CREATE schema hibernate;
GRANT ALL PRIVILEGES ON hibernate.* TO 'jboss'@'localhost' WITH GRANT
CREATE TABLE `hibernate`.`department` (
`department_name` VARCHAR(45) NOT NULL,
PRIMARY KEY (`department_id`)
CREATE TABLE `hibernate`.`employee` (
`employee_name` VARCHAR(45) NOT NULL,
`employee_salary` INTEGER UNSIGNED NOT NULL,
`employee_department_id` INTEGER UNSIGNED NOT NULL,
PRIMARY KEY (`employee_id`),
CONSTRAINT `FK_employee_1` FOREIGN KEY `FK_employee_1` (`employee_
REFERENCES `department` (`department_id`)

With the first Data Definition Language (DDL) command, we have created a schema named Hibernate that will be used to store our tables. Then, we have assigned the necessary privileges on the Hibernate schema to the user jboss.

Finally, we created a table named department that contains the list of company units, and another table named employee that contains the list of workers. The employee table references the department with a foreign key constraint.

JBoss AS 5 Development

A new Eclipse project

Now start Eclipse. You don't have a specific project for Hibernate applications, so a utility project (which simply packs the classes in an archive) will be enough. You can reach this option from the menu by going to New | Other | Java EE | Utility Project.

JBoss AS 5 Development

Name the project HibernateProject and target it to JBoss AS 5.0 Runtime. You can leave the default JBoss AS configuration and hit Finish.

Now, we are going to unleash the full potential of Hibernate tools. Select from the menu New | Other | Hibernate | Hibernate Configuration File. The Hibernate configuration contains all of the details for wiring your application to the database. You will be asked for the name and the parent folder of the configuration file. Accept the default hibernate.cfg.xml at the root of your project.

JBoss AS 5 Development

Next, insert the details of your Hibernate configuration. Choose a name for your SessionFactory, which will contain your MySQL connection facets. Remember to check the flag Create a console configuration, so that the wizard will complete the console configuration as the next step.

JBoss AS 5 Development

A console configuration describes how the Hibernate plugin should interact with Hibernate and what configuration files (including the classpath) are needed to load the POJOs, JDBC drivers, and so on. This step is required to make use of query prototyping, reverse engineering, and code generation.

JBoss AS 5 Development

The console wizard will look at the current selection in the IDE and will try to autodetect the settings, which you can approve or modify to suit your needs. For example, you don't need to enter the Configuration file or the Property file if you have just one in your project; Eclipse will select it automatically.

One important selection is the Type option that lets you choose between the Core hibernate configuration (Java classes backed by mapping files), Annotations, or even JPA annotations. We will leave the selected Core option.

Before clicking Finish, select MySQL (InnoDB) as Database dialect in the Options tab. No other changes are required.

JBoss AS 5 Development

Now verify that you have successfully linked to Hibernate by switching to Hibernate Perspective. This view will be composed by a tree of three objects: Configuration, Session Factory, and Database. Choose Database and verify that it expands correctly to show the database tables of your schema.

JBoss AS 5 Development

If you fail to browse the database schema, check that you have correctly set up your Hibernate configuration.

Reversing your schema into Java classes

The next move will be reversing our database schema into Java classes and mapping files. This powerful feature is available from the menu: File | New | Hibernate | Hibernate Reverse Engineering file. You can place this file in a convenient location for your project and choose a name for it. The default name proposed is hibernate.reveng.xml, which looks rather the tile of another fiction movie from G. Lucas.

JBoss AS 5 Development

On the next page, select your Console configuration and choose the tables that will be included in your reverse engineering process. (Hint: You have to hit Refresh first to show the database schema and then click Include....)

JBoss AS 5 Development

What Eclipse has just created for you is a file named hibernate.reveng.xml that should resemble the following code snippet:

<table-filter match-catalog="hibernate" match-name="department"/>
<table-filter match-catalog="hibernate" match-name="employee"/>

If you are smart at noticing variations, you might have discovered a new icon in your toolbar. This is your gateway to the reverse engineering process. (Notice: this icon is visible only in the Hibernate Perspective, you will not be able to find it anywhere else.)

JBoss AS 5 Development

Click on Hibernate's down arrow icon and select Hibernate Code Generation Configurations. In the next dialog, you will first have to create a new Hibernate Code Generation Configuration that will contain all the details of your reverse engineering process. Click on the New button located in the left corner of the wizard.

JBoss AS 5 Development

Now, select your brand new configuration and carefully choose the following options. First, wire the Console configuration to your project (HibernateProject). Then, choose an output directory for your generated files. We would suggest you to point to your src folder. (Be aware that existing files will be overwritten, that's why I just said you have to be careful!)

Just below, you will find the checkbox Reverse engineer from JDBC Connection. If enabled, the tools will reverse engineer the available database using the connection information in the selected Hibernate Console configuration. Check this option and enter the package name for the generated classes, which will be com.packtpub.hibernate. Leave the other text fields to the defaults and move to the tab Exporters.

JBoss AS 5 Development

The Exporters tab menu is used to specify which type of code should be generated. Each selection represents an Exporter that is responsible for generating the code, hence the name.

In the upper area of the dialog, you will notice an interesting checkbox named Generate EJB 3 annotations. We will return to this useful option later. At the moment, what we need is just to check the Domain code and Hibernate XML Mappings options, which will generate the Java POJOs and mapping files respectively.

JBoss AS 5 Development

It took a bit of time to complete all of these steps; however, now your Java classes and configuration files are handy and waiting to be packaged.

Adding Hibernate configuration to your project

The advantage of embedding the Hibernate application in JBoss AS is that you can expose Hibernate SessionFactory through a JNDI tree and modify its configuration at runtime.

This is indeed a great configuration advantage; before the new release of JBoss AS, you had to delegate to an MBean the creation of the Hibernate SessionFactory and its exposure through JNDI.

For example, if you wanted to configure a SessionFactory at the naming context hibernate/SessionFactory, you would have to package your Hibernate application with a file named xxx-service.xml in the META-INF folder. Here's a sample of it:

<mbean code="org.jboss.hibernate.jmx.Hibernate"
<attribute name="DatasourceName">java:/ MySqlDS</attribute>
<attribute name="Dialect">
<attribute name="SessionFactoryName">
<attribute name="CacheProviderClass">

This configuration is still valid for pre 5.0 releases of JBoss AS. With the introduction of the new Virtual Deployment Framework (VDF), you now have to provide your SessionFactory configuration using the Hibernate XML schema. For example, if you want to link your SessionFactory to your MySQL database, you have to add the following service-hibernate.xml. (Be aware, the suffix is -hibernate.xml and not –service.xml.)

<hibernate-configuration xmlns="urn:jboss:hibernate-deployer:1.0">
<session-factory name="java:/hibernate/SessionFactory"
<property name="datasourceName">java:/MySqlDS</property>
<property name="dialect">

The preceding configuration file needs to be stored in the META-INF folder of your Hibernate archive (HAR) file. The structure of the updated project from the Package Explorer is as shown in the following snapshot:

JBoss AS 5 Development

In the next part we will a web client to the project, package and deploy the application, generate EJB 3 using the wizard and compare the Hibernate framework with the JPA persistence standard, showing how the two technologies can be coupled in a single application.

>> Continue Reading: Developing Applications with JBoss and Hibernate - Part 2

[ 1 | 2 ]


If you have read this article you may be interested to view :

Books to Consider

comments powered by Disqus

An Introduction to 3D Printing

Explore the future of manufacturing and design  - read our guide to 3d printing for free